diff --git a/backend/chaturbate_autostart.go b/backend/chaturbate_autostart.go index bda50c9..7d792de 100644 --- a/backend/chaturbate_autostart.go +++ b/backend/chaturbate_autostart.go @@ -1,3 +1,5 @@ +// backend\chaturbate_autostart.go + package main import ( @@ -45,6 +47,7 @@ func cookieHeaderFromSettings(s RecorderSettings) string { if err != nil || len(m) == 0 { return "" } + keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) @@ -52,18 +55,25 @@ func cookieHeaderFromSettings(s RecorderSettings) string { sort.Strings(keys) var b strings.Builder - for i, k := range keys { + first := true + + for _, k := range keys { v := strings.TrimSpace(m[k]) + k = strings.TrimSpace(k) if k == "" || v == "" { continue } - if i > 0 { + + if !first { b.WriteString("; ") } + first = false + b.WriteString(k) b.WriteString("=") b.WriteString(v) } + return b.String() } @@ -82,7 +92,9 @@ func resolveChaturbateURL(m WatchedModelLite) string { // Startet watched+online(public) automatisch – unabhängig vom Frontend func startChaturbateAutoStartWorker(store *ModelStore) { if store == nil { - fmt.Println("⚠️ [autostart] model store is nil") + if verboseLogs() { + fmt.Println("⚠️ [autostart] model store is nil") + } return } @@ -213,9 +225,13 @@ func startChaturbateAutoStartWorker(store *ModelStore) { Cookie: cookieHdr, }) if err != nil { - fmt.Println("❌ [autostart] start failed:", it.url, err) + if verboseLogs() { + fmt.Println("❌ [autostart] start failed:", it.url, err) + } } else { - fmt.Println("▶️ [autostart] started:", it.url) + if verboseLogs() { + fmt.Println("▶️ [autostart] started:", it.url) + } lastStart = time.Now() } } diff --git a/backend/chaturbate_online.go b/backend/chaturbate_online.go index 9ce77fd..239c6ca 100644 --- a/backend/chaturbate_online.go +++ b/backend/chaturbate_online.go @@ -261,7 +261,7 @@ func startChaturbateOnlinePoller(store *ModelStore) { fmt.Println("✅ [chaturbate] online rooms fetch recovered") lastLoggedErr = "" } - if len(rooms) != lastLoggedCount { + if verboseLogs() && len(rooms) != lastLoggedCount { fmt.Println("✅ [chaturbate] online rooms:", len(rooms)) lastLoggedCount = len(rooms) } diff --git a/backend/data/models_store.db-shm b/backend/data/models_store.db-shm index 6f99d03..bf78d88 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 88460f9..ad58aab 100644 Binary files a/backend/data/models_store.db-wal and b/backend/data/models_store.db-wal differ diff --git a/backend/log_policy.go b/backend/log_policy.go new file mode 100644 index 0000000..3feacec --- /dev/null +++ b/backend/log_policy.go @@ -0,0 +1,99 @@ +// backend/log_policy.go +package main + +import ( + "context" + "errors" + "os" + "strings" +) + +// Optional: Verbose nur wenn du es explizit willst (z.B. beim Debuggen) +func verboseLogs() bool { + return os.Getenv("REC_VERBOSE") == "1" +} + +func shouldLogRecordError(err error, provider string, req RecordRequest) bool { + if err == nil { + return false + } + + // "STOP" / Cancel ist normal -> kein Fehlerlog + if errors.Is(err, context.Canceled) { + return false + } + + msg := strings.ToLower(err.Error()) + + // --- Chaturbate: Cookie/Auth/CF-Probleme IMMER loggen (auch bei Hidden) --- + if provider == "chaturbate" { + // deine explizite Cookie-Fehlermeldung + if strings.Contains(msg, "cf_clearance") && strings.Contains(msg, "cookie") { + return true + } + // typische Auth/CF/Blocker-Indikatoren + if strings.Contains(msg, "403") || strings.Contains(msg, "401") || + strings.Contains(msg, "cloudflare") || strings.Contains(msg, "cf") || + strings.Contains(msg, "captcha") || strings.Contains(msg, "forbidden") { + return true + } + } + + // --- harte Config/IO-Fehler (immer loggen) --- + if strings.Contains(msg, "recorddir") || + strings.Contains(msg, "auflösung fehlgeschlagen") || + strings.Contains(msg, "permission") || + strings.Contains(msg, "access is denied") || + strings.Contains(msg, "read-only") { + return true + } + + // --- erwartbare "Provider/Offline"-Situationen: NIE loggen --- + // unsupported provider + if strings.Contains(msg, "unsupported provider") { + return false + } + + // Chaturbate offline/parse/watch-segments end + if strings.Contains(msg, "kein hls") || + strings.Contains(msg, "room dossier") || + strings.Contains(msg, "keine neuen hls-segmente") || + strings.Contains(msg, "playlist nicht mehr erreichbar") || + strings.Contains(msg, "möglicherweise offline") || + strings.Contains(msg, "stream vermutlich offline") { + return false + } + + // MFC: "nicht public"/offline/private/not exist + if strings.Contains(msg, "mfc: stream wurde nicht public") || + strings.Contains(msg, "mfc: stream ist nicht public") || + strings.Contains(msg, "stream ist nicht öffentlich") || + strings.Contains(msg, "status: offline") || + strings.Contains(msg, "status: private") || + strings.Contains(msg, "status: notexist") { + return false + } + + // ffmpeg-Fehler: + // - bei Hidden (Autostart/Auto-Checks) meist "offline/kurzlebig" => stumm + // - bei manuell gestarteten Jobs sinnvoll => loggen + if strings.Contains(msg, "ffmpeg") { + if req.Hidden { + return false + } + return true + } + + // Default: + // - Hidden-Jobs sollen ruhig sein + // - manuelle Jobs dürfen Fehler loggen (aber keine "offline"/"expected" s.o.) + return !req.Hidden +} + +func shouldLogRecordInfo(req RecordRequest) bool { + // Standard: keine Info-Logs (wie auto-deleted), außer du setzt REC_VERBOSE=1 + if verboseLogs() { + return true + } + return false +} diff --git a/backend/main.go b/backend/main.go index a0b8f63..a2ed4c8 100644 --- a/backend/main.go +++ b/backend/main.go @@ -39,7 +39,6 @@ import ( "github.com/grafov/m3u8" gocpu "github.com/shirou/gopsutil/v3/cpu" godisk "github.com/shirou/gopsutil/v3/disk" - "github.com/sqweek/dialog" "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/math/fixed" @@ -69,6 +68,7 @@ type RecordJob struct { VideoWidth int `json:"videoWidth,omitempty"` VideoHeight int `json:"videoHeight,omitempty"` FPS float64 `json:"fps,omitempty"` + Meta *videoMeta `json:"meta,omitempty"` Hidden bool `json:"-"` @@ -184,6 +184,163 @@ func probeVideoProps(ctx context.Context, filePath string) (w int, h int, fps fl return w, h, fps, nil } +func metaJSONPathForAssetID(assetID string) (string, error) { + root, err := generatedMetaRoot() + if err != nil { + return "", err + } + if strings.TrimSpace(root) == "" { + return "", fmt.Errorf("generated/meta root leer") + } + return filepath.Join(root, assetID, "meta.json"), nil +} + +func readVideoMetaIfValid(metaPath string, fi os.FileInfo) (*videoMeta, bool) { + b, err := os.ReadFile(metaPath) + if err != nil || len(b) == 0 { + return nil, false + } + var m videoMeta + if err := json.Unmarshal(b, &m); err != nil { + return nil, false + } + + // nur akzeptieren wenn Datei identisch (damit wir nicht stale Werte zeigen) + if m.FileSize != fi.Size() || m.FileModUnix != fi.ModTime().Unix() { + return nil, false + } + + // Mindestvalidierung + if m.DurationSeconds <= 0 { + return nil, false + } + + return &m, true +} + +func ensureVideoMetaForFile(ctx context.Context, fullPath string, fi os.FileInfo, sourceURL string) (*videoMeta, bool) { + // assetID aus Dateiname + stem := strings.TrimSuffix(filepath.Base(fullPath), filepath.Ext(fullPath)) + assetID := stripHotPrefix(strings.TrimSpace(stem)) + if assetID == "" { + return nil, false + } + + // sanitize wie bei deinen generated Ordnern + var err error + assetID, err = sanitizeID(assetID) + if err != nil || assetID == "" { + return nil, false + } + + metaPath, err := metaJSONPathForAssetID(assetID) + if err != nil { + return nil, false + } + + // 1) valid meta vorhanden? + if m, ok := readVideoMetaIfValid(metaPath, fi); ok { + return m, true + } + + // 2) sonst neu erzeugen (mit Concurrency-Limit) + if ctx == nil { + ctx = context.Background() + } + cctx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + + if durSem != nil { + if err := durSem.Acquire(cctx); err != nil { + return nil, false + } + defer durSem.Release() + } + + // Dauer + dur, derr := durationSecondsCached(cctx, fullPath) + if derr != nil || dur <= 0 { + return nil, false + } + + // Video props + w, h, fps, perr := probeVideoProps(cctx, fullPath) + if perr != nil { + // width/height/fps dürfen 0 bleiben, duration ist aber trotzdem nützlich + w, h, fps = 0, 0, 0 + } + + // meta dir anlegen + _ = os.MkdirAll(filepath.Dir(metaPath), 0o755) + + m := &videoMeta{ + Version: 2, + DurationSeconds: dur, + FileSize: fi.Size(), + FileModUnix: fi.ModTime().Unix(), + VideoWidth: w, + VideoHeight: h, + FPS: fps, + Resolution: formatResolution(w, h), + SourceURL: strings.TrimSpace(sourceURL), + UpdatedAtUnix: time.Now().Unix(), + } + + b, _ := json.MarshalIndent(m, "", " ") + b = append(b, '\n') + _ = atomicWriteFile(metaPath, b) // best effort + + return m, true +} + +// ensureVideoMetaForFileBestEffort: +// - versucht zuerst echtes Generieren (ffprobe/ffmpeg) via ensureVideoMetaForFile +// - wenn das fehlschlägt, aber durationSecondsCacheOnly schon was weiß: +// schreibt eine Duration-only meta.json, damit wir künftig "aus meta.json" lesen können. +func ensureVideoMetaForFileBestEffort(ctx context.Context, fullPath string, sourceURL string) (*videoMeta, bool) { + fullPath = strings.TrimSpace(fullPath) + if fullPath == "" { + return nil, false + } + + fi, err := os.Stat(fullPath) + if err != nil || fi == nil || fi.IsDir() || fi.Size() <= 0 { + return nil, false + } + + // 1) Normaler Weg: meta erzeugen/lesen (ffprobe/ffmpeg) + if m, ok := ensureVideoMetaForFile(ctx, fullPath, fi, sourceURL); ok && m != nil { + return m, true + } + + // 2) Fallback: wenn wir Duration schon im RAM-Cache haben -> meta.json (Duration-only) persistieren + dur := durationSecondsCacheOnly(fullPath, fi) + if dur <= 0 { + return nil, false + } + + stem := strings.TrimSuffix(filepath.Base(fullPath), filepath.Ext(fullPath)) + assetID := stripHotPrefix(strings.TrimSpace(stem)) + if assetID == "" { + return nil, false + } + + metaPath, err := metaJSONPathForAssetID(assetID) + if err != nil || strings.TrimSpace(metaPath) == "" { + return nil, false + } + + _ = os.MkdirAll(filepath.Dir(metaPath), 0o755) + _ = writeVideoMetaDuration(metaPath, fi, dur, sourceURL) + + // nochmal lesen/validieren + if m, ok := readVideoMetaIfValid(metaPath, fi); ok && m != nil { + return m, true + } + + return nil, false +} + func (d *dummyResponseWriter) Header() http.Header { if d.h == nil { d.h = make(http.Header) @@ -1373,72 +1530,6 @@ func durationSecondsCached(ctx context.Context, path string) (float64, error) { return sec, nil } -type RecorderSettings struct { - RecordDir string `json:"recordDir"` - DoneDir string `json:"doneDir"` - FFmpegPath string `json:"ffmpegPath"` - - AutoAddToDownloadList bool `json:"autoAddToDownloadList"` - AutoStartAddedDownloads bool `json:"autoStartAddedDownloads"` - - 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 - - // EncryptedCookies contains base64(nonce+ciphertext) of a JSON cookie map. - EncryptedCookies string `json:"encryptedCookies"` -} - -var ( - settingsMu sync.Mutex - settings = RecorderSettings{ - RecordDir: "/records", - DoneDir: "/records/done", - FFmpegPath: "", - - AutoAddToDownloadList: false, - AutoStartAddedDownloads: false, - - UseChaturbateAPI: false, - UseMyFreeCamsWatcher: false, - AutoDeleteSmallDownloads: false, - AutoDeleteSmallDownloadsBelowMB: 50, - - BlurPreviews: false, - TeaserPlayback: "hover", - TeaserAudio: false, - - 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() - return settings -} - func detectFFmpegPath() string { // 0. Settings-Override (ffmpegPath in recorder_settings.json / UI) s := getSettings() @@ -1569,246 +1660,6 @@ func renameGenerated(oldID, newID string) { } } -func loadSettings() { - p := settingsFilePath() - b, err := os.ReadFile(p) - fmt.Println("🔧 settingsFile:", p) - if err == nil { - s := getSettings() // ✅ startet mit Defaults - if json.Unmarshal(b, &s) == nil { - if strings.TrimSpace(s.RecordDir) != "" { - s.RecordDir = filepath.Clean(strings.TrimSpace(s.RecordDir)) - } - if strings.TrimSpace(s.DoneDir) != "" { - s.DoneDir = filepath.Clean(strings.TrimSpace(s.DoneDir)) - } - if strings.TrimSpace(s.FFmpegPath) != "" { - 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 - } - - settingsMu.Lock() - settings = s - settingsMu.Unlock() - } - } - - // Ordner sicherstellen - s := getSettings() - 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() - fmt.Println("🔍 ffmpegPath:", ffmpegPath) - - ffprobePath = detectFFprobePath() - fmt.Println("🔍 ffprobePath:", ffprobePath) - -} - -func saveSettingsToDisk() { - s := getSettings() - - 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) { - switch r.Method { - case http.MethodGet: - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - _ = json.NewEncoder(w).Encode(getSettings()) - return - - case http.MethodPost: - var in RecorderSettings - if err := json.NewDecoder(r.Body).Decode(&in); err != nil { - http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest) - return - } - - // --- normalize (WICHTIG: erst trim, dann leer-check, dann clean) --- - recRaw := strings.TrimSpace(in.RecordDir) - doneRaw := strings.TrimSpace(in.DoneDir) - - if recRaw == "" || doneRaw == "" { - http.Error(w, "recordDir und doneDir dürfen nicht leer sein", http.StatusBadRequest) - return - } - - in.RecordDir = filepath.Clean(recRaw) - in.DoneDir = filepath.Clean(doneRaw) - - // Optional aber sehr empfehlenswert: "." verbieten - if in.RecordDir == "." || in.DoneDir == "." { - http.Error(w, "recordDir/doneDir dürfen nicht '.' sein", http.StatusBadRequest) - return - } - - 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" - } - - // Auto-Delete: clamp - if in.AutoDeleteSmallDownloadsBelowMB < 0 { - in.AutoDeleteSmallDownloadsBelowMB = 0 - } - if in.AutoDeleteSmallDownloadsBelowMB > 100_000 { - in.AutoDeleteSmallDownloadsBelowMB = 100_000 - } - - // --- ensure folders (Fehler zurückgeben, falls z.B. keine Rechte) --- - recAbs, err := resolvePathRelativeToApp(in.RecordDir) - if err != nil { - http.Error(w, "ungültiger recordDir: "+err.Error(), http.StatusBadRequest) - return - } - doneAbs, err := resolvePathRelativeToApp(in.DoneDir) - if err != nil { - http.Error(w, "ungültiger doneDir: "+err.Error(), http.StatusBadRequest) - return - } - - if err := os.MkdirAll(recAbs, 0o755); err != nil { - http.Error(w, "konnte recordDir nicht erstellen: "+err.Error(), http.StatusBadRequest) - return - } - if err := os.MkdirAll(doneAbs, 0o755); err != nil { - http.Error(w, "konnte doneDir nicht erstellen: "+err.Error(), http.StatusBadRequest) - return - } - - // ✅ Settings im RAM aktualisieren - settingsMu.Lock() - settings = in - settingsMu.Unlock() - - // ✅ Settings auf Disk persistieren - saveSettingsToDisk() - - // ✅ ffmpeg/ffprobe nach Änderungen neu bestimmen - // Tipp: wenn der User FFmpegPath explizit setzt, nutze den direkt. - if strings.TrimSpace(in.FFmpegPath) != "" { - ffmpegPath = in.FFmpegPath - } else { - ffmpegPath = detectFFmpegPath() - } - fmt.Println("🔍 ffmpegPath:", ffmpegPath) - - ffprobePath = detectFFprobePath() - fmt.Println("🔍 ffprobePath:", ffprobePath) - - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - _ = json.NewEncoder(w).Encode(getSettings()) - return - - default: - http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) - return - } -} - -func settingsBrowse(w http.ResponseWriter, r *http.Request) { - target := r.URL.Query().Get("target") - if target != "record" && target != "done" && target != "ffmpeg" { - http.Error(w, "target muss record, done oder ffmpeg sein", http.StatusBadRequest) - return - } - - var ( - p string - err error - ) - - if target == "ffmpeg" { - // Dateiauswahl für ffmpeg.exe - p, err = dialog.File(). - Title("ffmpeg.exe auswählen"). - Load() - } else { - // Ordnerauswahl für record/done - p, err = dialog.Directory(). - Title("Ordner auswählen"). - Browse() - } - - if err != nil { - // User cancelled → 204 No Content ist praktisch fürs Frontend - if strings.Contains(strings.ToLower(err.Error()), "cancel") { - w.WriteHeader(http.StatusNoContent) - return - } - http.Error(w, "auswahl fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return - } - - // optional: wenn innerhalb exe-dir, als RELATIV zurückgeben - p = maybeMakeRelativeToExe(p) - - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]string{"path": p}) -} - -func maybeMakeRelativeToExe(abs string) string { - exe, err := os.Executable() - if err != nil { - return abs - } - base := filepath.Dir(exe) - - rel, err := filepath.Rel(base, abs) - if err != nil { - return abs - } - // wenn rel mit ".." beginnt -> nicht innerhalb base -> absoluten Pfad behalten - if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return abs - } - return filepath.ToSlash(rel) // frontend-freundlich -} - // --- Gemeinsame Status-Werte für MFC --- type Status int diff --git a/backend/nsfwapp.exe b/backend/nsfwapp.exe index bfe30df..d471885 100644 Binary files a/backend/nsfwapp.exe and b/backend/nsfwapp.exe differ diff --git a/backend/record_handlers.go b/backend/record_handlers.go index 509aa90..7bc3575 100644 --- a/backend/record_handlers.go +++ b/backend/record_handlers.go @@ -3,12 +3,13 @@ package main import ( - "bytes" "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" + "net" "net/http" "net/url" "os" @@ -21,6 +22,7 @@ import ( "strings" "sync" "sync/atomic" + "syscall" "time" ) @@ -209,241 +211,413 @@ func startRecordingFromRequest(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(job) } -func recordVideo(w http.ResponseWriter, r *http.Request) { +// ---- track if headers/body were already written ---- +// (Go methods must be at package scope) +type rwTrack struct { + http.ResponseWriter + wrote bool +} +func (t *rwTrack) WriteHeader(statusCode int) { + if t.wrote { + return + } + t.wrote = true + t.ResponseWriter.WriteHeader(statusCode) +} + +func (t *rwTrack) Write(p []byte) (int, error) { + if !t.wrote { + t.wrote = true + } + return t.ResponseWriter.Write(p) +} + +func recordVideo(w http.ResponseWriter, r *http.Request) { + // ---- wrap writer to detect "already wrote" ---- + tw := &rwTrack{ResponseWriter: w} + w = tw + + writeErr := func(code int, msg string) { + // Wenn schon Header/Body raus sind, dürfen wir KEIN http.Error mehr machen, + // sonst gibt's "superfluous response.WriteHeader". + if tw.wrote { + fmt.Println("[recordVideo] late error (headers already sent):", code, msg) + return + } + http.Error(w, msg, code) // nutzt WriteHeader+Write -> tw.wrote wird automatisch true + } + + writeStatus := func(code int) { + if tw.wrote { + return + } + w.WriteHeader(code) // geht durch rwTrack.WriteHeader + } + + // ---- CORS ---- origin := r.Header.Get("Origin") if origin != "" { - // ✅ dev origin erlauben (oder "*" wenn’s dir egal ist) w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Vary", "Origin") w.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Range") - w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Range, Accept-Ranges") + // Wichtig: Browser schicken bei Video-Range-Requests oft If-Range / If-Modified-Since / If-None-Match. + // Wenn du die nicht erlaubst, schlägt der Preflight fehl -> VideoJS sieht "NETWORK error". + w.Header().Set("Access-Control-Allow-Headers", "Range, If-Range, If-Modified-Since, If-None-Match") + w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified, X-Transcode-Offset-Seconds") + w.Header().Set("Access-Control-Allow-Credentials", "true") } if r.Method == http.MethodOptions { - w.WriteHeader(http.StatusNoContent) + writeStatus(http.StatusNoContent) return } - // ✅ einmal lesen (für beide Zweige) + normalisieren - q := strings.TrimSpace(r.URL.Query().Get("quality")) - if strings.EqualFold(q, "auto") { - q = "" + // ---- query normalize ---- + // Neu: resolution=LOW|MEDIUM|HIGH|ORIGINAL + res := strings.TrimSpace(r.URL.Query().Get("resolution")) + + // Backwards-Compat: falls altes Frontend noch quality nutzt + if res == "" { + res = strings.TrimSpace(r.URL.Query().Get("quality")) } - if q != "" { - // früh validieren (liefert sauberen 400 statt später 500) - if _, ok := profileFromQuality(q); !ok { - http.Error(w, "ungültige quality", http.StatusBadRequest) + + // Normalize: auto/original => leer (== "ORIGINAL" Profil) + if strings.EqualFold(res, "auto") || strings.EqualFold(res, "original") { + res = "" + } + + // Validieren (wenn gesetzt) + if res != "" { + if _, ok := profileFromResolution(res); !ok { + writeErr(http.StatusBadRequest, "ungültige resolution") return } } - fmt.Println("[recordVideo] quality="+q, "file="+r.URL.Query().Get("file"), "id="+r.URL.Query().Get("id")) + rawProgress := strings.TrimSpace(r.URL.Query().Get("progress")) + if rawProgress == "" { + rawProgress = strings.TrimSpace(r.URL.Query().Get("p")) + } - // ✅ Wiedergabe über Dateiname (für doneDir / recordDir) - if raw := strings.TrimSpace(r.URL.Query().Get("file")); raw != "" { - // explizit decoden (zur Sicherheit) - file, err := url.QueryUnescape(raw) - if err != nil { - http.Error(w, "ungültiger file", http.StatusBadRequest) - return - } - file = strings.TrimSpace(file) + // ---- startSec parse (seek position in seconds) ---- + startSec := 0 + startFrac := -1.0 // wenn 0..1 => Progress-Fraction (currentProgress) - // kein Pfad, keine Backslashes, kein Traversal - if file == "" || - strings.Contains(file, "/") || - strings.Contains(file, "\\") || - filepath.Base(file) != file { - http.Error(w, "ungültiger file", http.StatusBadRequest) + raw := strings.TrimSpace(r.URL.Query().Get("start")) + if raw == "" { + raw = strings.TrimSpace(r.URL.Query().Get("t")) + } + + parseFracOrSeconds := func(s string) { + s = strings.TrimSpace(s) + if s == "" { return } - ext := strings.ToLower(filepath.Ext(file)) - if ext != ".mp4" && ext != ".ts" { - http.Error(w, "nicht erlaubt", http.StatusForbidden) - return - } - - s := getSettings() - recordAbs, err := resolvePathRelativeToApp(s.RecordDir) - if err != nil { - http.Error(w, "recordDir auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return - } - doneAbs, err := resolvePathRelativeToApp(s.DoneDir) - if err != nil { - http.Error(w, "doneDir auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return - } - - // 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" - names = append(names, mp4File) - } - - var outPath string - for _, name := range names { - // done root + done// (skip "keep") - if p, _, ok := findFileInDirOrOneLevelSubdirs(doneAbs, name, "keep"); ok { - outPath = p - break + // allow "hh:mm:ss" / "mm:ss" + if strings.Contains(s, ":") { + parts := strings.Split(s, ":") + ok := true + vals := make([]int, 0, len(parts)) + for _, p := range parts { + p = strings.TrimSpace(p) + n, err := strconv.Atoi(p) + if err != nil || n < 0 { + ok = false + break + } + vals = append(vals, n) } - // 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 - } - outPath = filepath.Clean(strings.TrimSpace(outPath)) - - // 1) ✅ TS -> MP4 (on-demand remux) - if strings.ToLower(filepath.Ext(outPath)) == ".ts" { - newOut, err := maybeRemuxTS(outPath) - if err != nil { - http.Error(w, "TS kann im Browser nicht abgespielt werden; Remux fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) - return - } - if strings.TrimSpace(newOut) == "" { - http.Error(w, "TS kann im Browser nicht abgespielt werden; Remux hat keine MP4 erzeugt", http.StatusInternalServerError) - return - } - outPath = filepath.Clean(strings.TrimSpace(newOut)) - - // sicherstellen, dass wirklich eine MP4 existiert - fi, err := os.Stat(outPath) - if err != nil || fi.IsDir() || fi.Size() == 0 || strings.ToLower(filepath.Ext(outPath)) != ".mp4" { - http.Error(w, "Remux-Ergebnis ungültig", http.StatusInternalServerError) - return - } - } - - // ✅ Falls Datei ".mp4" heißt, aber eigentlich TS/HTML ist -> nicht als MP4 ausliefern - if strings.ToLower(filepath.Ext(outPath)) == ".mp4" { - kind, _ := sniffVideoKind(outPath) - switch kind { - case "ts": - newOut, err := maybeRemuxTS(outPath) - if err != nil { - http.Error(w, "Datei ist TS (nur .mp4 benannt); Remux fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + if ok { + if len(vals) == 2 { + startSec = vals[0]*60 + vals[1] + return + } else if len(vals) == 3 { + startSec = vals[0]*3600 + vals[1]*60 + vals[2] return } - outPath = filepath.Clean(strings.TrimSpace(newOut)) - case "html": - http.Error(w, "Server liefert HTML statt Video (Pfad/Lookup prüfen)", http.StatusInternalServerError) - return - } - } - - // 2) ✅ MP4 -> Quality Transcode (on-demand) - w.Header().Set("Cache-Control", "no-store") - - stream := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("stream"))) - wantStream := stream == "1" || stream == "true" || stream == "yes" - - if q != "" && wantStream { - prof, _ := profileFromQuality(q) - - // ⚠️ Streaming-Transcode: startet Playback bevor fertig - if err := serveTranscodedStream(r.Context(), w, outPath, prof); err != nil { - http.Error(w, "transcode stream failed: "+err.Error(), http.StatusInternalServerError) - return } return } - if q != "" { - var terr error - outPath, terr = maybeTranscodeForRequest(r.Context(), outPath, q) - if terr != nil { - http.Error(w, "transcode failed: "+terr.Error(), http.StatusInternalServerError) - return - } - } - - serveVideoFile(w, r, outPath) - return - - } - - // ✅ ALT: Wiedergabe über Job-ID (funktioniert nur solange Job im RAM existiert) - id := strings.TrimSpace(r.URL.Query().Get("id")) - if id == "" { - http.Error(w, "id fehlt", http.StatusBadRequest) - return - } - - jobsMu.Lock() - job, ok := jobs[id] - jobsMu.Unlock() - if !ok { - http.Error(w, "job nicht gefunden", http.StatusNotFound) - return - } - - outPath := filepath.Clean(strings.TrimSpace(job.Output)) - if outPath == "" { - http.Error(w, "output fehlt", http.StatusNotFound) - return - } - - if !filepath.IsAbs(outPath) { - abs, err := resolvePathRelativeToApp(outPath) + // number: seconds OR fraction + f, err := strconv.ParseFloat(s, 64) if err != nil { - http.Error(w, "pfad auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) return } - outPath = abs + if f <= 0 { + return + } + + // < 1.0 => treat as fraction (currentProgress) + if f > 0 && f < 1.0 { + startFrac = f + return + } + + // >= 1.0 => treat as seconds (floor) + startSec = int(f) } - fi, err := os.Stat(outPath) - if err != nil || fi.IsDir() || fi.Size() == 0 { - http.Error(w, "datei nicht gefunden", http.StatusNotFound) + parseFracOrSeconds(raw) + + // optional explicit progress overrides fraction + if rawProgress != "" { + f, err := strconv.ParseFloat(strings.TrimSpace(rawProgress), 64) + if err == nil && f > 0 && f < 1.0 { + startFrac = f + } + } + + if startSec < 0 { + startSec = 0 + } + + // ---- resolve outPath from file or id ---- + resolveOutPath := func() (string, bool) { + // ✅ Wiedergabe über Dateiname (für doneDir / recordDir) + if rawFile := strings.TrimSpace(r.URL.Query().Get("file")); rawFile != "" { + file, err := url.QueryUnescape(rawFile) + if err != nil { + writeErr(http.StatusBadRequest, "ungültiger file") + return "", false + } + file = strings.TrimSpace(file) + + // kein Pfad, keine Backslashes, kein Traversal + if file == "" || + strings.Contains(file, "/") || + strings.Contains(file, "\\") || + filepath.Base(file) != file { + writeErr(http.StatusBadRequest, "ungültiger file") + return "", false + } + + ext := strings.ToLower(filepath.Ext(file)) + if ext != ".mp4" && ext != ".ts" { + writeErr(http.StatusForbidden, "nicht erlaubt") + return "", false + } + + s := getSettings() + recordAbs, err := resolvePathRelativeToApp(s.RecordDir) + if err != nil { + writeErr(http.StatusInternalServerError, "recordDir auflösung fehlgeschlagen: "+err.Error()) + return "", false + } + doneAbs, err := resolvePathRelativeToApp(s.DoneDir) + if err != nil { + writeErr(http.StatusInternalServerError, "doneDir auflösung fehlgeschlagen: "+err.Error()) + return "", false + } + + // Kandidaten: erst done (inkl. 1 Level Subdir, aber ohne "keep"), + // dann keep (inkl. 1 Level Subdir), dann recordDir + names := []string{file} + if ext == ".ts" { + names = append(names, strings.TrimSuffix(file, ext)+".mp4") + } + + var outPath string + for _, name := range names { + if p, _, ok := findFileInDirOrOneLevelSubdirs(doneAbs, name, "keep"); ok { + outPath = p + break + } + if p, _, ok := findFileInDirOrOneLevelSubdirs(filepath.Join(doneAbs, "keep"), name, ""); ok { + outPath = p + break + } + if p, _, ok := findFileInDirOrOneLevelSubdirs(recordAbs, name, ""); ok { + outPath = p + break + } + } + if outPath == "" { + writeErr(http.StatusNotFound, "datei nicht gefunden") + return "", false + } + return filepath.Clean(strings.TrimSpace(outPath)), true + } + + // ✅ ALT: Wiedergabe über Job-ID (funktioniert nur solange Job im RAM existiert) + id := strings.TrimSpace(r.URL.Query().Get("id")) + if id == "" { + writeErr(http.StatusBadRequest, "id fehlt") + return "", false + } + + jobsMu.Lock() + job, ok := jobs[id] + jobsMu.Unlock() + if !ok { + writeErr(http.StatusNotFound, "job nicht gefunden") + return "", false + } + + outPath := filepath.Clean(strings.TrimSpace(job.Output)) + if outPath == "" { + writeErr(http.StatusNotFound, "output fehlt") + return "", false + } + + if !filepath.IsAbs(outPath) { + abs, err := resolvePathRelativeToApp(outPath) + if err != nil { + writeErr(http.StatusInternalServerError, "pfad auflösung fehlgeschlagen: "+err.Error()) + return "", false + } + outPath = abs + } + + fi, err := os.Stat(outPath) + if err != nil || fi.IsDir() || fi.Size() == 0 { + writeErr(http.StatusNotFound, "datei nicht gefunden") + return "", false + } + return outPath, true + } + + outPath, ok := resolveOutPath() + if !ok { return } - // 1) ✅ TS -> MP4 (on-demand remux) + // ---- convert progress fraction to seconds (if needed) ---- + if startSec == 0 && startFrac > 0 && startFrac < 1.0 { + // ffprobe duration (cached) + if err := ensureFFprobeAvailable(); err == nil { + pctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + dur, derr := getVideoDurationSecondsCached(pctx, outPath) + cancel() + + if derr == nil && dur > 0 { + startSec = int(startFrac * dur) + } + } + } + + // sanitize + optional bucket align (wie bei GOP-ish seeking) + if startSec < 0 { + startSec = 0 + } + startSec = (startSec / 2) * 2 + + // ---- TS -> MP4 (on-demand remux) ---- if strings.ToLower(filepath.Ext(outPath)) == ".ts" { newOut, err := maybeRemuxTS(outPath) if err != nil { - http.Error(w, "TS Remux fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + writeErr(http.StatusInternalServerError, "TS Remux fehlgeschlagen: "+err.Error()) return } if strings.TrimSpace(newOut) == "" { - http.Error(w, "TS kann im Browser nicht abgespielt werden; Remux hat keine MP4 erzeugt", http.StatusInternalServerError) + writeErr(http.StatusInternalServerError, "TS kann im Browser nicht abgespielt werden; Remux hat keine MP4 erzeugt") return } outPath = filepath.Clean(strings.TrimSpace(newOut)) fi, err := os.Stat(outPath) if err != nil || fi.IsDir() || fi.Size() == 0 || strings.ToLower(filepath.Ext(outPath)) != ".mp4" { - http.Error(w, "Remux-Ergebnis ungültig", http.StatusInternalServerError) + writeErr(http.StatusInternalServerError, "Remux-Ergebnis ungültig") return } } - // 2) ✅ MP4 -> Quality Transcode (on-demand) + // ✅ Falls Datei ".mp4" heißt, aber eigentlich TS/HTML ist -> nicht als MP4 ausliefern + if strings.ToLower(filepath.Ext(outPath)) == ".mp4" { + kind, _ := sniffVideoKind(outPath) + switch kind { + case "ts": + newOut, err := maybeRemuxTS(outPath) + if err != nil { + writeErr(http.StatusInternalServerError, "Datei ist TS (nur .mp4 benannt); Remux fehlgeschlagen: "+err.Error()) + return + } + outPath = filepath.Clean(strings.TrimSpace(newOut)) + case "html": + writeErr(http.StatusInternalServerError, "Server liefert HTML statt Video (Pfad/Lookup prüfen)") + return + } + } + + // ---- Quality / Transcode handling ---- w.Header().Set("Cache-Control", "no-store") - if q != "" { + + stream := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("stream"))) + wantStream := stream == "1" || stream == "true" || stream == "yes" + + // ✅ Wenn quality gesetzt ist: + if res != "" { + prof, _ := profileFromResolution(res) + + // ✅ wenn Quelle schon <= Zielhöhe: ORIGINAL liefern + // ABER NUR wenn wir NICHT seeken und NICHT streamen wollen. + if prof.Height > 0 && startSec == 0 && !wantStream { + if err := ensureFFprobeAvailable(); err == nil { + pctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + + if srcH, err := getVideoHeightCached(pctx, outPath); err == nil && srcH > 0 { + if srcH <= prof.Height+8 { + serveVideoFile(w, r, outPath) + return + } + } + } + } + + // ✅ 1) Seek (startSec>0): Standard = Segment-Datei transcodieren & dann normal ausliefern (Range-fähig) + // stream=1 kann weiterhin den "live pipe" erzwingen. + if startSec > 0 && !wantStream { + segPath, terr := maybeTranscodeForRequest(r.Context(), outPath, res, startSec) + if terr != nil { + writeErr(http.StatusInternalServerError, "transcode failed: "+terr.Error()) + return + } + + // ✅ Offset NUR setzen, wenn wir wirklich ab startSec ausliefern (Segment) + w.Header().Set("X-Transcode-Offset-Seconds", strconv.Itoa(startSec)) + + serveVideoFile(w, r, segPath) + return + } + + // ✅ 2) stream=1 ODER startSec>0 mit stream=true: pipe-stream + if wantStream || startSec > 0 { + if startSec > 0 { + // ✅ Offset NUR setzen, wenn wir wirklich ab startSec ausliefern (Stream) + w.Header().Set("X-Transcode-Offset-Seconds", strconv.Itoa(startSec)) + } + + if err := serveTranscodedStreamAt(r.Context(), w, outPath, prof, startSec); err != nil { + if errors.Is(err, context.Canceled) { + return + } + writeErr(http.StatusInternalServerError, "transcode stream failed: "+err.Error()) + return + } + return + } + + // ✅ 3) startSec==0: Full-file Cache-Transcode (wie vorher) + if startSec == 0 { + segPath, terr := maybeTranscodeForRequest(r.Context(), outPath, res, 0) + if terr != nil { + writeErr(http.StatusInternalServerError, "transcode failed: "+terr.Error()) + return + } + serveVideoFile(w, r, segPath) + return + } + } + + // ✅ Full-file Cache-Transcode nur wenn startSec == 0 + if res != "" && startSec == 0 { var terr error - outPath, terr = maybeTranscodeForRequest(r.Context(), outPath, q) + outPath, terr = maybeTranscodeForRequest(r.Context(), outPath, res, startSec) + if terr != nil { - http.Error(w, "transcode failed: "+terr.Error(), http.StatusInternalServerError) + writeErr(http.StatusInternalServerError, "transcode failed: "+terr.Error()) return } } @@ -464,18 +638,50 @@ func (fw flushWriter) Write(p []byte) (int, error) { return n, err } +func isClientDisconnectErr(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.Canceled) || errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrClosedPipe) { + return true + } + + // Windows / net/http typische Fälle + var op *net.OpError + if errors.As(err, &op) { + // op.Err kann syscall.Errno(10054/10053/...) sein + if se, ok := op.Err.(syscall.Errno); ok { + switch int(se) { + case 10054, 10053, 10058: // WSAECONNRESET, WSAECONNABORTED, WSAESHUTDOWN + return true + } + } + } + + msg := strings.ToLower(err.Error()) + if strings.Contains(msg, "broken pipe") || + strings.Contains(msg, "connection reset") || + strings.Contains(msg, "forcibly closed") || + strings.Contains(msg, "wsasend") || + strings.Contains(msg, "wsarecv") { + return true + } + + return false +} + func serveTranscodedStream(ctx context.Context, w http.ResponseWriter, inPath string, prof TranscodeProfile) error { + return serveTranscodedStreamAt(ctx, w, inPath, prof, 0) +} + +func serveTranscodedStreamAt(ctx context.Context, w http.ResponseWriter, inPath string, prof TranscodeProfile, startSec int) error { if err := ensureFFmpegAvailable(); err != nil { return err } - // Header vor dem ersten Write setzen - w.Header().Set("Content-Type", "video/mp4") - w.Header().Set("Cache-Control", "no-store") - // Range macht bei Pipe-Streaming i.d.R. keinen Sinn: - w.Header().Set("Accept-Ranges", "none") + // ffmpeg args (mit -ss vor -i) + args := buildFFmpegStreamArgsAt(inPath, prof, startSec) - args := buildFFmpegStreamArgs(inPath, prof) cmd := exec.CommandContext(ctx, "ffmpeg", args...) stdout, err := cmd.StdoutPipe() @@ -483,34 +689,74 @@ func serveTranscodedStream(ctx context.Context, w http.ResponseWriter, inPath st return err } - var stderr bytes.Buffer - cmd.Stderr = &stderr + stderr, err := cmd.StderrPipe() + if err != nil { + return err + } if err := cmd.Start(); err != nil { return err } - defer func() { _ = stdout.Close() }() - flusher, _ := w.(http.Flusher) - fw := flushWriter{w: w, f: flusher} + // stderr MUSS gelesen werden, sonst kann ffmpeg blockieren + go func() { + _, _ = io.ReadAll(stderr) + _ = cmd.Wait() + }() - buf := make([]byte, 64*1024) - _, copyErr := io.CopyBuffer(fw, stdout, buf) + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "video/mp4") + w.Header().Set("Accept-Ranges", "none") + w.WriteHeader(http.StatusOK) - waitErr := cmd.Wait() - - // Wenn Client abbricht, ist ctx meist canceled -> nicht als "echter" Fehler behandeln - if ctx.Err() != nil { - return ctx.Err() + // kontinuierlich flushen + var out io.Writer = w + if f, ok := w.(http.Flusher); ok { + out = flushWriter{w: w, f: f} } + _, copyErr := io.Copy(out, stdout) + + // Client abgebrochen -> kein Fehler if copyErr != nil { - return fmt.Errorf("stream copy failed: %w", copyErr) + if isClientDisconnectErr(copyErr) { + return nil + } } - if waitErr != nil { - return fmt.Errorf("ffmpeg failed: %w (stderr=%s)", waitErr, strings.TrimSpace(stderr.String())) + + // Wenn der Request context weg ist: ebenfalls ok (Quality-Wechsel, Seek, Tab zu) + if ctx.Err() != nil && errors.Is(ctx.Err(), context.Canceled) { + return nil } - return nil + + return copyErr +} + +func buildFFmpegStreamArgsAt(inPath string, prof TranscodeProfile, startSec int) []string { + args := buildFFmpegStreamArgs(inPath, prof) + + if startSec <= 0 { + return args + } + + // Insert "-ss " before "-i" + out := make([]string, 0, len(args)+2) + + inserted := false + for i := 0; i < len(args); i++ { + if !inserted && args[i] == "-i" { + out = append(out, "-ss", strconv.Itoa(startSec)) + inserted = true + } + out = append(out, args[i]) + } + + // Fallback: falls "-i" nicht gefunden wird, häng's vorne dran + if !inserted { + return append([]string{"-ss", strconv.Itoa(startSec)}, args...) + } + + return out } func recordStatus(w http.ResponseWriter, r *http.Request) { @@ -1146,10 +1392,8 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { } } - // 2) Fallback: RAM-Cache only (immer noch schnell, kein ffprobe) - if dur <= 0 { - dur = durationSecondsCacheOnly(full, fi) - } + // ✅ Kein Cache-only Fallback hier. + // Wenn meta fehlt, bleibt dur erstmal 0 und wird beim Ausliefern (Pagination) via ensureVideoMetaForFileBestEffort erzeugt. ended := t mk := modelFromFullPath(full) @@ -1357,8 +1601,43 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { // Response jobs bauen out := make([]*RecordJob, 0, max(0, end-start)) - for _, i := range idx[start:end] { - out = append(out, items[i].job) + + for _, ii := range idx[start:end] { + base := items[ii].job + if base == nil { + continue + } + + // ✅ Kopie erzeugen (wichtig: keine Race/Mutations am Cache-Objekt) + c := *base + + // ✅ Meta immer aus meta.json (ggf. generieren, wenn fehlt) + // Kurzes Timeout pro Item, damit eine Seite nicht "hängen" kann. + pctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + m, ok := ensureVideoMetaForFileBestEffort(pctx, c.Output, c.SourceURL) + cancel() + + // Wenn Meta ok: Felder IMMER daraus setzen + if ok && m != nil { + c.Meta = m + c.DurationSeconds = m.DurationSeconds + c.SizeBytes = m.FileSize + c.VideoWidth = m.VideoWidth + c.VideoHeight = m.VideoHeight + c.FPS = m.FPS + + // SourceURL: wenn Job leer, aus Meta übernehmen + if strings.TrimSpace(c.SourceURL) == "" && strings.TrimSpace(m.SourceURL) != "" { + c.SourceURL = strings.TrimSpace(m.SourceURL) + } + } else { + // Falls wirklich gar keine Meta gebaut werden kann: wenigstens Size korrekt setzen + if fi, err := os.Stat(c.Output); err == nil && fi != nil && !fi.IsDir() && fi.Size() > 0 { + c.SizeBytes = fi.Size() + } + } + + out = append(out, &c) } w.Header().Set("Content-Type", "application/json") @@ -1490,6 +1769,16 @@ func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { } } + // ✅ NEU: auch Transcode-Cache zum endgültig gelöschten Video entfernen + if prevCanonical != "" { + removeTranscodesForID(doneAbs, prevCanonical) + + // Best-effort (falls irgendwo doch mal abweichende IDs genutzt wurden) + if prevBase != "" && prevBase != prevCanonical { + removeTranscodesForID(doneAbs, stripHotPrefix(prevBase)) + } + } + if err := os.MkdirAll(trashDir, 0o755); err != nil { http.Error(w, "trash dir erstellen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) return diff --git a/backend/record_job_progress.go b/backend/record_job_progress.go index dab4bb6..8a33b31 100644 --- a/backend/record_job_progress.go +++ b/backend/record_job_progress.go @@ -27,15 +27,15 @@ func setJobProgress(job *RecordJob, phase string, pct int) { rangeFor := func(ph string) rng { switch ph { case "postwork": - return rng{70, 72} + return rng{0, 5} case "remuxing": - return rng{72, 78} + return rng{5, 65} case "moving": - return rng{78, 84} + return rng{65, 75} case "probe": - return rng{84, 86} + return rng{75, 80} case "assets": - return rng{86, 99} + return rng{80, 99} default: return rng{0, 100} } @@ -58,6 +58,14 @@ func setJobProgress(job *RecordJob, phase string, pct int) { job.Phase = phase } + // ✅ Sonderfall: "wartet auf Nachbearbeitung" => Progress bleibt 0% + // Erwartung: Caller sendet phase="postwork" und pct=0 solange nur gewartet wird. + // Muss vor "niemals rückwärts" passieren, sonst käme man von Recording-Progress nicht mehr auf 0. + if phaseLower == "postwork" && pct == 0 { + job.Progress = 0 + return + } + // Progress-Logik: // - wenn wir in Postwork sind und jemand phasenlokale 0..100 liefert (z.B. remuxing 25), // mappe das in den globalen Bereich der Phase. @@ -66,20 +74,25 @@ func setJobProgress(job *RecordJob, phase string, pct int) { if inPostwork { r := rangeFor(phaseLower) - if r.start > 0 && r.end >= r.start { - // Wenn pct kleiner ist als unser globaler Einstiegspunkt, interpretieren wir ihn als lokal (0..100) - // und mappen in [start..end]. - if pct < r.start { + if r.end >= r.start { + // Heuristik: + // - Wenn pct bereits im globalen Bereich der Phase liegt => als global interpretieren, clampen. + // - Sonst => als lokales 0..100 interpretieren und in [start..end] mappen. + if pct >= r.start && pct <= r.end { + // schon global + mapped = pct + } else { + // lokal 0..100 -> global width := float64(r.end - r.start) mapped = r.start + int(math.Round((float64(pct)/100.0)*width)) - } else { - // Wenn schon "global" geliefert wird, trotzdem in den Bereich begrenzen - if mapped < r.start { - mapped = r.start - } - if mapped > r.end { - mapped = r.end - } + } + + // clamp in den Bereich + if mapped < r.start { + mapped = r.start + } + if mapped > r.end { + mapped = r.end } } } diff --git a/backend/record_start.go b/backend/record_start.go index f750bab..4bf0901 100644 --- a/backend/record_start.go +++ b/backend/record_start.go @@ -107,7 +107,7 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { } // ✅ Phase für Recording explizit setzen (damit spätere Progress-Writer das erkennen können) - setJobProgress(job, "recording", 1) + setJobProgress(job, "recording", 0) notifyJobsChanged() // ---- Aufnahme starten (Output-Pfad sauber relativ zur EXE auflösen) ---- @@ -173,6 +173,10 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { err = errors.New("unsupported provider") } + if err != nil && shouldLogRecordError(err, provider, req) { + fmt.Println("❌ [record]", provider, job.SourceURL, "->", err) + } + // ---- Recording fertig: EndedAt/Error setzen ---- end := time.Now() @@ -201,10 +205,12 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { // ✅ WICHTIG: sofort Phase wechseln, damit Recorder-Progress danach nichts mehr “zurücksetzt” job.Phase = "postwork" - // ✅ Progress darf ab jetzt nicht mehr runtergehen (mind. Einstieg in Postwork) - if job.Progress < 70 { - job.Progress = 70 - } + /* + // ✅ Progress darf ab jetzt nicht mehr runtergehen (mind. Einstieg in Postwork) + if job.Progress < 70 { + job.Progress = 70 + } + */ out := strings.TrimSpace(job.Output) jobsMu.Unlock() @@ -256,7 +262,10 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { notifyJobsChanged() notifyDoneChanged() - fmt.Println("🧹 auto-deleted (pre-queue):", base, "| size:", formatBytesSI(fi.Size())) + if shouldLogRecordInfo(req) { + fmt.Println("🧹 auto-deleted (pre-queue):", base, "(size: "+formatBytesSI(fi.Size())+")") + } + return } else { fmt.Println("⚠️ auto-delete (pre-queue) failed:", derr) @@ -305,7 +314,7 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { jobsMu.Unlock() // optisches "queued" bumping - setJobProgress(job, "postwork", 71) + setJobProgress(job, "postwork", 0) notifyJobsChanged() diff --git a/backend/record_stream_cb.go b/backend/record_stream_cb.go index 9f2637d..40d3f6b 100644 --- a/backend/record_stream_cb.go +++ b/backend/record_stream_cb.go @@ -1,3 +1,5 @@ +// backend\record_stream_cb.go + package main import ( @@ -49,11 +51,6 @@ func RecordStream( return fmt.Errorf("playlist abrufen: %w", err) } - // ✅ Job erst jetzt sichtbar machen (Stream wirklich verfügbar) - if job != nil { - _ = publishJob(job.ID) - } - if job != nil && strings.TrimSpace(job.PreviewDir) == "" { assetID := assetIDForJob(job) if strings.TrimSpace(assetID) == "" { @@ -75,9 +72,6 @@ func RecordStream( if err != nil { return fmt.Errorf("datei erstellen: %w", err) } - if job != nil { - _ = publishJob(job.ID) - } defer func() { _ = file.Close() @@ -88,6 +82,8 @@ func RecordStream( var lastPush time.Time var lastBytes int64 + published := false + // 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 @@ -95,6 +91,12 @@ func RecordStream( return fmt.Errorf("schreibe segment: %w", err) } + // ✅ erst sichtbar machen, wenn wirklich Bytes geschrieben wurden + if job != nil && !published { + published = true + _ = publishJob(job.ID) + } + // ✅ live size (UI) – throttled written += int64(len(b)) if job != nil { diff --git a/backend/record_stream_mfc.go b/backend/record_stream_mfc.go index 5cc1216..fd73f69 100644 --- a/backend/record_stream_mfc.go +++ b/backend/record_stream_mfc.go @@ -1,3 +1,5 @@ +// backend\record_stream_mfc.go + package main import ( diff --git a/backend/serve_video.go b/backend/serve_video.go index dc84196..70c076b 100644 --- a/backend/serve_video.go +++ b/backend/serve_video.go @@ -14,34 +14,36 @@ import ( "time" ) -func serveVideoFile(w http.ResponseWriter, r *http.Request, path string) { - f, err := openForReadShareDelete(path) +func serveVideoFile(w http.ResponseWriter, r *http.Request, filePath string) { + f, err := os.Open(filePath) if err != nil { - http.Error(w, "datei öffnen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + http.Error(w, "open failed: "+err.Error(), http.StatusNotFound) return } defer f.Close() fi, err := f.Stat() - if err != nil || fi.IsDir() || fi.Size() == 0 { - http.Error(w, "datei nicht gefunden", http.StatusNotFound) + if err != nil || fi.IsDir() || fi.Size() <= 0 { + http.Error(w, "file not found", http.StatusNotFound) return } - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Accept-Ranges", "bytes") - w.Header().Set("X-Content-Type-Options", "nosniff") - - ext := strings.ToLower(filepath.Ext(path)) + ext := strings.ToLower(filepath.Ext(filePath)) switch ext { + case ".mp4": + w.Header().Set("Content-Type", "video/mp4") case ".ts": w.Header().Set("Content-Type", "video/mp2t") default: - w.Header().Set("Content-Type", "video/mp4") + w.Header().Set("Content-Type", "application/octet-stream") } - // ServeContent unterstützt Range Requests (wichtig für Video) - http.ServeContent(w, r, filepath.Base(path), fi.ModTime(), f) + // Range-Support (http.ServeContent macht 206/Content-Range automatisch, wenn Range kommt) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("Cache-Control", "no-store") + + // ServeContent setzt Content-Length/Last-Modified/ETag-Handling korrekt + http.ServeContent(w, r, filepath.Base(filePath), fi.ModTime(), f) } func sniffVideoKind(path string) (string, error) { diff --git a/backend/settings.go b/backend/settings.go new file mode 100644 index 0000000..03153aa --- /dev/null +++ b/backend/settings.go @@ -0,0 +1,325 @@ +// backend\settings.go + +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/sqweek/dialog" +) + +type RecorderSettings struct { + RecordDir string `json:"recordDir"` + DoneDir string `json:"doneDir"` + FFmpegPath string `json:"ffmpegPath"` + + AutoAddToDownloadList bool `json:"autoAddToDownloadList"` + AutoStartAddedDownloads bool `json:"autoStartAddedDownloads"` + + 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 + + EnableNotifications bool `json:"enableNotifications"` + + // EncryptedCookies contains base64(nonce+ciphertext) of a JSON cookie map. + EncryptedCookies string `json:"encryptedCookies"` +} + +var ( + settingsMu sync.Mutex + settings = RecorderSettings{ + RecordDir: "/records", + DoneDir: "/records/done", + FFmpegPath: "", + + AutoAddToDownloadList: false, + AutoStartAddedDownloads: false, + + UseChaturbateAPI: false, + UseMyFreeCamsWatcher: false, + AutoDeleteSmallDownloads: false, + AutoDeleteSmallDownloadsBelowMB: 50, + + BlurPreviews: false, + TeaserPlayback: "hover", + TeaserAudio: false, + + EnableNotifications: true, + + 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() + return settings +} + +func loadSettings() { + p := settingsFilePath() + b, err := os.ReadFile(p) + fmt.Println("🔧 settingsFile:", p) + if err == nil { + s := getSettings() // ✅ startet mit Defaults + if json.Unmarshal(b, &s) == nil { + if strings.TrimSpace(s.RecordDir) != "" { + s.RecordDir = filepath.Clean(strings.TrimSpace(s.RecordDir)) + } + if strings.TrimSpace(s.DoneDir) != "" { + s.DoneDir = filepath.Clean(strings.TrimSpace(s.DoneDir)) + } + if strings.TrimSpace(s.FFmpegPath) != "" { + 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 + } + + settingsMu.Lock() + settings = s + settingsMu.Unlock() + } + } + + // Ordner sicherstellen + s := getSettings() + 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() + fmt.Println("🔍 ffmpegPath:", ffmpegPath) + + ffprobePath = detectFFprobePath() + fmt.Println("🔍 ffprobePath:", ffprobePath) + +} + +func saveSettingsToDisk() { + s := getSettings() + + 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) { + switch r.Method { + case http.MethodGet: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(getSettings()) + return + + case http.MethodPost: + var in RecorderSettings + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest) + return + } + + // --- normalize (WICHTIG: erst trim, dann leer-check, dann clean) --- + recRaw := strings.TrimSpace(in.RecordDir) + doneRaw := strings.TrimSpace(in.DoneDir) + + if recRaw == "" || doneRaw == "" { + http.Error(w, "recordDir und doneDir dürfen nicht leer sein", http.StatusBadRequest) + return + } + + in.RecordDir = filepath.Clean(recRaw) + in.DoneDir = filepath.Clean(doneRaw) + + // Optional aber sehr empfehlenswert: "." verbieten + if in.RecordDir == "." || in.DoneDir == "." { + http.Error(w, "recordDir/doneDir dürfen nicht '.' sein", http.StatusBadRequest) + return + } + + 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" + } + + // Auto-Delete: clamp + if in.AutoDeleteSmallDownloadsBelowMB < 0 { + in.AutoDeleteSmallDownloadsBelowMB = 0 + } + if in.AutoDeleteSmallDownloadsBelowMB > 100_000 { + in.AutoDeleteSmallDownloadsBelowMB = 100_000 + } + + // --- ensure folders (Fehler zurückgeben, falls z.B. keine Rechte) --- + recAbs, err := resolvePathRelativeToApp(in.RecordDir) + if err != nil { + http.Error(w, "ungültiger recordDir: "+err.Error(), http.StatusBadRequest) + return + } + doneAbs, err := resolvePathRelativeToApp(in.DoneDir) + if err != nil { + http.Error(w, "ungültiger doneDir: "+err.Error(), http.StatusBadRequest) + return + } + + if err := os.MkdirAll(recAbs, 0o755); err != nil { + http.Error(w, "konnte recordDir nicht erstellen: "+err.Error(), http.StatusBadRequest) + return + } + if err := os.MkdirAll(doneAbs, 0o755); err != nil { + http.Error(w, "konnte doneDir nicht erstellen: "+err.Error(), http.StatusBadRequest) + return + } + + // ✅ Settings im RAM aktualisieren + settingsMu.Lock() + settings = in + settingsMu.Unlock() + + // ✅ Settings auf Disk persistieren + saveSettingsToDisk() + + // ✅ ffmpeg/ffprobe nach Änderungen neu bestimmen + // Tipp: wenn der User FFmpegPath explizit setzt, nutze den direkt. + if strings.TrimSpace(in.FFmpegPath) != "" { + ffmpegPath = in.FFmpegPath + } else { + ffmpegPath = detectFFmpegPath() + } + fmt.Println("🔍 ffmpegPath:", ffmpegPath) + + ffprobePath = detectFFprobePath() + fmt.Println("🔍 ffprobePath:", ffprobePath) + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(getSettings()) + return + + default: + http.Error(w, "Nur GET/POST erlaubt", http.StatusMethodNotAllowed) + return + } +} + +func settingsBrowse(w http.ResponseWriter, r *http.Request) { + target := r.URL.Query().Get("target") + if target != "record" && target != "done" && target != "ffmpeg" { + http.Error(w, "target muss record, done oder ffmpeg sein", http.StatusBadRequest) + return + } + + var ( + p string + err error + ) + + if target == "ffmpeg" { + // Dateiauswahl für ffmpeg.exe + p, err = dialog.File(). + Title("ffmpeg.exe auswählen"). + Load() + } else { + // Ordnerauswahl für record/done + p, err = dialog.Directory(). + Title("Ordner auswählen"). + Browse() + } + + if err != nil { + // User cancelled → 204 No Content ist praktisch fürs Frontend + if strings.Contains(strings.ToLower(err.Error()), "cancel") { + w.WriteHeader(http.StatusNoContent) + return + } + http.Error(w, "auswahl fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + + // optional: wenn innerhalb exe-dir, als RELATIV zurückgeben + p = maybeMakeRelativeToExe(p) + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"path": p}) +} + +func maybeMakeRelativeToExe(abs string) string { + exe, err := os.Executable() + if err != nil { + return abs + } + base := filepath.Dir(exe) + + rel, err := filepath.Rel(base, abs) + if err != nil { + return abs + } + // wenn rel mit ".." beginnt -> nicht innerhalb base -> absoluten Pfad behalten + if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return abs + } + return filepath.ToSlash(rel) // frontend-freundlich +} diff --git a/backend/transcode.go b/backend/transcode.go index b09a5c6..84b41a6 100644 --- a/backend/transcode.go +++ b/backend/transcode.go @@ -10,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strconv" "strings" "sync" @@ -37,6 +38,66 @@ type heightCacheEntry struct { var heightCacheMu sync.Mutex var heightCache = map[string]heightCacheEntry{} +type durationCacheEntry struct { + mtime time.Time + size int64 + dur float64 +} + +var durationCacheMu sync.Mutex +var durationCache = map[string]durationCacheEntry{} + +func probeVideoDurationSeconds(ctx context.Context, inPath string) (float64, error) { + // ffprobe -v error -show_entries format=duration -of csv=p=0 + cmd := exec.CommandContext(ctx, "ffprobe", + "-v", "error", + "-show_entries", "format=duration", + "-of", "csv=p=0", + inPath, + ) + out, err := cmd.Output() + if err != nil { + return 0, err + } + s := strings.TrimSpace(string(out)) + if s == "" { + return 0, fmt.Errorf("ffprobe returned empty duration") + } + d, err := strconv.ParseFloat(s, 64) + if err != nil || d <= 0 { + return 0, fmt.Errorf("bad duration %q", s) + } + return d, nil +} + +func getVideoDurationSecondsCached(ctx context.Context, inPath string) (float64, error) { + fi, err := os.Stat(inPath) + if err != nil || fi.IsDir() || fi.Size() <= 0 { + return 0, fmt.Errorf("input not usable") + } + + durationCacheMu.Lock() + if e, ok := durationCache[inPath]; ok { + if e.size == fi.Size() && e.mtime.Equal(fi.ModTime()) && e.dur > 0 { + d := e.dur + durationCacheMu.Unlock() + return d, nil + } + } + durationCacheMu.Unlock() + + d, err := probeVideoDurationSeconds(ctx, inPath) + if err != nil { + return 0, err + } + + durationCacheMu.Lock() + durationCache[inPath] = durationCacheEntry{mtime: fi.ModTime(), size: fi.Size(), dur: d} + durationCacheMu.Unlock() + + return d, nil +} + func probeVideoHeight(ctx context.Context, inPath string) (int, error) { // ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 cmd := exec.CommandContext(ctx, "ffprobe", @@ -93,27 +154,40 @@ type TranscodeProfile struct { Height int } -func profileFromQuality(q string) (TranscodeProfile, bool) { - switch strings.ToLower(strings.TrimSpace(q)) { - case "", "auto": - return TranscodeProfile{Name: "auto", Height: 0}, true - case "2160p": - return TranscodeProfile{Name: "2160p", Height: 2160}, true - case "1080p": - return TranscodeProfile{Name: "1080p", Height: 1080}, true - case "720p": - return TranscodeProfile{Name: "720p", Height: 720}, true - case "480p": - return TranscodeProfile{Name: "480p", Height: 480}, true - default: - return TranscodeProfile{}, false +func profileFromResolution(res string) (TranscodeProfile, bool) { + // Stash-like: LOW | MEDIUM | HIGH | ORIGINAL (case-insensitive) + s := strings.ToUpper(strings.TrimSpace(res)) + switch s { + case "", "ORIGINAL", "SOURCE", "AUTO": + return TranscodeProfile{Name: "ORIGINAL", Height: 0}, true + case "LOW": + return TranscodeProfile{Name: "LOW", Height: 480}, true + case "MEDIUM": + return TranscodeProfile{Name: "MEDIUM", Height: 720}, true + case "HIGH": + return TranscodeProfile{Name: "HIGH", Height: 1080}, true } + + // Backwards-Kompatibilität: "p" (z.B. 720p) + s2 := strings.ToLower(strings.TrimSpace(res)) + if m := regexp.MustCompile(`^(\d{3,4})p$`).FindStringSubmatch(s2); m != nil { + h, err := strconv.Atoi(m[1]) + if err != nil || h <= 0 { + return TranscodeProfile{}, false + } + if h < 144 || h > 4320 { + return TranscodeProfile{}, false + } + return TranscodeProfile{Name: fmt.Sprintf("%dp", h), Height: h}, true + } + + return TranscodeProfile{}, false } -// Cache layout: /.transcodes//.mp4 -func transcodeCachePath(doneAbs, canonicalID, quality string) string { - const v = "v1" - return filepath.Join(doneAbs, ".transcodes", canonicalID, v, quality+".mp4") +// Cache layout: /.transcodes////s.mp4 +func transcodeCachePath(doneAbs, canonicalID, quality string, startSec int) string { + const v = "v2" + return filepath.Join(doneAbs, ".transcodes", canonicalID, v, quality, fmt.Sprintf("s%d.mp4", startSec)) } func ensureFFmpegAvailable() error { @@ -204,15 +278,21 @@ func runFFmpeg(ctx context.Context, args []string) error { // Public entry used by recordVideo // ------------------------- -// maybeTranscodeForRequest inspects "quality" query param. +// maybeTranscodeForRequest inspects "resolution" query param. // If quality is "auto" (or empty), it returns original outPath unchanged. // Otherwise it ensures cached transcode exists & is fresh, and returns the cached path. -func maybeTranscodeForRequest(rctx context.Context, originalPath string, quality string) (string, error) { - prof, ok := profileFromQuality(quality) - if !ok { - return "", fmt.Errorf("bad quality %q", quality) +func maybeTranscodeForRequest(rctx context.Context, originalPath string, resolution string, startSec int) (string, error) { + if startSec < 0 { + startSec = 0 } - if prof.Name == "auto" { + // optional: auf 2 Sekunden runter runden, passt zu GOP=60 (~2s bei 30fps) + startSec = (startSec / 2) * 2 + + prof, ok := profileFromResolution(resolution) + if !ok { + return "", fmt.Errorf("bad resolution %q", resolution) + } + if strings.EqualFold(prof.Name, "ORIGINAL") || prof.Height <= 0 { return originalPath, nil } @@ -221,18 +301,22 @@ func maybeTranscodeForRequest(rctx context.Context, originalPath string, quality return "", err } - // optional: skip transcode if source is already <= requested height (prevents upscaling) + needScale := true + if prof.Height > 0 { - // ffprobe is needed only for this optimization if err := ensureFFprobeAvailable(); err == nil { - // short timeout for probing pctx, cancel := context.WithTimeout(rctx, 5*time.Second) defer cancel() if srcH, err := getVideoHeightCached(pctx, originalPath); err == nil && srcH > 0 { - // if source is already at/below requested (with tiny tolerance), don't transcode + // Quelle <= Ziel => kein Downscale nötig if srcH <= prof.Height+8 { - return originalPath, nil + needScale = false + + // ✅ WICHTIG: wenn startSec==0, liefern wir wirklich Original (keine Cache-Datei bauen) + if startSec == 0 { + return originalPath, nil + } } } } @@ -254,7 +338,8 @@ func maybeTranscodeForRequest(rctx context.Context, originalPath string, quality return "", fmt.Errorf("canonical id empty") } - cacheOut := transcodeCachePath(doneAbs, canonicalID, prof.Name) + qualityKey := strings.ToLower(strings.TrimSpace(prof.Name)) + cacheOut := transcodeCachePath(doneAbs, canonicalID, qualityKey, startSec) // fast path: already exists & fresh if isCacheFresh(originalPath, cacheOut) { @@ -293,7 +378,13 @@ func maybeTranscodeForRequest(rctx context.Context, originalPath string, quality _ = os.Remove(tmp) // ffmpeg args - args := buildFFmpegArgs(originalPath, tmp, prof) + var args []string + if needScale { + args = buildFFmpegArgs(originalPath, tmp, prof, startSec) + } else { + // ✅ nativer Seek: schneiden ohne re-encode + args = buildFFmpegCopySegmentArgs(originalPath, tmp, startSec) + } if err := runFFmpeg(ctx, args); err != nil { _ = os.Remove(tmp) @@ -335,18 +426,27 @@ func maybeTranscodeForRequest(rctx context.Context, originalPath string, quality // ffmpeg profiles // ------------------------- -func buildFFmpegArgs(inPath, outPath string, prof TranscodeProfile) []string { +func buildFFmpegArgs(inPath, outPath string, prof TranscodeProfile, startSec int) []string { // You can tune these defaults: // - CRF: lower => better quality, bigger file (1080p ~22, 720p ~23, 480p ~24/25) // - preset: veryfast is good for on-demand crf := "23" - switch prof.Name { - case "1080p": + h := prof.Height + switch { + case h >= 2160: + crf = "20" + case h >= 1440: + crf = "21" + case h >= 1080: crf = "22" - case "720p": + case h >= 720: crf = "23" - case "480p": + case h >= 480: crf = "25" + case h >= 360: + crf = "27" + default: + crf = "29" } // Keyframes: choose a stable value; if you want dynamic based on fps you can extend later. @@ -359,12 +459,27 @@ func buildFFmpegArgs(inPath, outPath string, prof TranscodeProfile) []string { // scale keeps aspect ratio, ensures even width vf := fmt.Sprintf("scale=-2:%d", prof.Height) - return []string{ + // sanitize start + if startSec < 0 { + startSec = 0 + } + // optional: align to small buckets to reduce cache fragmentation (and match GOP-ish seeking) + // startSec = (startSec / 2) * 2 + + args := []string{ "-hide_banner", "-loglevel", "error", "-nostdin", "-y", + } + // ✅ Startposition: VOR "-i" => schnelles Seek zum nächsten Keyframe (gut für on-demand) + // (Wenn du frame-genau willst: "-ss" NACH "-i", ist aber deutlich langsamer.) + if startSec > 0 { + args = append(args, "-ss", strconv.Itoa(startSec)) + } + + args = append(args, "-i", inPath, // ✅ robust: falls Audio fehlt, trotzdem kein Fehler @@ -394,58 +509,105 @@ func buildFFmpegArgs(inPath, outPath string, prof TranscodeProfile) []string { "-movflags", movflags, outPath, - } + ) + return args } -func buildFFmpegStreamArgs(inPath string, prof TranscodeProfile) []string { - crf := "23" - switch prof.Name { - case "1080p": - crf = "22" - case "720p": - crf = "23" - case "480p": - crf = "25" - } - - gop := "60" - vf := fmt.Sprintf("scale=-2:%d", prof.Height) - movflags := "frag_keyframe+empty_moov+default_base_moof" - - return []string{ +func buildFFmpegCopySegmentArgs(inPath, outPath string, startSec int) []string { + args := []string{ "-hide_banner", "-loglevel", "error", "-nostdin", "-y", - "-i", inPath, + } - // ✅ robust (wie im File-Transcode) + if startSec > 0 { + args = append(args, "-ss", strconv.Itoa(startSec)) + } + + args = append(args, + "-i", inPath, "-map", "0:v:0?", "-map", "0:a:0?", "-sn", - "-vf", vf, + // ✅ kein re-encode + "-c", "copy", + // ✅ fürs normale File: moov nach vorne + "-movflags", "+faststart", + + outPath, + ) + + return args +} + +func buildFFmpegStreamArgs(inPath string, prof TranscodeProfile) []string { + // Stash streamt MP4 als fragmented MP4 mit empty_moov + // (kein default_base_moof für "plain mp4 stream"). + movflags := "frag_keyframe+empty_moov" + + // Stash-ähnliche CRF-Werte + crf := "25" + switch strings.ToUpper(strings.TrimSpace(prof.Name)) { + case "HIGH", "1080P": + crf = "23" + case "MEDIUM", "720P": + crf = "25" + case "LOW", "480P": + crf = "27" + } + + args := []string{ + "-hide_banner", + "-loglevel", "error", + "-nostdin", + // "-y" ist bei pipe egal, kann aber bleiben – ich lasse es weg wie im Beispiel + } + + // Input + args = append(args, "-i", inPath) + + // robust: Video/Audio optional + args = append(args, + "-map", "0:v:0?", + "-map", "0:a:0?", + "-sn", + ) + + // Scale nur wenn wir wirklich runterskalieren wollen + if prof.Height > 0 { + vf := fmt.Sprintf("scale=-2:%d", prof.Height) + args = append(args, "-vf", vf) + } + + // Video + args = append(args, "-c:v", "libx264", "-preset", "veryfast", "-crf", crf, "-pix_fmt", "yuv420p", - "-max_muxing_queue_size", "1024", - - "-g", gop, - "-keyint_min", gop, "-sc_threshold", "0", + "-max_muxing_queue_size", "1024", + ) + // Audio (nur wenn vorhanden wegen map 0:a:0?) + args = append(args, "-c:a", "aac", "-b:a", "128k", "-ac", "2", + ) + // MP4 stream flags + args = append(args, "-movflags", movflags, - "-f", "mp4", - "pipe:1", - } + "pipe:", // wichtig: wie im Beispiel + ) + + return args } // ------------------------- diff --git a/backend/web/dist/assets/index-BRCxVTHL.css b/backend/web/dist/assets/index-BRCxVTHL.css deleted file mode 100644 index 3610dce..0000000 --- a/backend/web/dist/assets/index-BRCxVTHL.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-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-green-800:oklch(44.8% .119 151.328);--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-slate-200:oklch(92.9% .013 255.508);--color-slate-400:oklch(70.4% .04 256.788);--color-slate-500:oklch(55.4% .046 257.417);--color-slate-900:oklch(20.8% .042 265.755);--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-md:28rem;--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-4{top:calc(var(--spacing)*4)}.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-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-40{z-index:40}.z-50{z-index:50}.z-\[1\]{z-index:1}.z-\[60\]{z-index:60}.z-\[80\]{z-index:80}.z-\[9999\]{z-index:9999}.z-\[2147483647\]{z-index:2147483647}.col-span-1{grid-column:span 1/span 1}.col-span-2{grid-column:span 2/span 2}.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-5{margin-top:calc(var(--spacing)*5)}.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-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.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{height:calc(var(--spacing)*1)}.h-1\.5{height:calc(var(--spacing)*1.5)}.h-2{height:calc(var(--spacing)*2)}.h-2\.5{height:calc(var(--spacing)*2.5)}.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-44{height:calc(var(--spacing)*44)}.h-52{height:calc(var(--spacing)*52)}.h-60{height:calc(var(--spacing)*60)}.h-80{height:calc(var(--spacing)*80)}.h-\[60px\]{height:60px}.h-\[64px\]{height:64px}.h-\[220px\]{height:220px}.h-full{height:100%}.max-h-0{max-height:calc(var(--spacing)*0)}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-\[40vh\]{max-height:40vh}.max-h-\[80vh\]{max-height:80vh}.max-h-\[720px\]{max-height:720px}.max-h-\[calc\(100vh-3rem\)\]{max-height:calc(100vh - 3rem)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\[100dvh\]{min-height:100dvh}.min-h-full{min-height:100%}.w-1{width:calc(var(--spacing)*1)}.w-2\.5{width:calc(var(--spacing)*2.5)}.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-20{width:calc(var(--spacing)*20)}.w-28{width:calc(var(--spacing)*28)}.w-44{width:calc(var(--spacing)*44)}.w-52{width:calc(var(--spacing)*52)}.w-72{width:calc(var(--spacing)*72)}.w-\[46rem\]{width:46rem}.w-\[52rem\]{width:52rem}.w-\[64px\]{width:64px}.w-\[90px\]{width:90px}.w-\[92px\]{width:92px}.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-\[360px\]{width:360px}.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-\[420px\]{max-width:420px}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100\%-24px\)\]{max-width:calc(100% - 24px)}.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-md{max-width:var(--container-md)}.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-\[980px\]{min-width:980px}.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-1{--tw-translate-y:calc(var(--spacing)*-1);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-grab{cursor:grab}.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))}.grid-cols-\[minmax\(0\,1fr\)_auto_auto\]{grid-template-columns:minmax(0,1fr) auto auto}.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}.items-stretch{align-items:stretch}.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-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}: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-r{border-right-style:var(--tw-border-style);border-right-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-200{border-color:var(--color-indigo-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\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.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\/30{background-color:#0000004d}@supports (color:color-mix(in lab,red,red)){.bg-black\/30{background-color:color-mix(in oklab,var(--color-black)30%,transparent)}}.bg-black\/35{background-color:#00000059}@supports (color:color-mix(in lab,red,red)){.bg-black\/35{background-color:color-mix(in oklab,var(--color-black)35%,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\/70{background-color:#f3f4f6b3}@supports (color:color-mix(in lab,red,red)){.bg-gray-100\/70{background-color:color-mix(in oklab,var(--color-gray-100)70%,transparent)}}.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-100{background-color:var(--color-red-100)}.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-slate-500\/15{background-color:#62748e26}@supports (color:color-mix(in lab,red,red)){.bg-slate-500\/15{background-color:color-mix(in oklab,var(--color-slate-500)15%,transparent)}}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.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)}.pl-2{padding-left:calc(var(--spacing)*2)}.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}.break-all{word-break:break-all}.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-green-800{color:var(--color-green-800)}.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-slate-900{color:var(--color-slate-900)}.text-white{color:var(--color-white)}.text-white\/50{color:#ffffff80}@supports (color:color-mix(in lab,red,red)){.text-white\/50{color:color-mix(in oklab,var(--color-white)50%,transparent)}}.text-white\/60{color:#fff9}@supports (color:color-mix(in lab,red,red)){.text-white\/60{color:color-mix(in oklab,var(--color-white)60%,transparent)}}.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)}}.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)}}.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,.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)}.ring-2{--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)}.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-100{--tw-ring-color:var(--color-indigo-100)}.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-slate-500\/30{--tw-ring-color:#62748e4d}@supports (color:color-mix(in lab,red,red)){.ring-slate-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-slate-500)30%,transparent)}}.ring-white{--tw-ring-color:var(--color-white)}.ring-white\/10{--tw-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.ring-white\/10{--tw-ring-color:color-mix(in oklab,var(--color-white)10%,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,)}.blur-xl{--tw-blur:blur(var(--blur-xl));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,)}.filter{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-md{--tw-backdrop-blur:blur(var(--blur-md));-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-\[max-height\,opacity\]{transition-property:max-height,opacity;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-all{-webkit-user-select:all;user-select:all}.select-none{-webkit-user-select:none;user-select:none}.\[contain-intrinsic-size\:180px_120px\]{contain-intrinsic-size:180px 120px}.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\:translate-x-\[1px\]:is(:where(.group):hover *){--tw-translate-x:1px;translate:var(--tw-translate-x)var(--tw-translate-y)}.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\:-translate-y-\[1px\]:hover{--tw-translate-y: -1px ;translate:var(--tw-translate-x)var(--tw-translate-y)}.hover\:scale-\[1\.03\]:hover{scale:1.03}.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\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.focus-visible\:ring-offset-white:focus-visible{--tw-ring-offset-color:var(--color-white)}.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\:scale-\[0\.98\]:active{scale:.98}.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-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\:inset-x-auto{inset-inline:auto}.md\:right-auto{right:auto}.md\:bottom-4{bottom:calc(var(--spacing)*4)}.md\:left-1\/2{left:50%}.md\:inline-block{display:inline-block}.md\:w-\[min\(760px\,calc\(100vw-32px\)\)\]{width:min(760px,100vw - 32px)}.md\:-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}}@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(min-width:80rem){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@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-indigo-500\/30{border-color:#625fff4d}@supports (color:color-mix(in lab,red,red)){.dark\:border-indigo-500\/30{border-color:color-mix(in oklab,var(--color-indigo-500)30%,transparent)}}.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\/30{background-color:#0000004d}@supports (color:color-mix(in lab,red,red)){.dark\:bg-black\/30{background-color:color-mix(in oklab,var(--color-black)30%,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-black\/45{background-color:#00000073}@supports (color:color-mix(in lab,red,red)){.dark\:bg-black\/45{background-color:color-mix(in oklab,var(--color-black)45%,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\/60{background-color:#10182899}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/60{background-color:color-mix(in oklab,var(--color-gray-900)60%,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\/80{background-color:#030712cc}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/80{background-color:color-mix(in oklab,var(--color-gray-950)80%,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-green-500\/20{background-color:#00c75833}@supports (color:color-mix(in lab,red,red)){.dark\:bg-green-500\/20{background-color:color-mix(in oklab,var(--color-green-500)20%,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-slate-400\/10{background-color:#90a1b91a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-slate-400\/10{background-color:color-mix(in oklab,var(--color-slate-400)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\/35{background-color:#ffffff59}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/35{background-color:color-mix(in oklab,var(--color-white)35%,transparent)}}.dark\:bg-white\/\[0\.06\]{background-color:#ffffff0f}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/\[0\.06\]{background-color:color-mix(in oklab,var(--color-white)6%,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-slate-200{color:var(--color-slate-200)}.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-gray-950{--tw-ring-color:var(--color-gray-950)}.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-indigo-500\/20{--tw-ring-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:ring-indigo-500\/20{--tw-ring-color:color-mix(in oklab,var(--color-indigo-500)20%,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-slate-400\/25{--tw-ring-color:#90a1b940}@supports (color:color-mix(in lab,red,red)){.dark\:ring-slate-400\/25{--tw-ring-color:color-mix(in oklab,var(--color-slate-400)25%,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\/20:hover{background-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/20:hover{background-color:color-mix(in oklab,var(--color-indigo-500)20%,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\:bg-white\/\[0\.09\]:hover{background-color:#ffffff17}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/\[0\.09\]:hover{background-color:color-mix(in oklab,var(--color-white)9%,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\:ring-offset-gray-950:focus-visible{--tw-ring-offset-color:var(--color-gray-950)}.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}.video-js{position:relative}.video-js .vjs-control-bar{z-index:60;position:relative}.video-js .vjs-menu-button-popup .vjs-menu,.video-js .vjs-volume-panel .vjs-volume-control{z-index:9999!important}.vjs-mini .video-js .vjs-current-time,.vjs-mini .video-js .vjs-time-divider,.vjs-mini .video-js .vjs-duration{opacity:1!important;visibility:visible!important;display:flex!important}.vjs-mini .video-js .vjs-current-time-display,.vjs-mini .video-js .vjs-duration-display{display:inline!important}.video-js .vjs-time-control{width:auto!important;min-width:0!important;padding-left:.35em!important;padding-right:.35em!important}.video-js .vjs-time-divider{padding-left:.15em!important;padding-right:.15em!important}.video-js .vjs-time-divider>div{padding:0!important}.video-js .vjs-current-time-display,.video-js .vjs-duration-display{font-variant-numeric:tabular-nums;font-size:.95em}@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-DV6ZfOPf.js b/backend/web/dist/assets/index-DV6ZfOPf.js deleted file mode 100644 index ea622a4..0000000 --- a/backend/web/dist/assets/index-DV6ZfOPf.js +++ /dev/null @@ -1,419 +0,0 @@ -function kI(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 a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).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 Qm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function DI(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 ly={exports:{}},zd={};var lS;function LI(){if(lS)return zd;lS=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var a=null;if(r!==void 0&&(a=""+r),n.key!==void 0&&(a=""+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:a,ref:n!==void 0?n:null,props:r}}return zd.Fragment=e,zd.jsx=t,zd.jsxs=t,zd}var uS;function RI(){return uS||(uS=1,ly.exports=LI()),ly.exports}var g=RI(),uy={exports:{}},ai={};var cS;function II(){if(cS)return ai;cS=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"),a=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"),y=Symbol.iterator;function v(F){return F===null||typeof F!="object"?null:(F=y&&F[y]||F["@@iterator"],typeof F=="function"?F:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,E={};function L(F,ee,he){this.props=F,this.context=ee,this.refs=E,this.updater=he||b}L.prototype.isReactComponent={},L.prototype.setState=function(F,ee){if(typeof F!="object"&&typeof F!="function"&&F!=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,F,ee,"setState")},L.prototype.forceUpdate=function(F){this.updater.enqueueForceUpdate(this,F,"forceUpdate")};function I(){}I.prototype=L.prototype;function R(F,ee,he){this.props=F,this.context=ee,this.refs=E,this.updater=he||b}var $=R.prototype=new I;$.constructor=R,_($,L.prototype),$.isPureReactComponent=!0;var P=Array.isArray;function B(){}var O={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function D(F,ee,he){var be=he.ref;return{$$typeof:s,type:F,key:ee,ref:be!==void 0?be:null,props:he}}function M(F,ee){return D(F.type,ee,F.props)}function W(F){return typeof F=="object"&&F!==null&&F.$$typeof===s}function K(F){var ee={"=":"=0",":":"=2"};return"$"+F.replace(/[=:]/g,function(he){return ee[he]})}var J=/\/+/g;function ue(F,ee){return typeof F=="object"&&F!==null&&F.key!=null?K(""+F.key):ee.toString(36)}function se(F){switch(F.status){case"fulfilled":return F.value;case"rejected":throw F.reason;default:switch(typeof F.status=="string"?F.then(B,B):(F.status="pending",F.then(function(ee){F.status==="pending"&&(F.status="fulfilled",F.value=ee)},function(ee){F.status==="pending"&&(F.status="rejected",F.reason=ee)})),F.status){case"fulfilled":return F.value;case"rejected":throw F.reason}}throw F}function q(F,ee,he,be,pe){var Ce=typeof F;(Ce==="undefined"||Ce==="boolean")&&(F=null);var Re=!1;if(F===null)Re=!0;else switch(Ce){case"bigint":case"string":case"number":Re=!0;break;case"object":switch(F.$$typeof){case s:case e:Re=!0;break;case f:return Re=F._init,q(Re(F._payload),ee,he,be,pe)}}if(Re)return pe=pe(F),Re=be===""?"."+ue(F,0):be,P(pe)?(he="",Re!=null&&(he=Re.replace(J,"$&/")+"/"),q(pe,ee,he,"",function(it){return it})):pe!=null&&(W(pe)&&(pe=M(pe,he+(pe.key==null||F&&F.key===pe.key?"":(""+pe.key).replace(J,"$&/")+"/")+Re)),ee.push(pe)),1;Re=0;var Ze=be===""?".":be+":";if(P(F))for(var Ge=0;Ge>>1,oe=q[Q];if(0>>1;Qn(he,ie))ben(pe,he)?(q[Q]=pe,q[be]=ie,Q=be):(q[Q]=he,q[ee]=ie,Q=ee);else if(ben(pe,ie))q[Q]=pe,q[be]=ie,Q=be;else break e}}return Y}function n(q,Y){var ie=q.sortIndex-Y.sortIndex;return ie!==0?ie:q.id-Y.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 a=Date,u=a.now();s.unstable_now=function(){return a.now()-u}}var c=[],d=[],f=1,p=null,y=3,v=!1,b=!1,_=!1,E=!1,L=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function $(q){for(var Y=t(d);Y!==null;){if(Y.callback===null)i(d);else if(Y.startTime<=q)i(d),Y.sortIndex=Y.expirationTime,e(c,Y);else break;Y=t(d)}}function P(q){if(_=!1,$(q),!b)if(t(c)!==null)b=!0,B||(B=!0,K());else{var Y=t(d);Y!==null&&se(P,Y.startTime-q)}}var B=!1,O=-1,H=5,D=-1;function M(){return E?!0:!(s.unstable_now()-Dq&&M());){var Q=p.callback;if(typeof Q=="function"){p.callback=null,y=p.priorityLevel;var oe=Q(p.expirationTime<=q);if(q=s.unstable_now(),typeof oe=="function"){p.callback=oe,$(q),Y=!0;break t}p===t(c)&&i(c),$(q)}else i(c);p=t(c)}if(p!==null)Y=!0;else{var F=t(d);F!==null&&se(P,F.startTime-q),Y=!1}}break e}finally{p=null,y=ie,v=!1}Y=void 0}}finally{Y?K():B=!1}}}var K;if(typeof R=="function")K=function(){R(W)};else if(typeof MessageChannel<"u"){var J=new MessageChannel,ue=J.port2;J.port1.onmessage=W,K=function(){ue.postMessage(null)}}else K=function(){L(W,0)};function se(q,Y){O=L(function(){q(s.unstable_now())},Y)}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(q){q.callback=null},s.unstable_forceFrameRate=function(q){0>q||125Q?(q.sortIndex=ie,e(d,q),t(c)===null&&q===t(d)&&(_?(I(O),O=-1):_=!0,se(P,ie-Q))):(q.sortIndex=oe,e(c,q),b||v||(b=!0,B||(B=!0,K()))),q},s.unstable_shouldYield=M,s.unstable_wrapCallback=function(q){var Y=y;return function(){var ie=y;y=Y;try{return q.apply(this,arguments)}finally{y=ie}}}})(hy)),hy}var mS;function OI(){return mS||(mS=1,dy.exports=NI()),dy.exports}var fy={exports:{}},xn={};var pS;function MI(){if(pS)return xn;pS=1;var s=Pp();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(),fy.exports=MI(),fy.exports}var yS;function PI(){if(yS)return qd;yS=1;var s=OI(),e=Pp(),t=sA();function i(o){var l="https://react.dev/errors/"+o;if(1oe||(o.current=Q[oe],Q[oe]=null,oe--)}function he(o,l){oe++,Q[oe]=o.current,o.current=l}var be=F(null),pe=F(null),Ce=F(null),Re=F(null);function Ze(o,l){switch(he(Ce,l),he(pe,o),he(be,null),l.nodeType){case 9:case 11:o=(o=l.documentElement)&&(o=o.namespaceURI)?R_(o):0;break;default:if(o=l.tagName,l=l.namespaceURI)l=R_(l),o=I_(l,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}ee(be),he(be,o)}function Ge(){ee(be),ee(pe),ee(Ce)}function it(o){o.memoizedState!==null&&he(Re,o);var l=be.current,h=I_(l,o.type);l!==h&&(he(pe,o),he(be,h))}function dt(o){pe.current===o&&(ee(be),ee(pe)),Re.current===o&&(ee(Re),$d._currentValue=ie)}var ot,nt;function ft(o){if(ot===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);ot=l&&l[1]||"",nt=-1)":-1T||ve[m]!==Ne[T]){var $e=` -`+ve[m].replace(" at new "," at ");return o.displayName&&$e.includes("")&&($e=$e.replace("",o.displayName)),$e}while(1<=m&&0<=T);break}}}finally{gt=!1,Error.prepareStackTrace=h}return(h=o?o.displayName||o.name:"")?ft(h):""}function bt(o,l){switch(o.tag){case 26:case 27:case 5:return ft(o.type);case 16:return ft("Lazy");case 13:return o.child!==l&&l!==null?ft("Suspense Fallback"):ft("Suspense");case 19:return ft("SuspenseList");case 0:case 15:return je(o.type,!1);case 11:return je(o.type.render,!1);case 1:return je(o.type,!0);case 31:return ft("Activity");default:return""}}function vt(o){try{var l="",h=null;do l+=bt(o,h),h=o,o=o.return;while(o);return l}catch(m){return` -Error generating stack: `+m.message+` -`+m.stack}}var jt=Object.prototype.hasOwnProperty,We=s.unstable_scheduleCallback,ut=s.unstable_cancelCallback,ge=s.unstable_shouldYield,Je=s.unstable_requestPaint,Ye=s.unstable_now,Qe=s.unstable_getCurrentPriorityLevel,mt=s.unstable_ImmediatePriority,ct=s.unstable_UserBlockingPriority,et=s.unstable_NormalPriority,Gt=s.unstable_LowPriority,Jt=s.unstable_IdlePriority,It=s.log,Ft=s.unstable_setDisableYieldValue,$t=null,Ke=null;function Lt(o){if(typeof It=="function"&&Ft(o),Ke&&typeof Ke.setStrictMode=="function")try{Ke.setStrictMode($t,o)}catch{}}var Qt=Math.clz32?Math.clz32:vi,Ut=Math.log,ci=Math.LN2;function vi(o){return o>>>=0,o===0?32:31-(Ut(o)/ci|0)|0}var ei=256,Bi=262144,yt=4194304;function z(o){var l=o&42;if(l!==0)return l;switch(o&-o){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 o&261888;case 262144:case 524288:case 1048576:case 2097152:return o&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return o&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return o}}function V(o,l,h){var m=o.pendingLanes;if(m===0)return 0;var T=0,S=o.suspendedLanes,j=o.pingedLanes;o=o.warmLanes;var Z=m&134217727;return Z!==0?(m=Z&~S,m!==0?T=z(m):(j&=Z,j!==0?T=z(j):h||(h=Z&~o,h!==0&&(T=z(h))))):(Z=m&~S,Z!==0?T=z(Z):j!==0?T=z(j):h||(h=m&~o,h!==0&&(T=z(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 te(o,l){return(o.pendingLanes&~(o.suspendedLanes&~o.pingedLanes)&l)===0}function _e(o,l){switch(o){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 Oe(){var o=yt;return yt<<=1,(yt&62914560)===0&&(yt=4194304),o}function tt(o){for(var l=[],h=0;31>h;h++)l.push(o);return l}function Ot(o,l){o.pendingLanes|=l,l!==268435456&&(o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0)}function xi(o,l,h,m,T,S){var j=o.pendingLanes;o.pendingLanes=h,o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0,o.expiredLanes&=h,o.entangledLanes&=h,o.errorRecoveryDisabledLanes&=h,o.shellSuspendCounter=0;var Z=o.entanglements,ve=o.expirationTimes,Ne=o.hiddenUpdates;for(h=j&~h;0"u")return null;try{return o.activeElement||o.body}catch{return o.body}}var Tt=/[\n"\\]/g;function Bt(o){return o.replace(Tt,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function lt(o,l,h,m,T,S,j,Z){o.name="",j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?o.type=j:o.removeAttribute("type"),l!=null?j==="number"?(l===0&&o.value===""||o.value!=l)&&(o.value=""+xe(l)):o.value!==""+xe(l)&&(o.value=""+xe(l)):j!=="submit"&&j!=="reset"||o.removeAttribute("value"),l!=null?Et(o,j,xe(l)):h!=null?Et(o,j,xe(h)):m!=null&&o.removeAttribute("value"),T==null&&S!=null&&(o.defaultChecked=!!S),T!=null&&(o.checked=T&&typeof T!="function"&&typeof T!="symbol"),Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"?o.name=""+xe(Z):o.removeAttribute("name")}function pt(o,l,h,m,T,S,j,Z){if(S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(o.type=S),l!=null||h!=null){if(!(S!=="submit"&&S!=="reset"||l!=null)){st(o);return}h=h!=null?""+xe(h):"",l=l!=null?""+xe(l):h,Z||l===o.value||(o.value=l),o.defaultValue=l}m=m??T,m=typeof m!="function"&&typeof m!="symbol"&&!!m,o.checked=Z?o.checked:!!m,o.defaultChecked=!!m,j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"&&(o.name=j),st(o)}function Et(o,l,h){l==="number"&&kt(o.ownerDocument)===o||o.defaultValue===""+h||(o.defaultValue=""+h)}function Nt(o,l,h,m){if(o=o.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),go=!1;if(pn)try{var Qr={};Object.defineProperty(Qr,"passive",{get:function(){go=!0}}),window.addEventListener("test",Qr,Qr),window.removeEventListener("test",Qr,Qr)}catch{go=!1}var sr=null,xl=null,Ma=null;function hs(){if(Ma)return Ma;var o,l=xl,h=l.length,m,T="value"in sr?sr.value:sr.textContent,S=T.length;for(o=0;o=El),ef=" ",Qc=!1;function Tu(o,l){switch(o){case"keyup":return A0.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function tf(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var To=!1;function C0(o,l){switch(o){case"compositionend":return tf(l);case"keypress":return l.which!==32?null:(Qc=!0,ef);case"textInput":return o=l.data,o===ef&&Qc?null:o;default:return null}}function Zc(o,l){if(To)return o==="compositionend"||!bo&&Tu(o,l)?(o=hs(),Ma=xl=sr=null,To=!1,o):null;switch(o){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-o};o=m}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=So(h)}}function Fa(o,l){return o&&l?o===l?!0:o&&o.nodeType===3?!1:l&&l.nodeType===3?Fa(o,l.parentNode):"contains"in o?o.contains(l):o.compareDocumentPosition?!!(o.compareDocumentPosition(l)&16):!1:!1}function _u(o){o=o!=null&&o.ownerDocument!=null&&o.ownerDocument.defaultView!=null?o.ownerDocument.defaultView:window;for(var l=kt(o.document);l instanceof o.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)o=l.contentWindow;else break;l=kt(o.document)}return l}function nd(o){var l=o&&o.nodeName&&o.nodeName.toLowerCase();return l&&(l==="input"&&(o.type==="text"||o.type==="search"||o.type==="tel"||o.type==="url"||o.type==="password")||l==="textarea"||o.contentEditable==="true")}var N0=pn&&"documentMode"in document&&11>=document.documentMode,Eo=null,rd=null,wo=null,Su=!1;function ad(o,l,h){var m=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Su||Eo==null||Eo!==kt(m)||(m=Eo,"selectionStart"in m&&nd(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}),wo&&Jr(wo,m)||(wo=m,m=Yf(rd,"onSelect"),0>=j,T-=j,ar=1<<32-Qt(l)+T|h<di?(wi=Mt,Mt=null):wi=Mt.sibling;var Ii=Me(Ae,Mt,Ie[di],ze);if(Ii===null){Mt===null&&(Mt=wi);break}o&&Mt&&Ii.alternate===null&&l(Ae,Mt),Te=S(Ii,Te,di),Ri===null?Ht=Ii:Ri.sibling=Ii,Ri=Ii,Mt=wi}if(di===Ie.length)return h(Ae,Mt),Ti&&hi(Ae,di),Ht;if(Mt===null){for(;didi?(wi=Mt,Mt=null):wi=Mt.sibling;var Xo=Me(Ae,Mt,Ii.value,ze);if(Xo===null){Mt===null&&(Mt=wi);break}o&&Mt&&Xo.alternate===null&&l(Ae,Mt),Te=S(Xo,Te,di),Ri===null?Ht=Xo:Ri.sibling=Xo,Ri=Xo,Mt=wi}if(Ii.done)return h(Ae,Mt),Ti&&hi(Ae,di),Ht;if(Mt===null){for(;!Ii.done;di++,Ii=Ie.next())Ii=qe(Ae,Ii.value,ze),Ii!==null&&(Te=S(Ii,Te,di),Ri===null?Ht=Ii:Ri.sibling=Ii,Ri=Ii);return Ti&&hi(Ae,di),Ht}for(Mt=m(Mt);!Ii.done;di++,Ii=Ie.next())Ii=Be(Mt,Ae,di,Ii.value,ze),Ii!==null&&(o&&Ii.alternate!==null&&Mt.delete(Ii.key===null?di:Ii.key),Te=S(Ii,Te,di),Ri===null?Ht=Ii:Ri.sibling=Ii,Ri=Ii);return o&&Mt.forEach(function(CI){return l(Ae,CI)}),Ti&&hi(Ae,di),Ht}function Yi(Ae,Te,Ie,ze){if(typeof Ie=="object"&&Ie!==null&&Ie.type===_&&Ie.key===null&&(Ie=Ie.props.children),typeof Ie=="object"&&Ie!==null){switch(Ie.$$typeof){case v:e:{for(var Ht=Ie.key;Te!==null;){if(Te.key===Ht){if(Ht=Ie.type,Ht===_){if(Te.tag===7){h(Ae,Te.sibling),ze=T(Te,Ie.props.children),ze.return=Ae,Ae=ze;break e}}else if(Te.elementType===Ht||typeof Ht=="object"&&Ht!==null&&Ht.$$typeof===H&&Ml(Ht)===Te.type){h(Ae,Te.sibling),ze=T(Te,Ie.props),vd(ze,Ie),ze.return=Ae,Ae=ze;break e}h(Ae,Te);break}else l(Ae,Te);Te=Te.sibling}Ie.type===_?(ze=ta(Ie.props.children,Ae.mode,ze,Ie.key),ze.return=Ae,Ae=ze):(ze=fd(Ie.type,Ie.key,Ie.props,null,Ae.mode,ze),vd(ze,Ie),ze.return=Ae,Ae=ze)}return j(Ae);case b:e:{for(Ht=Ie.key;Te!==null;){if(Te.key===Ht)if(Te.tag===4&&Te.stateNode.containerInfo===Ie.containerInfo&&Te.stateNode.implementation===Ie.implementation){h(Ae,Te.sibling),ze=T(Te,Ie.children||[]),ze.return=Ae,Ae=ze;break e}else{h(Ae,Te);break}else l(Ae,Te);Te=Te.sibling}ze=Lo(Ie,Ae.mode,ze),ze.return=Ae,Ae=ze}return j(Ae);case H:return Ie=Ml(Ie),Yi(Ae,Te,Ie,ze)}if(se(Ie))return Ct(Ae,Te,Ie,ze);if(K(Ie)){if(Ht=K(Ie),typeof Ht!="function")throw Error(i(150));return Ie=Ht.call(Ie),Wt(Ae,Te,Ie,ze)}if(typeof Ie.then=="function")return Yi(Ae,Te,xf(Ie),ze);if(Ie.$$typeof===R)return Yi(Ae,Te,si(Ae,Ie),ze);bf(Ae,Ie)}return typeof Ie=="string"&&Ie!==""||typeof Ie=="number"||typeof Ie=="bigint"?(Ie=""+Ie,Te!==null&&Te.tag===6?(h(Ae,Te.sibling),ze=T(Te,Ie),ze.return=Ae,Ae=ze):(h(Ae,Te),ze=Ll(Ie,Ae.mode,ze),ze.return=Ae,Ae=ze),j(Ae)):h(Ae,Te)}return function(Ae,Te,Ie,ze){try{yd=0;var Ht=Yi(Ae,Te,Ie,ze);return Du=null,Ht}catch(Mt){if(Mt===ku||Mt===yf)throw Mt;var Ri=Ss(29,Mt,null,Ae.mode);return Ri.lanes=ze,Ri.return=Ae,Ri}}}var Bl=_T(!0),ST=_T(!1),No=!1;function F0(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function U0(o,l){o=o.updateQueue,l.updateQueue===o&&(l.updateQueue={baseState:o.baseState,firstBaseUpdate:o.firstBaseUpdate,lastBaseUpdate:o.lastBaseUpdate,shared:o.shared,callbacks:null})}function Oo(o){return{lane:o,tag:0,payload:null,callback:null,next:null}}function Mo(o,l,h){var m=o.updateQueue;if(m===null)return null;if(m=m.shared,(Ni&2)!==0){var T=m.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),m.pending=l,l=Au(o),hf(o,null,h),l}return wu(o,m,l,h),Au(o)}function xd(o,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,zi(o,h)}}function j0(o,l){var h=o.updateQueue,m=o.alternate;if(m!==null&&(m=m.updateQueue,h===m)){var T=null,S=null;if(h=h.firstBaseUpdate,h!==null){do{var j={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};S===null?T=S=j:S=S.next=j,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},o.updateQueue=h;return}o=h.lastBaseUpdate,o===null?h.firstBaseUpdate=l:o.next=l,h.lastBaseUpdate=l}var $0=!1;function bd(){if($0){var o=Js;if(o!==null)throw o}}function Td(o,l,h,m){$0=!1;var T=o.updateQueue;No=!1;var S=T.firstBaseUpdate,j=T.lastBaseUpdate,Z=T.shared.pending;if(Z!==null){T.shared.pending=null;var ve=Z,Ne=ve.next;ve.next=null,j===null?S=Ne:j.next=Ne,j=ve;var $e=o.alternate;$e!==null&&($e=$e.updateQueue,Z=$e.lastBaseUpdate,Z!==j&&(Z===null?$e.firstBaseUpdate=Ne:Z.next=Ne,$e.lastBaseUpdate=ve))}if(S!==null){var qe=T.baseState;j=0,$e=Ne=ve=null,Z=S;do{var Me=Z.lane&-536870913,Be=Me!==Z.lane;if(Be?(Ei&Me)===Me:(m&Me)===Me){Me!==0&&Me===Sr&&($0=!0),$e!==null&&($e=$e.next={lane:0,tag:Z.tag,payload:Z.payload,callback:null,next:null});e:{var Ct=o,Wt=Z;Me=l;var Yi=h;switch(Wt.tag){case 1:if(Ct=Wt.payload,typeof Ct=="function"){qe=Ct.call(Yi,qe,Me);break e}qe=Ct;break e;case 3:Ct.flags=Ct.flags&-65537|128;case 0:if(Ct=Wt.payload,Me=typeof Ct=="function"?Ct.call(Yi,qe,Me):Ct,Me==null)break e;qe=p({},qe,Me);break e;case 2:No=!0}}Me=Z.callback,Me!==null&&(o.flags|=64,Be&&(o.flags|=8192),Be=T.callbacks,Be===null?T.callbacks=[Me]:Be.push(Me))}else Be={lane:Me,tag:Z.tag,payload:Z.payload,callback:Z.callback,next:null},$e===null?(Ne=$e=Be,ve=qe):$e=$e.next=Be,j|=Me;if(Z=Z.next,Z===null){if(Z=T.shared.pending,Z===null)break;Be=Z,Z=Be.next,Be.next=null,T.lastBaseUpdate=Be,T.shared.pending=null}}while(!0);$e===null&&(ve=qe),T.baseState=ve,T.firstBaseUpdate=Ne,T.lastBaseUpdate=$e,S===null&&(T.shared.lanes=0),jo|=j,o.lanes=j,o.memoizedState=qe}}function ET(o,l){if(typeof o!="function")throw Error(i(191,o));o.call(l)}function wT(o,l){var h=o.callbacks;if(h!==null)for(o.callbacks=null,o=0;oS?S:8;var j=q.T,Z={};q.T=Z,ag(o,!1,l,h);try{var ve=T(),Ne=q.S;if(Ne!==null&&Ne(Z,ve),ve!==null&&typeof ve=="object"&&typeof ve.then=="function"){var $e=gR(ve,m);Ed(o,l,$e,dr(o))}else Ed(o,l,m,dr(o))}catch(qe){Ed(o,l,{then:function(){},status:"rejected",reason:qe},dr())}finally{Y.p=S,j!==null&&Z.types!==null&&(j.types=Z.types),q.T=j}}function _R(){}function ng(o,l,h,m){if(o.tag!==5)throw Error(i(476));var T=s1(o).queue;i1(o,T,l,ie,h===null?_R:function(){return n1(o),h(m)})}function s1(o){var l=o.memoizedState;if(l!==null)return l;l={memoizedState:ie,baseState:ie,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ga,lastRenderedState:ie},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ga,lastRenderedState:h},next:null},o.memoizedState=l,o=o.alternate,o!==null&&(o.memoizedState=l),l}function n1(o){var l=s1(o);l.next===null&&(l=o.alternate.memoizedState),Ed(o,l.next.queue,{},dr())}function rg(){return _t($d)}function r1(){return Rs().memoizedState}function a1(){return Rs().memoizedState}function SR(o){for(var l=o.return;l!==null;){switch(l.tag){case 24:case 3:var h=dr();o=Oo(h);var m=Mo(l,o,h);m!==null&&(Vn(m,l,h),xd(m,l,h)),l={cache:$a()},o.payload=l;return}l=l.return}}function ER(o,l,h){var m=dr();h={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},Lf(o)?l1(l,h):(h=dd(o,l,h,m),h!==null&&(Vn(h,o,m),u1(h,l,m)))}function o1(o,l,h){var m=dr();Ed(o,l,h,m)}function Ed(o,l,h,m){var T={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(Lf(o))l1(l,T);else{var S=o.alternate;if(o.lanes===0&&(S===null||S.lanes===0)&&(S=l.lastRenderedReducer,S!==null))try{var j=l.lastRenderedState,Z=S(j,h);if(T.hasEagerState=!0,T.eagerState=Z,yn(Z,j))return wu(o,l,T,0),Ji===null&&Eu(),!1}catch{}if(h=dd(o,l,T,m),h!==null)return Vn(h,o,m),u1(h,l,m),!0}return!1}function ag(o,l,h,m){if(m={lane:2,revertLane:Fg(),gesture:null,action:m,hasEagerState:!1,eagerState:null,next:null},Lf(o)){if(l)throw Error(i(479))}else l=dd(o,h,m,2),l!==null&&Vn(l,o,2)}function Lf(o){var l=o.alternate;return o===ui||l!==null&&l===ui}function l1(o,l){Ru=Sf=!0;var h=o.pending;h===null?l.next=l:(l.next=h.next,h.next=l),o.pending=l}function u1(o,l,h){if((h&4194048)!==0){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,zi(o,h)}}var wd={readContext:_t,use:Af,useCallback:Es,useContext:Es,useEffect:Es,useImperativeHandle:Es,useLayoutEffect:Es,useInsertionEffect:Es,useMemo:Es,useReducer:Es,useRef:Es,useState:Es,useDebugValue:Es,useDeferredValue:Es,useTransition:Es,useSyncExternalStore:Es,useId:Es,useHostTransitionStatus:Es,useFormState:Es,useActionState:Es,useOptimistic:Es,useMemoCache:Es,useCacheRefresh:Es};wd.useEffectEvent=Es;var c1={readContext:_t,use:Af,useCallback:function(o,l){return wn().memoizedState=[o,l===void 0?null:l],o},useContext:_t,useEffect:KT,useImperativeHandle:function(o,l,h){h=h!=null?h.concat([o]):null,kf(4194308,4,QT.bind(null,l,o),h)},useLayoutEffect:function(o,l){return kf(4194308,4,o,l)},useInsertionEffect:function(o,l){kf(4,2,o,l)},useMemo:function(o,l){var h=wn();l=l===void 0?null:l;var m=o();if(Fl){Lt(!0);try{o()}finally{Lt(!1)}}return h.memoizedState=[m,l],m},useReducer:function(o,l,h){var m=wn();if(h!==void 0){var T=h(l);if(Fl){Lt(!0);try{h(l)}finally{Lt(!1)}}}else T=l;return m.memoizedState=m.baseState=T,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:o,lastRenderedState:T},m.queue=o,o=o.dispatch=ER.bind(null,ui,o),[m.memoizedState,o]},useRef:function(o){var l=wn();return o={current:o},l.memoizedState=o},useState:function(o){o=J0(o);var l=o.queue,h=o1.bind(null,ui,l);return l.dispatch=h,[o.memoizedState,h]},useDebugValue:ig,useDeferredValue:function(o,l){var h=wn();return sg(h,o,l)},useTransition:function(){var o=J0(!1);return o=i1.bind(null,ui,o.queue,!0,!1),wn().memoizedState=o,[!1,o]},useSyncExternalStore:function(o,l,h){var m=ui,T=wn();if(Ti){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),Ji===null)throw Error(i(349));(Ei&127)!==0||RT(m,l,h)}T.memoizedState=h;var S={value:h,getSnapshot:l};return T.queue=S,KT(NT.bind(null,m,S,o),[o]),m.flags|=2048,Nu(9,{destroy:void 0},IT.bind(null,m,S,h,l),null),h},useId:function(){var o=wn(),l=Ji.identifierPrefix;if(Ti){var h=an,m=ar;h=(m&~(1<<32-Qt(m)-1)).toString(32)+h,l="_"+l+"R_"+h,h=Ef++,0<\/script>",S=S.removeChild(S.firstChild);break;case"select":S=typeof m.is=="string"?j.createElement("select",{is:m.is}):j.createElement("select"),m.multiple?S.multiple=!0:m.size&&(S.size=m.size);break;default:S=typeof m.is=="string"?j.createElement(T,{is:m.is}):j.createElement(T)}}S[oi]=l,S[ti]=m;e:for(j=l.child;j!==null;){if(j.tag===5||j.tag===6)S.appendChild(j.stateNode);else if(j.tag!==4&&j.tag!==27&&j.child!==null){j.child.return=j,j=j.child;continue}if(j===l)break e;for(;j.sibling===null;){if(j.return===null||j.return===l)break e;j=j.return}j.sibling.return=j.return,j=j.sibling}l.stateNode=S;e:switch(ln(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&&za(l)}}return ds(l),bg(l,l.type,o===null?null:o.memoizedProps,l.pendingProps,h),null;case 6:if(o&&l.stateNode!=null)o.memoizedProps!==m&&za(l);else{if(typeof m!="string"&&l.stateNode===null)throw Error(i(166));if(o=Ce.current,x(l)){if(o=l.stateNode,h=l.memoizedProps,m=null,T=Ps,T!==null)switch(T.tag){case 27:case 5:m=T.memoizedProps}o[oi]=l,o=!!(o.nodeValue===h||m!==null&&m.suppressHydrationWarning===!0||D_(o.nodeValue,h)),o||ra(l,!0)}else o=Xf(o).createTextNode(m),o[oi]=l,l.stateNode=o}return ds(l),null;case 31:if(h=l.memoizedState,o===null||o.memoizedState!==null){if(m=x(l),h!==null){if(o===null){if(!m)throw Error(i(318));if(o=l.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(i(557));o[oi]=l}else A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ds(l),o=!1}else h=k(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=h),o=!0;if(!o)return l.flags&256?(lr(l),l):(lr(l),null);if((l.flags&128)!==0)throw Error(i(558))}return ds(l),null;case 13:if(m=l.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(T=x(l),m!==null&&m.dehydrated!==null){if(o===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 A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ds(l),T=!1}else T=k(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(lr(l),l):(lr(l),null)}return lr(l),(l.flags&128)!==0?(l.lanes=h,l):(h=m!==null,o=o!==null&&o.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!==o&&h&&(l.child.flags|=8192),Mf(l,l.updateQueue),ds(l),null);case 4:return Ge(),o===null&&Hg(l.stateNode.containerInfo),ds(l),null;case 10:return de(l.type),ds(l),null;case 19:if(ee(Ls),m=l.memoizedState,m===null)return ds(l),null;if(T=(l.flags&128)!==0,S=m.rendering,S===null)if(T)Cd(m,!1);else{if(ws!==0||o!==null&&(o.flags&128)!==0)for(o=l.child;o!==null;){if(S=_f(o),S!==null){for(l.flags|=128,Cd(m,!1),o=S.updateQueue,l.updateQueue=o,Mf(l,o),l.subtreeFlags=0,o=h,h=l.child;h!==null;)ff(h,o),h=h.sibling;return he(Ls,Ls.current&1|2),Ti&&hi(l,m.treeForkCount),l.child}o=o.sibling}m.tail!==null&&Ye()>jf&&(l.flags|=128,T=!0,Cd(m,!1),l.lanes=4194304)}else{if(!T)if(o=_f(S),o!==null){if(l.flags|=128,T=!0,o=o.updateQueue,l.updateQueue=o,Mf(l,o),Cd(m,!0),m.tail===null&&m.tailMode==="hidden"&&!S.alternate&&!Ti)return ds(l),null}else 2*Ye()-m.renderingStartTime>jf&&h!==536870912&&(l.flags|=128,T=!0,Cd(m,!1),l.lanes=4194304);m.isBackwards?(S.sibling=l.child,l.child=S):(o=m.last,o!==null?o.sibling=S:l.child=S,m.last=S)}return m.tail!==null?(o=m.tail,m.rendering=o,m.tail=o.sibling,m.renderingStartTime=Ye(),o.sibling=null,h=Ls.current,he(Ls,T?h&1|2:h&1),Ti&&hi(l,m.treeForkCount),o):(ds(l),null);case 22:case 23:return lr(l),G0(),m=l.memoizedState!==null,o!==null?o.memoizedState!==null!==m&&(l.flags|=8192):m&&(l.flags|=8192),m?(h&536870912)!==0&&(l.flags&128)===0&&(ds(l),l.subtreeFlags&6&&(l.flags|=8192)):ds(l),h=l.updateQueue,h!==null&&Mf(l,h.retryQueue),h=null,o!==null&&o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==h&&(l.flags|=2048),o!==null&&ee(Ol),null;case 24:return h=null,o!==null&&(h=o.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),de(as),ds(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function DR(o,l){switch(Fn(l),l.tag){case 1:return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 3:return de(as),Ge(),o=l.flags,(o&65536)!==0&&(o&128)===0?(l.flags=o&-65537|128,l):null;case 26:case 27:case 5:return dt(l),null;case 31:if(l.memoizedState!==null){if(lr(l),l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 13:if(lr(l),o=l.memoizedState,o!==null&&o.dehydrated!==null){if(l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 19:return ee(Ls),null;case 4:return Ge(),null;case 10:return de(l.type),null;case 22:case 23:return lr(l),G0(),o!==null&&ee(Ol),o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 24:return de(as),null;case 25:return null;default:return null}}function O1(o,l){switch(Fn(l),l.tag){case 3:de(as),Ge();break;case 26:case 27:case 5:dt(l);break;case 4:Ge();break;case 31:l.memoizedState!==null&&lr(l);break;case 13:lr(l);break;case 19:ee(Ls);break;case 10:de(l.type);break;case 22:case 23:lr(l),G0(),o!==null&&ee(Ol);break;case 24:de(as)}}function kd(o,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&o)===o){m=void 0;var S=h.create,j=h.inst;m=S(),j.destroy=m}h=h.next}while(h!==T)}}catch(Z){$i(l,l.return,Z)}}function Fo(o,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&o)===o){var j=m.inst,Z=j.destroy;if(Z!==void 0){j.destroy=void 0,T=l;var ve=h,Ne=Z;try{Ne()}catch($e){$i(T,ve,$e)}}}m=m.next}while(m!==S)}}catch($e){$i(l,l.return,$e)}}function M1(o){var l=o.updateQueue;if(l!==null){var h=o.stateNode;try{wT(l,h)}catch(m){$i(o,o.return,m)}}}function P1(o,l,h){h.props=Ul(o.type,o.memoizedProps),h.state=o.memoizedState;try{h.componentWillUnmount()}catch(m){$i(o,l,m)}}function Dd(o,l){try{var h=o.ref;if(h!==null){switch(o.tag){case 26:case 27:case 5:var m=o.stateNode;break;case 30:m=o.stateNode;break;default:m=o.stateNode}typeof h=="function"?o.refCleanup=h(m):h.current=m}}catch(T){$i(o,l,T)}}function la(o,l){var h=o.ref,m=o.refCleanup;if(h!==null)if(typeof m=="function")try{m()}catch(T){$i(o,l,T)}finally{o.refCleanup=null,o=o.alternate,o!=null&&(o.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){$i(o,l,T)}else h.current=null}function B1(o){var l=o.type,h=o.memoizedProps,m=o.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){$i(o,o.return,T)}}function Tg(o,l,h){try{var m=o.stateNode;QR(m,o.type,h,l),m[ti]=l}catch(T){$i(o,o.return,T)}}function F1(o){return o.tag===5||o.tag===3||o.tag===26||o.tag===27&&zo(o.type)||o.tag===4}function _g(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||F1(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.tag===27&&zo(o.type)||o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function Sg(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(o,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(o),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=us));else if(m!==4&&(m===27&&zo(o.type)&&(h=o.stateNode,l=null),o=o.child,o!==null))for(Sg(o,l,h),o=o.sibling;o!==null;)Sg(o,l,h),o=o.sibling}function Pf(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?h.insertBefore(o,l):h.appendChild(o);else if(m!==4&&(m===27&&zo(o.type)&&(h=o.stateNode),o=o.child,o!==null))for(Pf(o,l,h),o=o.sibling;o!==null;)Pf(o,l,h),o=o.sibling}function U1(o){var l=o.stateNode,h=o.memoizedProps;try{for(var m=o.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);ln(l,m,h),l[oi]=o,l[ti]=h}catch(S){$i(o,o.return,S)}}var qa=!1,Us=!1,Eg=!1,j1=typeof WeakSet=="function"?WeakSet:Set,en=null;function LR(o,l){if(o=o.containerInfo,zg=sm,o=_u(o),nd(o)){if("selectionStart"in o)var h={start:o.selectionStart,end:o.selectionEnd};else e:{h=(h=o.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 j=0,Z=-1,ve=-1,Ne=0,$e=0,qe=o,Me=null;t:for(;;){for(var Be;qe!==h||T!==0&&qe.nodeType!==3||(Z=j+T),qe!==S||m!==0&&qe.nodeType!==3||(ve=j+m),qe.nodeType===3&&(j+=qe.nodeValue.length),(Be=qe.firstChild)!==null;)Me=qe,qe=Be;for(;;){if(qe===o)break t;if(Me===h&&++Ne===T&&(Z=j),Me===S&&++$e===m&&(ve=j),(Be=qe.nextSibling)!==null)break;qe=Me,Me=qe.parentNode}qe=Be}h=Z===-1||ve===-1?null:{start:Z,end:ve}}else h=null}h=h||{start:0,end:0}}else h=null;for(qg={focusedElem:o,selectionRange:h},sm=!1,en=l;en!==null;)if(l=en,o=l.child,(l.subtreeFlags&1028)!==0&&o!==null)o.return=l,en=o;else for(;en!==null;){switch(l=en,S=l.alternate,o=l.flags,l.tag){case 0:if((o&4)!==0&&(o=l.updateQueue,o=o!==null?o.events:null,o!==null))for(h=0;h title"))),ln(S,m,h),S[oi]=o,ki(S),m=S;break e;case"link":var j=q_("link","href",T).get(m+(h.href||""));if(j){for(var Z=0;ZYi&&(j=Yi,Yi=Wt,Wt=j);var Ae=fs(Z,Wt),Te=fs(Z,Yi);if(Ae&&Te&&(Be.rangeCount!==1||Be.anchorNode!==Ae.node||Be.anchorOffset!==Ae.offset||Be.focusNode!==Te.node||Be.focusOffset!==Te.offset)){var Ie=qe.createRange();Ie.setStart(Ae.node,Ae.offset),Be.removeAllRanges(),Wt>Yi?(Be.addRange(Ie),Be.extend(Te.node,Te.offset)):(Ie.setEnd(Te.node,Te.offset),Be.addRange(Ie))}}}}for(qe=[],Be=Z;Be=Be.parentNode;)Be.nodeType===1&&qe.push({element:Be,left:Be.scrollLeft,top:Be.scrollTop});for(typeof Z.focus=="function"&&Z.focus(),Z=0;Zh?32:h,q.T=null,h=Rg,Rg=null;var S=Ho,j=Qa;if(Ys=0,Fu=Ho=null,Qa=0,(Ni&6)!==0)throw Error(i(331));var Z=Ni;if(Ni|=4,Q1(S.current),W1(S,S.current,j,h),Ni=Z,Md(0,!1),Ke&&typeof Ke.onPostCommitFiberRoot=="function")try{Ke.onPostCommitFiberRoot($t,S)}catch{}return!0}finally{Y.p=T,q.T=m,p_(o,l)}}function y_(o,l,h){l=Pn(h,l),l=cg(o.stateNode,l,2),o=Mo(o,l,2),o!==null&&(Ot(o,2),ua(o))}function $i(o,l,h){if(o.tag===3)y_(o,o,h);else for(;l!==null;){if(l.tag===3){y_(l,o,h);break}else if(l.tag===1){var m=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&($o===null||!$o.has(m))){o=Pn(h,o),h=v1(2),m=Mo(l,h,2),m!==null&&(x1(h,m,l,o),Ot(m,2),ua(m));break}}l=l.return}}function Mg(o,l,h){var m=o.pingCache;if(m===null){m=o.pingCache=new NR;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)||(Cg=!0,T.add(h),o=FR.bind(null,o,l,h),l.then(o,o))}function FR(o,l,h){var m=o.pingCache;m!==null&&m.delete(l),o.pingedLanes|=o.suspendedLanes&h,o.warmLanes&=~h,Ji===o&&(Ei&h)===h&&(ws===4||ws===3&&(Ei&62914560)===Ei&&300>Ye()-Uf?(Ni&2)===0&&Uu(o,0):kg|=h,Bu===Ei&&(Bu=0)),ua(o)}function v_(o,l){l===0&&(l=Oe()),o=ja(o,l),o!==null&&(Ot(o,l),ua(o))}function UR(o){var l=o.memoizedState,h=0;l!==null&&(h=l.retryLane),v_(o,h)}function jR(o,l){var h=0;switch(o.tag){case 31:case 13:var m=o.stateNode,T=o.memoizedState;T!==null&&(h=T.retryLane);break;case 19:m=o.stateNode;break;case 22:m=o.stateNode._retryCache;break;default:throw Error(i(314))}m!==null&&m.delete(l),v_(o,h)}function $R(o,l){return We(o,l)}var qf=null,$u=null,Pg=!1,Kf=!1,Bg=!1,Vo=0;function ua(o){o!==$u&&o.next===null&&($u===null?qf=$u=o:$u=$u.next=o),Kf=!0,Pg||(Pg=!0,GR())}function Md(o,l){if(!Bg&&Kf){Bg=!0;do for(var h=!1,m=qf;m!==null;){if(o!==0){var T=m.pendingLanes;if(T===0)var S=0;else{var j=m.suspendedLanes,Z=m.pingedLanes;S=(1<<31-Qt(42|o)+1)-1,S&=T&~(j&~Z),S=S&201326741?S&201326741|1:S?S|2:0}S!==0&&(h=!0,__(m,S))}else S=Ei,S=V(m,m===Ji?S:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),(S&3)===0||te(m,S)||(h=!0,__(m,S));m=m.next}while(h);Bg=!1}}function HR(){x_()}function x_(){Kf=Pg=!1;var o=0;Vo!==0&&JR()&&(o=Vo);for(var l=Ye(),h=null,m=qf;m!==null;){var T=m.next,S=b_(m,l);S===0?(m.next=null,h===null?qf=T:h.next=T,T===null&&($u=h)):(h=m,(o!==0||(S&3)!==0)&&(Kf=!0)),m=T}Ys!==0&&Ys!==5||Md(o),Vo!==0&&(Vo=0)}function b_(o,l){for(var h=o.suspendedLanes,m=o.pingedLanes,T=o.expirationTimes,S=o.pendingLanes&-62914561;0Z)break;var $e=ve.transferSize,qe=ve.initiatorType;$e&&L_(qe)&&(ve=ve.responseEnd,j+=$e*(ve"u"?null:document;function H_(o,l,h){var m=Hu;if(m&&typeof l=="string"&&l){var T=Bt(l);T='link[rel="'+o+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),$_.has(T)||($_.add(T),o={rel:o,crossOrigin:h,href:l},m.querySelector(T)===null&&(l=m.createElement("link"),ln(l,"link",o),ki(l),m.head.appendChild(l)))}}function lI(o){Za.D(o),H_("dns-prefetch",o,null)}function uI(o,l){Za.C(o,l),H_("preconnect",o,l)}function cI(o,l,h){Za.L(o,l,h);var m=Hu;if(m&&o&&l){var T='link[rel="preload"][as="'+Bt(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+Bt(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+Bt(h.imageSizes)+'"]')):T+='[href="'+Bt(o)+'"]';var S=T;switch(l){case"style":S=Gu(o);break;case"script":S=Vu(o)}Ar.has(S)||(o=p({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:o,as:l},h),Ar.set(S,o),m.querySelector(T)!==null||l==="style"&&m.querySelector(Ud(S))||l==="script"&&m.querySelector(jd(S))||(l=m.createElement("link"),ln(l,"link",o),ki(l),m.head.appendChild(l)))}}function dI(o,l){Za.m(o,l);var h=Hu;if(h&&o){var m=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+Bt(m)+'"][href="'+Bt(o)+'"]',S=T;switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":S=Vu(o)}if(!Ar.has(S)&&(o=p({rel:"modulepreload",href:o},l),Ar.set(S,o),h.querySelector(T)===null)){switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(jd(S)))return}m=h.createElement("link"),ln(m,"link",o),ki(m),h.head.appendChild(m)}}}function hI(o,l,h){Za.S(o,l,h);var m=Hu;if(m&&o){var T=zs(m).hoistableStyles,S=Gu(o);l=l||"default";var j=T.get(S);if(!j){var Z={loading:0,preload:null};if(j=m.querySelector(Ud(S)))Z.loading=5;else{o=p({rel:"stylesheet",href:o,"data-precedence":l},h),(h=Ar.get(S))&&Jg(o,h);var ve=j=m.createElement("link");ki(ve),ln(ve,"link",o),ve._p=new Promise(function(Ne,$e){ve.onload=Ne,ve.onerror=$e}),ve.addEventListener("load",function(){Z.loading|=1}),ve.addEventListener("error",function(){Z.loading|=2}),Z.loading|=4,Zf(j,l,m)}j={type:"stylesheet",instance:j,count:1,state:Z},T.set(S,j)}}}function fI(o,l){Za.X(o,l);var h=Hu;if(h&&o){var m=zs(h).hoistableScripts,T=Vu(o),S=m.get(T);S||(S=h.querySelector(jd(T)),S||(o=p({src:o,async:!0},l),(l=Ar.get(T))&&ey(o,l),S=h.createElement("script"),ki(S),ln(S,"link",o),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},m.set(T,S))}}function mI(o,l){Za.M(o,l);var h=Hu;if(h&&o){var m=zs(h).hoistableScripts,T=Vu(o),S=m.get(T);S||(S=h.querySelector(jd(T)),S||(o=p({src:o,async:!0,type:"module"},l),(l=Ar.get(T))&&ey(o,l),S=h.createElement("script"),ki(S),ln(S,"link",o),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},m.set(T,S))}}function G_(o,l,h,m){var T=(T=Ce.current)?Qf(T):null;if(!T)throw Error(i(446));switch(o){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=Gu(h.href),h=zs(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"){o=Gu(h.href);var S=zs(T).hoistableStyles,j=S.get(o);if(j||(T=T.ownerDocument||T,j={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},S.set(o,j),(S=T.querySelector(Ud(o)))&&!S._p&&(j.instance=S,j.state.loading=5),Ar.has(o)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},Ar.set(o,h),S||pI(T,o,h,j.state))),l&&m===null)throw Error(i(528,""));return j}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=Vu(h),h=zs(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,o))}}function Gu(o){return'href="'+Bt(o)+'"'}function Ud(o){return'link[rel="stylesheet"]['+o+"]"}function V_(o){return p({},o,{"data-precedence":o.precedence,precedence:null})}function pI(o,l,h,m){o.querySelector('link[rel="preload"][as="style"]['+l+"]")?m.loading=1:(l=o.createElement("link"),m.preload=l,l.addEventListener("load",function(){return m.loading|=1}),l.addEventListener("error",function(){return m.loading|=2}),ln(l,"link",h),ki(l),o.head.appendChild(l))}function Vu(o){return'[src="'+Bt(o)+'"]'}function jd(o){return"script[async]"+o}function z_(o,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var m=o.querySelector('style[data-href~="'+Bt(h.href)+'"]');if(m)return l.instance=m,ki(m),m;var T=p({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return m=(o.ownerDocument||o).createElement("style"),ki(m),ln(m,"style",T),Zf(m,h.precedence,o),l.instance=m;case"stylesheet":T=Gu(h.href);var S=o.querySelector(Ud(T));if(S)return l.state.loading|=4,l.instance=S,ki(S),S;m=V_(h),(T=Ar.get(T))&&Jg(m,T),S=(o.ownerDocument||o).createElement("link"),ki(S);var j=S;return j._p=new Promise(function(Z,ve){j.onload=Z,j.onerror=ve}),ln(S,"link",m),l.state.loading|=4,Zf(S,h.precedence,o),l.instance=S;case"script":return S=Vu(h.src),(T=o.querySelector(jd(S)))?(l.instance=T,ki(T),T):(m=h,(T=Ar.get(S))&&(m=p({},h),ey(m,T)),o=o.ownerDocument||o,T=o.createElement("script"),ki(T),ln(T,"link",m),o.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,Zf(m,h.precedence,o));return l.instance}function Zf(o,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,j=0;j title"):null)}function gI(o,l,h){if(h===1||l.itemProp!=null)return!1;switch(o){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"?(o=l.disabled,typeof l.precedence=="string"&&o==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 W_(o){return!(o.type==="stylesheet"&&(o.state.loading&3)===0)}function yI(o,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=Gu(m.href),S=l.querySelector(Ud(T));if(S){l=S._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(o.count++,o=em.bind(o),l.then(o,o)),h.state.loading|=4,h.instance=S,ki(S);return}S=l.ownerDocument||l,m=V_(m),(T=Ar.get(T))&&Jg(m,T),S=S.createElement("link"),ki(S);var j=S;j._p=new Promise(function(Z,ve){j.onload=Z,j.onerror=ve}),ln(S,"link",m),h.instance=S}o.stylesheets===null&&(o.stylesheets=new Map),o.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(o.count++,h=em.bind(o),l.addEventListener("load",h),l.addEventListener("error",h))}}var ty=0;function vI(o,l){return o.stylesheets&&o.count===0&&im(o,o.stylesheets),0ty?50:800)+l);return o.unsuspend=h,function(){o.unsuspend=null,clearTimeout(m),clearTimeout(T)}}:null}function em(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)im(this,this.stylesheets);else if(this.unsuspend){var o=this.unsuspend;this.unsuspend=null,o()}}}var tm=null;function im(o,l){o.stylesheets=null,o.unsuspend!==null&&(o.count++,tm=new Map,l.forEach(xI,o),tm=null,em.call(o))}function xI(o,l){if(!(l.state.loading&4)){var h=tm.get(o);if(h)var m=h.get(null);else{h=new Map,tm.set(o,h);for(var T=o.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(),cy.exports=PI(),cy.exports}var FI=BI();function UI(...s){return s.filter(Boolean).join(" ")}const jI="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",$I={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},HI={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"},GI={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 VI(){return g.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[g.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),g.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function Zt({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:a,isLoading:u=!1,disabled:c,className:d,type:f="button",...p}){const y=r||a||u?"gap-x-1.5":"";return g.jsxs("button",{type:f,disabled:c||u,className:UI(jI,$I[n],HI[i],GI[t][e],y,d),...p,children:[u?g.jsx("span",{className:"-ml-0.5",children:g.jsx(VI,{})}):r&&g.jsx("span",{className:"-ml-0.5",children:r}),g.jsx("span",{children:s}),a&&!u&&g.jsx("span",{className:"-mr-0.5",children:a})]})}function nA(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?zI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,my=(s,e,t)=>(qI(s,typeof e!="symbol"?e+"":e,t),t);let KI=class{constructor(){my(this,"current",this.detect()),my(this,"handoffState","pending"),my(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"}},wa=new KI;function Ph(s){var e;return wa.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function Gv(s){var e,t;return wa.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function rA(s){var e,t;return(t=(e=Gv(s))==null?void 0:e.activeElement)!=null?t:null}function WI(s){return rA(s)===s}function Bp(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function po(){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 Bp(()=>{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=po();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 Fp(){let[s]=w.useState(po);return w.useEffect(()=>()=>s.dispose(),[s]),s}let Zn=(s,e)=>{wa.isServer?w.useEffect(s,e):w.useLayoutEffect(s,e)};function hu(s){let e=w.useRef(s);return Zn(()=>{e.current=s},[s]),e}let ts=function(s){let e=hu(s);return Vt.useCallback((...t)=>e.current(...t),[e])};function Bh(s){return w.useMemo(()=>s,Object.values(s))}let YI=w.createContext(void 0);function XI(){return w.useContext(YI)}function Vv(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function fo(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,fo),i}var Zm=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(Zm||{}),cl=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(cl||{});function Nr(){let s=ZI();return w.useCallback(e=>QI({mergeRefs:s,...e}),[s])}function QI({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:a,mergeRefs:u}){u=u??JI;let c=aA(e,s);if(r)return cm(c,t,i,a,u);let d=n??0;if(d&2){let{static:f=!1,...p}=c;if(f)return cm(p,t,i,a,u)}if(d&1){let{unmount:f=!0,...p}=c;return fo(f?0:1,{0(){return null},1(){return cm({...p,hidden:!0,style:{display:"none"}},t,i,a,u)}})}return cm(c,t,i,a,u)}function cm(s,e={},t,i,n){let{as:r=t,children:a,refName:u="ref",...c}=py(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof a=="function"?a(e):a;"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 y=!1,v=[];for(let[b,_]of Object.entries(e))typeof _=="boolean"&&(y=!0),_===!0&&v.push(b.replace(/([A-Z])/g,E=>`-${E.toLowerCase()}`));if(y){p["data-headlessui-state"]=v.join(" ");for(let b of v)p[`data-${b}`]=""}}if(uh(r)&&(Object.keys(Kl(c)).length>0||Object.keys(Kl(p)).length>0))if(!w.isValidElement(f)||Array.isArray(f)&&f.length>1||tN(f)){if(Object.keys(Kl(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(Kl(c)).concat(Object.keys(Kl(p))).map(y=>` - ${y}`).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(y=>` - ${y}`).join(` -`)].join(` -`))}else{let y=f.props,v=y?.className,b=typeof v=="function"?(...L)=>Vv(v(...L),c.className):Vv(v,c.className),_=b?{className:b}:{},E=aA(f.props,Kl(py(c,["ref"])));for(let L in p)L in E&&delete p[L];return w.cloneElement(f,Object.assign({},E,p,d,{ref:n(eN(f),d.ref)},_))}return w.createElement(r,Object.assign({},py(c,["ref"]),!uh(r)&&d,!uh(r)&&p),f)}function ZI(){let s=w.useRef([]),e=w.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 JI(...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 aA(...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 a=t[i];for(let u of a){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function er(s){var e;return Object.assign(w.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function Kl(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function py(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function eN(s){return Vt.version.split(".")[0]>="19"?s.props.ref:s.ref}function uh(s){return s===w.Fragment||s===Symbol.for("react.fragment")}function tN(s){return uh(s.type)}let iN="span";var Jm=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(Jm||{});function sN(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 Nr()({ourProps:r,theirProps:n,slot:{},defaultTag:iN,name:"Hidden"})}let zv=er(sN);function nN(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function hl(s){return nN(s)&&"tagName"in s}function lu(s){return hl(s)&&"accessKey"in s}function dl(s){return hl(s)&&"tabIndex"in s}function rN(s){return hl(s)&&"style"in s}function aN(s){return lu(s)&&s.nodeName==="IFRAME"}function oN(s){return lu(s)&&s.nodeName==="INPUT"}let oA=Symbol();function lN(s,e=!0){return Object.assign(s,{[oA]:e})}function Na(...s){let e=w.useRef(s);w.useEffect(()=>{e.current=s},[s]);let t=ts(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[oA])?void 0:t}let Yx=w.createContext(null);Yx.displayName="DescriptionContext";function lA(){let s=w.useContext(Yx);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,lA),e}return s}function uN(){let[s,e]=w.useState([]);return[s.length>0?s.join(" "):void 0,w.useMemo(()=>function(t){let i=ts(r=>(e(a=>[...a,r]),()=>e(a=>{let u=a.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=w.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 Vt.createElement(Yx.Provider,{value:n},t.children)},[e])]}let cN="p";function dN(s,e){let t=w.useId(),i=XI(),{id:n=`headlessui-description-${t}`,...r}=s,a=lA(),u=Na(e);Zn(()=>a.register(n),[n,a.register]);let c=Bh({...a.slot,disabled:i||!1}),d={ref:u,...a.props,id:n};return Nr()({ourProps:d,theirProps:r,slot:c,defaultTag:cN,name:a.name||"Description"})}let hN=er(dN),fN=Object.assign(hN,{});var uA=(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))(uA||{});let mN=w.createContext(()=>{});function pN({value:s,children:e}){return Vt.createElement(mN.Provider,{value:s},e)}let cA=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 gN=Object.defineProperty,yN=(s,e,t)=>e in s?gN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,vN=(s,e,t)=>(yN(s,e+"",t),t),dA=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Cr=(s,e,t)=>(dA(s,e,"read from private field"),t?t.call(s):e.get(s)),gy=(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)},xS=(s,e,t,i)=>(dA(s,e,"write to private field"),e.set(s,t),t),fa,ih,sh;let xN=class{constructor(e){gy(this,fa,{}),gy(this,ih,new cA(()=>new Set)),gy(this,sh,new Set),vN(this,"disposables",po()),xS(this,fa,e),wa.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return Cr(this,fa)}subscribe(e,t){if(wa.isServer)return()=>{};let i={selector:e,callback:t,current:e(Cr(this,fa))};return Cr(this,sh).add(i),this.disposables.add(()=>{Cr(this,sh).delete(i)})}on(e,t){return wa.isServer?()=>{}:(Cr(this,ih).get(e).add(t),this.disposables.add(()=>{Cr(this,ih).get(e).delete(t)}))}send(e){let t=this.reduce(Cr(this,fa),e);if(t!==Cr(this,fa)){xS(this,fa,t);for(let i of Cr(this,sh)){let n=i.selector(Cr(this,fa));hA(i.current,n)||(i.current=n,i.callback(n))}for(let i of Cr(this,ih).get(e.type))i(Cr(this,fa),e)}}};fa=new WeakMap,ih=new WeakMap,sh=new WeakMap;function hA(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:yy(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:yy(s.entries(),e.entries()):bS(s)&&bS(e)?yy(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function yy(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 bS(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var bN=Object.defineProperty,TN=(s,e,t)=>e in s?bN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,TS=(s,e,t)=>(TN(s,typeof e!="symbol"?e+"":e,t),t),_N=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(_N||{});let SN={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}}},EN=class fA extends xN{constructor(){super(...arguments),TS(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),TS(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new fA({stack:[]})}reduce(e,t){return fo(t.type,SN,e,t)}};const mA=new cA(()=>EN.new());var vy={exports:{}},xy={};var _S;function wN(){if(_S)return xy;_S=1;var s=Pp();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,a=s.useMemo,u=s.useDebugValue;return xy.useSyncExternalStoreWithSelector=function(c,d,f,p,y){var v=n(null);if(v.current===null){var b={hasValue:!1,value:null};v.current=b}else b=v.current;v=a(function(){function E(P){if(!L){if(L=!0,I=P,P=p(P),y!==void 0&&b.hasValue){var B=b.value;if(y(B,P))return R=B}return R=P}if(B=R,t(I,P))return B;var O=p(P);return y!==void 0&&y(B,O)?(I=P,B):(I=P,R=O)}var L=!1,I,R,$=f===void 0?null:f;return[function(){return E(d())},$===null?void 0:function(){return E($())}]},[d,f,p,y]);var _=i(c,v[0],v[1]);return r(function(){b.hasValue=!0,b.value=_},[_]),u(_),_},xy}var SS;function AN(){return SS||(SS=1,vy.exports=wN()),vy.exports}var CN=AN();function pA(s,e,t=hA){return CN.useSyncExternalStoreWithSelector(ts(i=>s.subscribe(kN,i)),ts(()=>s.state),ts(()=>s.state),ts(e),t)}function kN(s){return s}function Fh(s,e){let t=w.useId(),i=mA.get(e),[n,r]=pA(i,w.useCallback(a=>[i.selectors.isTop(a,t),i.selectors.inStack(a,t)],[i,t]));return Zn(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let qv=new Map,ch=new Map;function ES(s){var e;let t=(e=ch.get(s))!=null?e:0;return ch.set(s,t+1),t!==0?()=>wS(s):(qv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>wS(s))}function wS(s){var e;let t=(e=ch.get(s))!=null?e:1;if(t===1?ch.delete(s):ch.set(s,t-1),t!==1)return;let i=qv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,qv.delete(s))}function DN(s,{allowed:e,disallowed:t}={}){let i=Fh(s,"inert-others");Zn(()=>{var n,r;if(!i)return;let a=po();for(let c of(n=t?.())!=null?n:[])c&&a.add(ES(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=Ph(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let p of f.children)u.some(y=>p.contains(y))||a.add(ES(p));f=f.parentElement}}return a.dispose},[i,e,t])}function LN(s,e,t){let i=hu(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});w.useEffect(()=>{if(!s)return;let n=e===null?null:lu(e)?e:e.current;if(!n)return;let r=po();if(typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}if(typeof IntersectionObserver<"u"){let a=new IntersectionObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}return()=>r.dispose()},[e,i,s])}let ep=["[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(","),RN=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var ao=(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))(ao||{}),Kv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(Kv||{}),IN=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(IN||{});function NN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(ep)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function ON(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(RN)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var gA=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(gA||{});function MN(s,e=0){var t;return s===((t=Ph(s))==null?void 0:t.body)?!1:fo(e,{0(){return s.matches(ep)},1(){let i=s;for(;i!==null;){if(i.matches(ep))return!0;i=i.parentElement}return!1}})}var PN=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(PN||{});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 co(s){s?.focus({preventScroll:!0})}let BN=["textarea","input"].join(",");function FN(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,BN))!=null?t:!1}function UN(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 a=n.compareDocumentPosition(r);return a&Node.DOCUMENT_POSITION_FOLLOWING?-1:a&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function dh(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?Gv(s[0]):document:Gv(s),a=Array.isArray(s)?t?UN(s):s:e&64?ON(s):NN(s);n.length>0&&a.length>1&&(a=a.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,a.indexOf(i))-1;if(e&4)return Math.max(0,a.indexOf(i))+1;if(e&8)return a.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,p=a.length,y;do{if(f>=p||f+p<=0)return 0;let v=c+f;if(e&16)v=(v+p)%p;else{if(v<0)return 3;if(v>=p)return 1}y=a[v],y?.focus(d),f+=u}while(y!==rA(y));return e&6&&FN(y)&&y.select(),2}function yA(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function jN(){return/Android/gi.test(window.navigator.userAgent)}function AS(){return yA()||jN()}function dm(s,e,t,i){let n=hu(t);w.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function vA(s,e,t,i){let n=hu(t);w.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const CS=30;function $N(s,e,t){let i=hu(t),n=w.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(y){return typeof y=="function"?p(y()):Array.isArray(y)||y instanceof Set?y:[y]})(e);for(let p of f)if(p!==null&&(p.contains(d)||u.composed&&u.composedPath().includes(p)))return;return!MN(d,gA.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=w.useRef(null);dm(s,"pointerdown",u=>{var c,d;AS()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),dm(s,"pointerup",u=>{if(AS()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let a=w.useRef({x:0,y:0});dm(s,"touchstart",u=>{a.current.x=u.touches[0].clientX,a.current.y=u.touches[0].clientY},!0),dm(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-a.current.x)>=CS||Math.abs(c.y-a.current.y)>=CS))return n(u,()=>dl(u.target)?u.target:null)},!0),vA(s,"blur",u=>n(u,()=>aN(window.document.activeElement)?window.document.activeElement:null),!0)}function Xx(...s){return w.useMemo(()=>Ph(...s),[...s])}function xA(s,e,t,i){let n=hu(t);w.useEffect(()=>{s=s??window;function r(a){n.current(a)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function HN(s){return w.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function GN(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 a=e[n].call(t,...r);a&&(t=a,i.forEach(u=>u()))}}}function VN(){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 zN(){return yA()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let a of r())if(a.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=po();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,a=null;e.addEventListener(s,"click",u=>{if(dl(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);dl(f)&&!i(f)&&(a=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),dl(c.target)&&rN(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(dl(u.target)){if(oN(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),a&&a.isConnected&&(a.scrollIntoView({block:"nearest"}),a=null)})})}}:{}}function qN(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function kS(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let Jl=GN(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:po(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=kS(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=kS(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[zN(),VN(),qN()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});Jl.subscribe(()=>{let s=Jl.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)&&Jl.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&Jl.dispatch("TEARDOWN",t)}});function KN(s,e,t=()=>({containers:[]})){let i=HN(Jl),n=e?i.get(e):void 0,r=n?n.count>0:!1;return Zn(()=>{if(!(!e||!s))return Jl.dispatch("PUSH",e,t),()=>Jl.dispatch("POP",e,t)},[s,e]),r}function WN(s,e,t=()=>[document.body]){let i=Fh(s,"scroll-lock");KN(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function YN(s=0){let[e,t]=w.useState(s),i=w.useCallback(c=>t(c),[]),n=w.useCallback(c=>t(d=>d|c),[]),r=w.useCallback(c=>(e&c)===c,[e]),a=w.useCallback(c=>t(d=>d&~c),[]),u=w.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:a,toggleFlag:u}}var XN={},DS,LS;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((DS=process==null?void 0:XN)==null?void 0:DS.NODE_ENV)==="test"&&typeof((LS=Element?.prototype)==null?void 0:LS.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 QN=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(QN||{});function ZN(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function JN(s,e,t,i){let[n,r]=w.useState(t),{hasFlag:a,addFlag:u,removeFlag:c}=YN(s&&n?3:0),d=w.useRef(!1),f=w.useRef(!1),p=Fp();return Zn(()=>{var y;if(s){if(t&&r(!0),!e){t&&u(3);return}return(y=i?.start)==null||y.call(i,t),e5(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&&s5(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,p]),s?[n,{closed:a(1),enter:a(2),leave:a(4),transition:a(2)||a(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function e5(s,{prepare:e,run:t,done:i,inFlight:n}){let r=po();return i5(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(t5(s,i))})}),r.dispose}function t5(s,e){var t,i;let n=po();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let a=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return a.length===0?(e(),n.dispose):(Promise.allSettled(a.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function i5(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 s5(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 Qx(s,e){let t=w.useRef([]),i=ts(s);w.useEffect(()=>{let n=[...t.current];for(let[r,a]of e.entries())if(t.current[r]!==a){let u=i(e,n);return t.current=e,u}},[i,...e])}let Up=w.createContext(null);Up.displayName="OpenClosedContext";var qr=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(qr||{});function jp(){return w.useContext(Up)}function n5({value:s,children:e}){return Vt.createElement(Up.Provider,{value:s},e)}function r5({children:s}){return Vt.createElement(Up.Provider,{value:null},s)}function a5(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let ul=[];a5(()=>{function s(e){if(!dl(e.target)||e.target===document.body||ul[0]===e.target)return;let t=e.target;t=t.closest(ep),ul.unshift(t??e.target),ul=ul.filter(i=>i!=null&&i.isConnected),ul.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 bA(s){let e=ts(s),t=w.useRef(!1);w.useEffect(()=>(t.current=!1,()=>{t.current=!0,Bp(()=>{t.current&&e()})}),[e])}let TA=w.createContext(!1);function o5(){return w.useContext(TA)}function RS(s){return Vt.createElement(TA.Provider,{value:s.force},s.children)}function l5(s){let e=o5(),t=w.useContext(SA),[i,n]=w.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(wa.isServer)return null;let a=s?.getElementById("headlessui-portal-root");if(a)return a;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return w.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),w.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let _A=w.Fragment,u5=er(function(s,e){let{ownerDocument:t=null,...i}=s,n=w.useRef(null),r=Na(lN(y=>{n.current=y}),e),a=Xx(n.current),u=t??a,c=l5(u),d=w.useContext(Wv),f=Fp(),p=Nr();return bA(()=>{var y;c&&c.childNodes.length<=0&&((y=c.parentElement)==null||y.removeChild(c))}),c?Ec.createPortal(Vt.createElement("div",{"data-headlessui-portal":"",ref:y=>{f.dispose(),d&&y&&f.add(d.register(y))}},p({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:_A,name:"Portal"})),c):null});function c5(s,e){let t=Na(e),{enabled:i=!0,ownerDocument:n,...r}=s,a=Nr();return i?Vt.createElement(u5,{...r,ownerDocument:n,ref:t}):a({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:_A,name:"Portal"})}let d5=w.Fragment,SA=w.createContext(null);function h5(s,e){let{target:t,...i}=s,n={ref:Na(e)},r=Nr();return Vt.createElement(SA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:d5,name:"Popover.Group"}))}let Wv=w.createContext(null);function f5(){let s=w.useContext(Wv),e=w.useRef([]),t=ts(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=ts(r=>{let a=e.current.indexOf(r);a!==-1&&e.current.splice(a,1),s&&s.unregister(r)}),n=w.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,w.useMemo(()=>function({children:r}){return Vt.createElement(Wv.Provider,{value:n},r)},[n])]}let m5=er(c5),EA=er(h5),p5=Object.assign(m5,{Group:EA});function g5(s,e=typeof document<"u"?document.defaultView:null,t){let i=Fh(s,"escape");xA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===uA.Escape&&t(n))})}function y5(){var s;let[e]=w.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=w.useState((s=e?.matches)!=null?s:!1);return Zn(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function v5({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=ts(()=>{var n,r;let a=Ph(t),u=[];for(let c of s)c!==null&&(hl(c)?u.push(c):"current"in c&&hl(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=a?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&hl(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:ts(n=>i().some(r=>r.contains(n)))}}let wA=w.createContext(null);function IS({children:s,node:e}){let[t,i]=w.useState(null),n=AA(e??t);return Vt.createElement(wA.Provider,{value:n},s,n===null&&Vt.createElement(zv,{features:Jm.Hidden,ref:r=>{var a,u;if(r){for(let c of(u=(a=Ph(r))==null?void 0:a.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&hl(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function AA(s=null){var e;return(e=w.useContext(wA))!=null?e:s}function x5(){let s=typeof document>"u";return"useSyncExternalStore"in hS?(e=>e.useSyncExternalStore)(hS)(()=>()=>{},()=>!1,()=>!s):!1}function $p(){let s=x5(),[e,t]=w.useState(wa.isHandoffComplete);return e&&wa.isHandoffComplete===!1&&t(!1),w.useEffect(()=>{e!==!0&&t(!0)},[e]),w.useEffect(()=>wa.handoff(),[]),s?!1:e}function Zx(){let s=w.useRef(!1);return Zn(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var nh=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(nh||{});function b5(){let s=w.useRef(0);return vA(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function CA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)hl(t.current)&&e.add(t.current);return e}let T5="div";var Ql=(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))(Ql||{});function _5(s,e){let t=w.useRef(null),i=Na(t,e),{initialFocus:n,initialFocusFallback:r,containers:a,features:u=15,...c}=s;$p()||(u=0);let d=Xx(t.current);A5(u,{ownerDocument:d});let f=C5(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});k5(u,{ownerDocument:d,container:t,containers:a,previousActiveElement:f});let p=b5(),y=ts(I=>{if(!lu(t.current))return;let R=t.current;($=>$())(()=>{fo(p.current,{[nh.Forwards]:()=>{dh(R,ao.First,{skipElements:[I.relatedTarget,r]})},[nh.Backwards]:()=>{dh(R,ao.Last,{skipElements:[I.relatedTarget,r]})}})})}),v=Fh(!!(u&2),"focus-trap#tab-lock"),b=Fp(),_=w.useRef(!1),E={ref:i,onKeyDown(I){I.key=="Tab"&&(_.current=!0,b.requestAnimationFrame(()=>{_.current=!1}))},onBlur(I){if(!(u&4))return;let R=CA(a);lu(t.current)&&R.add(t.current);let $=I.relatedTarget;dl($)&&$.dataset.headlessuiFocusGuard!=="true"&&(kA(R,$)||(_.current?dh(t.current,fo(p.current,{[nh.Forwards]:()=>ao.Next,[nh.Backwards]:()=>ao.Previous})|ao.WrapAround,{relativeTo:I.target}):dl(I.target)&&co(I.target)))}},L=Nr();return Vt.createElement(Vt.Fragment,null,v&&Vt.createElement(zv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:Jm.Focusable}),L({ourProps:E,theirProps:c,defaultTag:T5,name:"FocusTrap"}),v&&Vt.createElement(zv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:Jm.Focusable}))}let S5=er(_5),E5=Object.assign(S5,{features:Ql});function w5(s=!0){let e=w.useRef(ul.slice());return Qx(([t],[i])=>{i===!0&&t===!1&&Bp(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=ul.slice())},[s,ul,e]),ts(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function A5(s,{ownerDocument:e}){let t=!!(s&8),i=w5(t);Qx(()=>{t||WI(e?.body)&&co(i())},[t]),bA(()=>{t&&co(i())})}function C5(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=w.useRef(null),a=Fh(!!(s&1),"focus-trap#initial-focus"),u=Zx();return Qx(()=>{if(s===0)return;if(!a){n!=null&&n.current&&co(n.current);return}let c=t.current;c&&Bp(()=>{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)co(i.current);else{if(s&16){if(dh(c,ao.First|ao.AutoFocus)!==Kv.Error)return}else if(dh(c,ao.First)!==Kv.Error)return;if(n!=null&&n.current&&(co(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,a,s]),r}function k5(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=Zx(),a=!!(s&4);xA(e?.defaultView,"focus",u=>{if(!a||!r.current)return;let c=CA(i);lu(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;lu(f)?kA(c,f)?(n.current=f,co(f)):(u.preventDefault(),u.stopPropagation(),co(d)):co(n.current)},!0)}function kA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function DA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!uh((e=s.as)!=null?e:RA)||Vt.Children.count(s.children)===1}let Hp=w.createContext(null);Hp.displayName="TransitionContext";var D5=(s=>(s.Visible="visible",s.Hidden="hidden",s))(D5||{});function L5(){let s=w.useContext(Hp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function R5(){let s=w.useContext(Gp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let Gp=w.createContext(null);Gp.displayName="NestingContext";function Vp(s){return"children"in s?Vp(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function LA(s,e){let t=hu(s),i=w.useRef([]),n=Zx(),r=Fp(),a=ts((v,b=cl.Hidden)=>{let _=i.current.findIndex(({el:E})=>E===v);_!==-1&&(fo(b,{[cl.Unmount](){i.current.splice(_,1)},[cl.Hidden](){i.current[_].state="hidden"}}),r.microTask(()=>{var E;!Vp(i)&&n.current&&((E=t.current)==null||E.call(t))}))}),u=ts(v=>{let b=i.current.find(({el:_})=>_===v);return b?b.state!=="visible"&&(b.state="visible"):i.current.push({el:v,state:"visible"}),()=>a(v,cl.Unmount)}),c=w.useRef([]),d=w.useRef(Promise.resolve()),f=w.useRef({enter:[],leave:[]}),p=ts((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)}),y=ts((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 w.useMemo(()=>({children:i,register:u,unregister:a,onStart:p,onStop:y,wait:d,chains:f}),[u,a,i,p,y,f,d])}let RA=w.Fragment,IA=Zm.RenderStrategy;function I5(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:a,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:p,entered:y,leave:v,leaveFrom:b,leaveTo:_,...E}=s,[L,I]=w.useState(null),R=w.useRef(null),$=DA(s),P=Na(...$?[R,e,I]:e===null?[]:[e]),B=(t=E.unmount)==null||t?cl.Unmount:cl.Hidden,{show:O,appear:H,initial:D}=L5(),[M,W]=w.useState(O?"visible":"hidden"),K=R5(),{register:J,unregister:ue}=K;Zn(()=>J(R),[J,R]),Zn(()=>{if(B===cl.Hidden&&R.current){if(O&&M!=="visible"){W("visible");return}return fo(M,{hidden:()=>ue(R),visible:()=>J(R)})}},[M,R,J,ue,O,B]);let se=$p();Zn(()=>{if($&&se&&M==="visible"&&R.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[R,M,se,$]);let q=D&&!H,Y=H&&O&&D,ie=w.useRef(!1),Q=LA(()=>{ie.current||(W("hidden"),ue(R))},K),oe=ts(Re=>{ie.current=!0;let Ze=Re?"enter":"leave";Q.onStart(R,Ze,Ge=>{Ge==="enter"?r?.():Ge==="leave"&&u?.()})}),F=ts(Re=>{let Ze=Re?"enter":"leave";ie.current=!1,Q.onStop(R,Ze,Ge=>{Ge==="enter"?a?.():Ge==="leave"&&c?.()}),Ze==="leave"&&!Vp(Q)&&(W("hidden"),ue(R))});w.useEffect(()=>{$&&n||(oe(O),F(O))},[O,$,n]);let ee=!(!n||!$||!se||q),[,he]=JN(ee,L,O,{start:oe,end:F}),be=Kl({ref:P,className:((i=Vv(E.className,Y&&d,Y&&f,he.enter&&d,he.enter&&he.closed&&f,he.enter&&!he.closed&&p,he.leave&&v,he.leave&&!he.closed&&b,he.leave&&he.closed&&_,!he.transition&&O&&y))==null?void 0:i.trim())||void 0,...ZN(he)}),pe=0;M==="visible"&&(pe|=qr.Open),M==="hidden"&&(pe|=qr.Closed),O&&M==="hidden"&&(pe|=qr.Opening),!O&&M==="visible"&&(pe|=qr.Closing);let Ce=Nr();return Vt.createElement(Gp.Provider,{value:Q},Vt.createElement(n5,{value:pe},Ce({ourProps:be,theirProps:E,defaultTag:RA,features:IA,visible:M==="visible",name:"Transition.Child"})))}function N5(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,a=w.useRef(null),u=DA(s),c=Na(...u?[a,e]:e===null?[]:[e]);$p();let d=jp();if(t===void 0&&d!==null&&(t=(d&qr.Open)===qr.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,p]=w.useState(t?"visible":"hidden"),y=LA(()=>{t||p("hidden")}),[v,b]=w.useState(!0),_=w.useRef([t]);Zn(()=>{v!==!1&&_.current[_.current.length-1]!==t&&(_.current.push(t),b(!1))},[_,t]);let E=w.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);Zn(()=>{t?p("visible"):!Vp(y)&&a.current!==null&&p("hidden")},[t,y]);let L={unmount:n},I=ts(()=>{var P;v&&b(!1),(P=s.beforeEnter)==null||P.call(s)}),R=ts(()=>{var P;v&&b(!1),(P=s.beforeLeave)==null||P.call(s)}),$=Nr();return Vt.createElement(Gp.Provider,{value:y},Vt.createElement(Hp.Provider,{value:E},$({ourProps:{...L,as:w.Fragment,children:Vt.createElement(NA,{ref:c,...L,...r,beforeEnter:I,beforeLeave:R})},theirProps:{},defaultTag:w.Fragment,features:IA,visible:f==="visible",name:"Transition"})))}function O5(s,e){let t=w.useContext(Hp)!==null,i=jp()!==null;return Vt.createElement(Vt.Fragment,null,!t&&i?Vt.createElement(Yv,{ref:e,...s}):Vt.createElement(NA,{ref:e,...s}))}let Yv=er(N5),NA=er(I5),Jx=er(O5),hh=Object.assign(Yv,{Child:Jx,Root:Yv});var M5=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(M5||{}),P5=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(P5||{});let B5={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},eb=w.createContext(null);eb.displayName="DialogContext";function zp(s){let e=w.useContext(eb);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,zp),t}return e}function F5(s,e){return fo(e.type,B5,s,e)}let NS=er(function(s,e){let t=w.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:a,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...p}=s,y=w.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(y.current||(y.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=jp();n===void 0&&v!==null&&(n=(v&qr.Open)===qr.Open);let b=w.useRef(null),_=Na(b,e),E=Xx(b.current),L=n?0:1,[I,R]=w.useReducer(F5,{titleId:null,descriptionId:null,panelRef:w.createRef()}),$=ts(()=>r(!1)),P=ts(he=>R({type:0,id:he})),B=$p()?L===0:!1,[O,H]=f5(),D={get current(){var he;return(he=I.panelRef.current)!=null?he:b.current}},M=AA(),{resolveContainers:W}=v5({mainTreeNode:M,portals:O,defaultContainers:[D]}),K=v!==null?(v&qr.Closing)===qr.Closing:!1;DN(d||K?!1:B,{allowed:ts(()=>{var he,be;return[(be=(he=b.current)==null?void 0:he.closest("[data-headlessui-portal]"))!=null?be:null]}),disallowed:ts(()=>{var he;return[(he=M?.closest("body > *:not(#headlessui-portal-root)"))!=null?he:null]})});let J=mA.get(null);Zn(()=>{if(B)return J.actions.push(i),()=>J.actions.pop(i)},[J,i,B]);let ue=pA(J,w.useCallback(he=>J.selectors.isTop(he,i),[J,i]));$N(ue,W,he=>{he.preventDefault(),$()}),g5(ue,E?.defaultView,he=>{he.preventDefault(),he.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),$()}),WN(d||K?!1:B,E,W),LN(B,b,$);let[se,q]=uN(),Y=w.useMemo(()=>[{dialogState:L,close:$,setTitleId:P,unmount:f},I],[L,$,P,f,I]),ie=Bh({open:L===0}),Q={ref:_,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:L===0?!0:void 0,"aria-labelledby":I.titleId,"aria-describedby":se,unmount:f},oe=!y5(),F=Ql.None;B&&!d&&(F|=Ql.RestoreFocus,F|=Ql.TabLock,c&&(F|=Ql.AutoFocus),oe&&(F|=Ql.InitialFocus));let ee=Nr();return Vt.createElement(r5,null,Vt.createElement(RS,{force:!0},Vt.createElement(p5,null,Vt.createElement(eb.Provider,{value:Y},Vt.createElement(EA,{target:b},Vt.createElement(RS,{force:!1},Vt.createElement(q,{slot:ie},Vt.createElement(H,null,Vt.createElement(E5,{initialFocus:a,initialFocusFallback:b,containers:W,features:F},Vt.createElement(pN,{value:$},ee({ourProps:Q,theirProps:p,slot:ie,defaultTag:U5,features:j5,visible:L===0,name:"Dialog"})))))))))))}),U5="div",j5=Zm.RenderStrategy|Zm.Static;function $5(s,e){let{transition:t=!1,open:i,...n}=s,r=jp(),a=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!a&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!a)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?Vt.createElement(IS,null,Vt.createElement(hh,{show:i,transition:t,unmount:n.unmount},Vt.createElement(NS,{ref:e,...n}))):Vt.createElement(IS,null,Vt.createElement(NS,{ref:e,open:i,...n}))}let H5="div";function G5(s,e){let t=w.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:a,unmount:u},c]=zp("Dialog.Panel"),d=Na(e,c.panelRef),f=Bh({open:a===0}),p=ts(E=>{E.stopPropagation()}),y={ref:d,id:i,onClick:p},v=n?Jx:w.Fragment,b=n?{unmount:u}:{},_=Nr();return Vt.createElement(v,{...b},_({ourProps:y,theirProps:r,slot:f,defaultTag:H5,name:"Dialog.Panel"}))}let V5="div";function z5(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=zp("Dialog.Backdrop"),a=Bh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?Jx:w.Fragment,d=t?{unmount:r}:{},f=Nr();return Vt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:a,defaultTag:V5,name:"Dialog.Backdrop"}))}let q5="h2";function K5(s,e){let t=w.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:a}]=zp("Dialog.Title"),u=Na(e);w.useEffect(()=>(a(i),()=>a(null)),[i,a]);let c=Bh({open:r===0}),d={ref:u,id:i};return Nr()({ourProps:d,theirProps:n,slot:c,defaultTag:q5,name:"Dialog.Title"})}let W5=er($5),Y5=er(G5);er(z5);let X5=er(K5),cc=Object.assign(W5,{Panel:Y5,Title:X5,Description:fN});function Q5({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=w.useState(""),[a,u]=w.useState(""),[c,d]=w.useState([]),f=w.useRef(!1);w.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function p(){const b=n.trim(),_=a.trim();!b||!_||(d(E=>[...E.filter(I=>I.name!==b),{name:b,value:_}]),r(""),u(""))}function y(b){d(_=>_.filter(E=>E.name!==b))}function v(){t(c),e()}return g.jsxs(cc,{open:s,onClose:e,className:"relative z-50",children:[g.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),g.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:g.jsxs(cc.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:[g.jsx(cc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),g.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[g.jsx("input",{value:n,onChange:b=>r(b.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"}),g.jsx("input",{value:a,onChange:b=>u(b.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"})]}),g.jsx("div",{className:"mt-2",children:g.jsx(Zt,{size:"sm",variant:"secondary",onClick:p,disabled:!n.trim()||!a.trim(),children:"Hinzufügen"})}),g.jsx("div",{className:"mt-4",children:c.length===0?g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):g.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[g.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:g.jsxs("tr",{children:[g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),g.jsx("th",{className:"px-3 py-2"})]})}),g.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(b=>g.jsxs("tr",{children:[g.jsx("td",{className:"px-3 py-2 font-mono",children:b.name}),g.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:b.value}),g.jsx("td",{className:"px-3 py-2 text-right",children:g.jsx("button",{onClick:()=>y(b.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},b.name))})]})}),g.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[g.jsx(Zt,{variant:"secondary",onClick:e,children:"Abbrechen"}),g.jsx(Zt,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function Z5({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 J5=w.forwardRef(Z5);function OS({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:a=!1}){if(!s?.length)return null;const u=s.find(y=>y.id===e)??s[0],c=mi("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=y=>mi(y?"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",a?"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=(y,v)=>v.count===void 0?null:g.jsx("span",{className:d(y),children:v.count}),p=()=>{switch(r){case"underline":case"underlineIcons":return g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:mi(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"&&y.icon?g.jsx(y.icon,{"aria-hidden":"true",className:mi(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,g.jsx("span",{children:y.label}),f(v,y)]},y.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const y=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 g.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(b=>{const _=b.id===u.id,E=!!b.disabled;return g.jsxs("button",{type:"button",onClick:()=>!E&&t(b.id),disabled:E,"aria-current":_?"page":void 0,className:mi(_?y: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:[g.jsx("span",{children:b.label}),b.count!==void 0?g.jsx("span",{className:mi(_?"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 g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:mi(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:y.label},y.id)})})});case"barUnderline":return g.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((y,v)=>{const b=y.id===u.id,_=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!_&&t(y.id),disabled:_,"aria-current":b?"page":void 0,className:mi(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:[g.jsxs("span",{className:"inline-flex items-center justify-center",children:[y.label,y.count!==void 0?g.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:y.count}):null]}),g.jsx("span",{"aria-hidden":"true",className:mi(b?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},y.id)})});case"simple":return g.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:g.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(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("li",{children:g.jsx("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:mi(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:y.label})},y.id)})})});default:return null}};return g.jsxs("div",{className:i,children:[g.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[g.jsx("select",{value:u.id,onChange:y=>t(y.target.value),"aria-label":n,className:c,children:s.map(y=>g.jsx("option",{value:y.id,children:y.label},y.id))}),g.jsx(J5,{"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"})]}),g.jsx("div",{className:"hidden sm:block",children:p()})]})}function Ca({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:a=!1,className:u,bodyClassName:c,children:d}){const f=r;return g.jsxs("div",{className:mi("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&&g.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),g.jsx("div",{className:mi("min-h-0",a?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&g.jsx("div",{className:mi("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 Xv({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:a,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:p}){const y=b=>{n||e(b.target.checked)},v=mi("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?g.jsxs("div",{className:mi("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:[g.jsx("span",{className:mi("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")}),g.jsx("span",{className:mi("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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]}):g.jsxs("div",{className:mi("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"?g.jsxs("span",{className:mi("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:[g.jsx("span",{"aria-hidden":"true",className:mi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:g.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:g.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx("span",{"aria-hidden":"true",className:mi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:g.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:g.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"})})})]}):g.jsx("span",{className:mi("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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function nl({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const a=w.useId(),u=i??`sw-${a}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?g.jsxs("div",{className:mi("flex items-center justify-between gap-3",n),children:[g.jsx(Xv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),g.jsxs("div",{className:"text-sm",children:[g.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?g.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):g.jsxs("div",{className:mi("flex items-center justify-between",n),children:[g.jsxs("span",{className:"flex grow flex-col",children:[g.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?g.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),g.jsx(Xv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}function wc({label:s,value:e=0,indeterminate:t=!1,showPercent:i=!1,rightLabel:n,steps:r,currentStep:a,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,y=p?r.length:0,v=E=>E===0?"text-left":E===y-1?"text-right":"text-center",b=E=>typeof a!="number"||!Number.isFinite(a)?!1:E<=a,_=i&&!t;return g.jsxs("div",{className:c,children:[s||_?g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s?g.jsx("p",{className:"flex-1 min-w-0 truncate text-xs font-medium text-gray-900 dark:text-white",children:s}):g.jsx("span",{className:"flex-1"}),_?g.jsxs("span",{className:"shrink-0 text-xs font-medium text-gray-700 dark:text-gray-300",children:[Math.round(d),"%"]}):null]}):null,g.jsxs("div",{"aria-hidden":"true",className:s||_?"mt-2":"",children:[g.jsx("div",{className:"overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:t?g.jsx("div",{className:`${f} w-full rounded-full bg-indigo-600/70 dark:bg-indigo-500/70 animate-pulse`}):g.jsx("div",{className:`${f} rounded-full bg-indigo-600 dark:bg-indigo-500 transition-[width] duration-200`,style:{width:`${d}%`}})}),n?g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:n}):null,p?g.jsx("div",{className:"mt-3 hidden text-sm font-medium text-gray-600 sm:grid dark:text-gray-400",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:r.map((E,L)=>g.jsx("div",{className:[v(L),b(L)?"text-indigo-600 dark:text-indigo-400":""].join(" "),children:E},`${L}-${E}`))}):null]})]})}async function MS(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 eO({onFinished:s}){const[e,t]=w.useState(null),[i,n]=w.useState(null),[r,a]=w.useState(!1),[u,c]=w.useState(!1),d=w.useCallback(async()=>{try{const $=await MS("/api/tasks/generate-assets");t($)}catch($){n($?.message??String($))}},[]),f=w.useRef(!1);w.useEffect(()=>{const $=f.current,P=!!e?.running;f.current=P,$&&!P&&s?.()},[e?.running,s]),w.useEffect(()=>{d()},[d]),w.useEffect(()=>{if(!e?.running)return;const $=window.setInterval(d,1200);return()=>window.clearInterval($)},[e?.running,d]);async function p(){n(null),a(!0);try{const $=await MS("/api/tasks/generate-assets",{method:"POST"});t($)}catch($){n($?.message??String($))}finally{a(!1)}}async function y(){n(null),c(!0);try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}finally{await d(),c(!1)}}const v=!!e?.running,b=e?.total??0,_=e?.done??0,E=b>0?Math.min(100,Math.round(_/b*100)):0,L=$=>{const P=String($??"").trim();if(!P)return null;const B=new Date(P);return Number.isFinite(B.getTime())?B.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):null},I=L(e?.startedAt),R=L(e?.finishedAt);return g.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:[g.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Assets-Generator"}),v?g.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"}):g.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"})]}),g.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-white/70",children:["Erzeugt pro fertiger Datei unter ",g.jsx("span",{className:"font-mono",children:"/generated//"})," ",g.jsx("span",{className:"font-mono",children:"thumbs.jpg"}),", ",g.jsx("span",{className:"font-mono",children:"preview.mp4"})," ","und ",g.jsx("span",{className:"font-mono",children:"meta.json"})," für schnelle Listen & zuverlässige Duration."]})]}),g.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[v?g.jsx(Zt,{variant:"secondary",color:"red",onClick:y,disabled:u,className:"w-full sm:w-auto",children:u?"Stoppe…":"Stop"}):null,g.jsx(Zt,{variant:"primary",onClick:p,disabled:r||v,className:"w-full sm:w-auto",children:r?"Starte…":v?"Läuft…":"Generieren"})]})]}),i?g.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?g.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?g.jsxs("div",{className:"mt-4 space-y-3",children:[g.jsx(wc,{value:E,showPercent:!0,rightLabel:b?`${_}/${b} Dateien`:"—"}),g.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Thumbs"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedThumbs??0})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Previews"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedPreviews??0})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Übersprungen"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.skipped??0})]})]}),g.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:[g.jsx("span",{children:I?g.jsxs(g.Fragment,{children:["Start: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:I})]}):"Start: —"}),g.jsx("span",{children:R?g.jsxs(g.Fragment,{children:["Ende: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R})]}):"Ende: —"})]})]}):g.jsx("div",{className:"mt-4 text-xs text-gray-600 dark:text-white/70",children:"Status wird geladen…"})]})}const js={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!0,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:5};function tO({onAssetsGenerated:s}){const[e,t]=w.useState(js),[i,n]=w.useState(!1),[r,a]=w.useState(!1),[u,c]=w.useState(null),[d,f]=w.useState(null),[p,y]=w.useState(null),[v,b]=w.useState(null),_=Number(e.lowDiskPauseBelowGB??js.lowDiskPauseBelowGB??5),E=v?.pauseGB??_,L=v?.resumeGB??_+3;w.useEffect(()=>{let P=!0;return fetch("/api/settings",{cache:"no-store"}).then(async B=>{if(!B.ok)throw new Error(await B.text());return B.json()}).then(B=>{P&&t({recordDir:(B.recordDir||js.recordDir).toString(),doneDir:(B.doneDir||js.doneDir).toString(),ffmpegPath:String(B.ffmpegPath??js.ffmpegPath??""),autoAddToDownloadList:B.autoAddToDownloadList??js.autoAddToDownloadList,autoStartAddedDownloads:B.autoStartAddedDownloads??js.autoStartAddedDownloads,useChaturbateApi:B.useChaturbateApi??js.useChaturbateApi,useMyFreeCamsWatcher:B.useMyFreeCamsWatcher??js.useMyFreeCamsWatcher,autoDeleteSmallDownloads:B.autoDeleteSmallDownloads??js.autoDeleteSmallDownloads,autoDeleteSmallDownloadsBelowMB:B.autoDeleteSmallDownloadsBelowMB??js.autoDeleteSmallDownloadsBelowMB,blurPreviews:B.blurPreviews??js.blurPreviews,teaserPlayback:B.teaserPlayback??js.teaserPlayback,teaserAudio:B.teaserAudio??js.teaserAudio,lowDiskPauseBelowGB:B.lowDiskPauseBelowGB??js.lowDiskPauseBelowGB})}).catch(()=>{}),()=>{P=!1}},[]),w.useEffect(()=>{let P=!0;const B=async()=>{try{const H=await fetch("/api/status/disk",{cache:"no-store"});if(!H.ok)return;const D=await H.json();P&&b(D)}catch{}};B();const O=window.setInterval(B,5e3);return()=>{P=!1,window.clearInterval(O)}},[]);async function I(P){y(null),f(null),c(P);try{window.focus();const B=await fetch(`/api/settings/browse?target=${P}`,{cache:"no-store"});if(B.status===204)return;if(!B.ok){const D=await B.text().catch(()=>"");throw new Error(D||`HTTP ${B.status}`)}const H=((await B.json()).path??"").trim();if(!H)return;t(D=>P==="record"?{...D,recordDir:H}:P==="done"?{...D,doneDir:H}:{...D,ffmpegPath:H})}catch(B){y(B?.message??String(B))}finally{c(null)}}async function R(){y(null),f(null);const P=e.recordDir.trim(),B=e.doneDir.trim(),O=(e.ffmpegPath??"").trim();if(!P||!B){y("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const H=!!e.autoAddToDownloadList,D=H?!!e.autoStartAddedDownloads:!1,M=!!e.useChaturbateApi,W=!!e.useMyFreeCamsWatcher,K=!!e.autoDeleteSmallDownloads,J=Math.max(0,Math.min(1e5,Math.floor(Number(e.autoDeleteSmallDownloadsBelowMB??js.autoDeleteSmallDownloadsBelowMB)))),ue=!!e.blurPreviews,se=e.teaserPlayback==="still"||e.teaserPlayback==="all"||e.teaserPlayback==="hover"?e.teaserPlayback:js.teaserPlayback,q=!!e.teaserAudio,Y=Math.max(1,Math.floor(Number(e.lowDiskPauseBelowGB??js.lowDiskPauseBelowGB)));n(!0);try{const ie=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:P,doneDir:B,ffmpegPath:O,autoAddToDownloadList:H,autoStartAddedDownloads:D,useChaturbateApi:M,useMyFreeCamsWatcher:W,autoDeleteSmallDownloads:K,autoDeleteSmallDownloadsBelowMB:J,blurPreviews:ue,teaserPlayback:se,teaserAudio:q,lowDiskPauseBelowGB:Y})});if(!ie.ok){const Q=await ie.text().catch(()=>"");throw new Error(Q||`HTTP ${ie.status}`)}f("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(ie){y(ie?.message??String(ie))}finally{n(!1)}}async function $(){y(null),f(null);const P=Number(e.autoDeleteSmallDownloadsBelowMB??js.autoDeleteSmallDownloadsBelowMB??0),B=(e.doneDir||js.doneDir).trim();if(!B){y("doneDir ist leer.");return}if(!P||P<=0){y("Mindestgröße ist 0 – es würde nichts gelöscht.");return}if(window.confirm(`Aufräumen: -• Löscht Dateien in "${B}" < ${P} MB (Ordner "keep" wird übersprungen) -• Entfernt verwaiste Previews/Thumbs/Generated-Assets ohne passende Datei - -Fortfahren?`)){a(!0);try{const H=await fetch("/api/settings/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store"});if(!H.ok){const M=await H.text().catch(()=>"");throw new Error(M||`HTTP ${H.status}`)}const D=await H.json();f(`🧹 Aufräumen fertig: -• Gelöscht: ${D.deletedFiles} Datei(en) (${D.deletedBytesHuman}) -• Geprüft: ${D.scannedFiles} · Übersprungen: ${D.skippedFiles} · Fehler: ${D.errorCount} -• Orphans: ${D.orphanIdsRemoved}/${D.orphanIdsScanned} entfernt (Previews/Thumbs/Generated)`)}catch(H){y(H?.message??String(H))}finally{a(!1)}}}return g.jsx(Ca,{header:g.jsxs("div",{className:"flex items-center justify-between gap-4",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"}),g.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Recorder-Konfiguration, Automatisierung und Tasks."})]}),g.jsx(Zt,{variant:"primary",onClick:R,disabled:i,children:"Speichern"})]}),grayBody:!0,children:g.jsxs("div",{className:"space-y-4",children:[p&&g.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:p}),d&&g.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:d}),g.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:[g.jsxs("div",{className:"flex items-start justify-between gap-4",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tasks"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Generiere fehlende Vorschauen/Metadaten für schnelle Listenansichten."})]}),g.jsx("div",{className:"shrink-0",children:g.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"})})]}),g.jsx("div",{className:"mt-3",children:g.jsx(eO,{onFinished:s})})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Pfad-Einstellungen"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aufnahme- und Zielverzeichnisse sowie optionaler ffmpeg-Pfad."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.recordDir,onChange:P=>t(B=>({...B,recordDir:P.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`}),g.jsx(Zt,{variant:"secondary",onClick:()=>I("record"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.doneDir,onChange:P=>t(B=>({...B,doneDir:P.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`}),g.jsx(Zt,{variant:"secondary",onClick:()=>I("done"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.ffmpegPath??"",onChange:P=>t(B=>({...B,ffmpegPath:P.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`}),g.jsx(Zt,{variant:"secondary",onClick:()=>I("ffmpeg"),disabled:i||u!==null,children:"Durchsuchen..."})]})]})]})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Automatisierung & Anzeige"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Verhalten beim Hinzufügen/Starten sowie Anzeigeoptionen."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsx(nl,{checked:!!e.autoAddToDownloadList,onChange:P=>t(B=>({...B,autoAddToDownloadList:P,autoStartAddedDownloads:P?B.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),g.jsx(nl,{checked:!!e.autoStartAddedDownloads,onChange:P=>t(B=>({...B,autoStartAddedDownloads:P})),disabled:!e.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),g.jsx(nl,{checked:!!e.useChaturbateApi,onChange:P=>t(B=>({...B,useChaturbateApi:P})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),g.jsx(nl,{checked:!!e.useMyFreeCamsWatcher,onChange:P=>t(B=>({...B,useMyFreeCamsWatcher:P})),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."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx(nl,{checked:!!e.autoDeleteSmallDownloads,onChange:P=>t(B=>({...B,autoDeleteSmallDownloads:P,autoDeleteSmallDownloadsBelowMB:B.autoDeleteSmallDownloadsBelowMB??50})),label:"Kleine Downloads automatisch löschen",description:"Löscht fertige Downloads automatisch, wenn die Datei kleiner als die eingestellte Mindestgröße ist."}),g.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:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Mindestgröße"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Alles darunter wird gelöscht."})]}),g.jsx("div",{className:"sm:col-span-8",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("input",{type:"number",min:0,step:1,value:e.autoDeleteSmallDownloadsBelowMB??50,onChange:P=>t(B=>({...B,autoDeleteSmallDownloadsBelowMB:Number(P.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`}),g.jsx("span",{className:"shrink-0 text-xs text-gray-600 dark:text-gray-300",children:"MB"}),g.jsx(Zt,{variant:"secondary",onClick:$,disabled:i||r||!e.autoDeleteSmallDownloads,className:"h-9 shrink-0 px-3",title:"Löscht Dateien im doneDir kleiner als die Mindestgröße (keep wird übersprungen)",children:r?"…":"Aufräumen"})]})})]})]}),g.jsx(nl,{checked:!!e.blurPreviews,onChange:P=>t(B=>({...B,blurPreviews:P})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Teaser abspielen"}),g.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."})]}),g.jsxs("div",{className:"sm:col-span-8",children:[g.jsx("label",{className:"sr-only",htmlFor:"teaserPlayback",children:"Teaser abspielen"}),g.jsxs("select",{id:"teaserPlayback",value:e.teaserPlayback??"hover",onChange:P=>t(B=>({...B,teaserPlayback:P.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:[g.jsx("option",{value:"still",children:"Standbild"}),g.jsx("option",{value:"hover",children:"Bei Hover (Standard)"}),g.jsx("option",{value:"all",children:"Alle"})]})]})]}),g.jsx(nl,{checked:!!e.teaserAudio,onChange:P=>t(B=>({...B,teaserAudio:P})),label:"Teaser mit Ton",description:"Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Speicherplatz-Notbremse"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aktiviert automatisch Stop + Autostart-Block bei wenig freiem Speicher (Resume bei +3 GB)."})]}),g.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium "+(v?.emergency?"bg-red-100 text-red-800 dark:bg-red-500/20 dark:text-red-200":"bg-green-100 text-green-800 dark:bg-green-500/20 dark:text-green-200"),title:v?.emergency?"Notfallbremse greift gerade":"OK",children:v?.emergency?"AKTIV":"OK"})]}),g.jsxs("div",{className:"mt-3 text-sm text-gray-900 dark:text-gray-200",children:[g.jsxs("div",{children:[g.jsx("span",{className:"font-medium",children:"Schwelle:"})," ","Pause unter ",g.jsx("span",{className:"tabular-nums",children:E})," GB"," · ","Resume ab"," ",g.jsx("span",{className:"tabular-nums",children:L})," ","GB"]}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:v?`Frei: ${v.freeBytesHuman}${v.recordPath?` (Pfad: ${v.recordPath})`:""}`:"Status wird geladen…"}),v?.emergency&&g.jsx("div",{className:"mt-2 text-xs text-red-700 dark:text-red-200",children:"Notfallbremse greift: laufende Downloads werden gestoppt und Autostart bleibt gesperrt, bis wieder genug frei ist."})]})]})]})]})]})})}function iO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 sO=w.forwardRef(iO);function nO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 rO=w.forwardRef(nO);function aO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 oO=w.forwardRef(aO);function lO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 uO=w.forwardRef(lO);function zn(...s){return s.filter(Boolean).join(" ")}function PS(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function cO(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function BS(s,e){const t=s===0,i=s===e-1;return t||i?"pl-2 pr-2":"px-2"}function FS(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 fh({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:a=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:p=!1,emptyLabel:y="Keine Daten vorhanden.",className:v,rowClassName:b,onRowClick:_,onRowContextMenu:E,sort:L,onSortChange:I,defaultSort:R=null}){const $=f?"py-2":"py-4",P=f?"py-3":"py-3.5",B=L!==void 0,[O,H]=w.useState(R),D=B?L:O,M=w.useCallback(K=>{B||H(K),I?.(K)},[B,I]),W=w.useMemo(()=>{if(!D)return e;const K=s.find(se=>se.key===D.key);if(!K)return e;const J=D.direction==="asc"?1:-1,ue=e.map((se,q)=>({r:se,i:q}));return ue.sort((se,q)=>{let Y=0;if(K.sortFn)Y=K.sortFn(se.r,q.r);else{const ie=K.sortValue?K.sortValue(se.r):se.r?.[K.key],Q=K.sortValue?K.sortValue(q.r):q.r?.[K.key],oe=FS(ie),F=FS(Q);oe.isNull&&!F.isNull?Y=1:!oe.isNull&&F.isNull?Y=-1:oe.kind==="number"&&F.kind==="number"?Y=oe.valueF.value?1:0:Y=String(oe.value).localeCompare(String(F.value),void 0,{numeric:!0})}return Y===0?se.i-q.i:Y*J}),ue.map(se=>se.r)},[e,s,D]);return g.jsxs("div",{className:zn(a?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&g.jsxs("div",{className:"sm:flex sm:items-center",children:[g.jsxs("div",{className:"sm:flex-auto",children:[i&&g.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&g.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&g.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),g.jsx("div",{className:zn(i||n||r?"mt-8":""),children:g.jsx("div",{className:"flow-root",children:g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:zn("inline-block min-w-full align-middle",a?"":"sm:px-6 lg:px-8"),children:g.jsx("div",{className:zn(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:g.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[g.jsx("thead",{className:zn(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:g.jsx("tr",{children:s.map((K,J)=>{const ue=BS(J,s.length),se=!!D&&D.key===K.key,q=se?D.direction:void 0,Y=K.sortable&&!K.srOnlyHeader?se?q==="asc"?"ascending":"descending":"none":void 0,ie=()=>{if(!(!K.sortable||K.srOnlyHeader))return M(se?q==="asc"?{key:K.key,direction:"desc"}:null:{key:K.key,direction:"asc"})};return g.jsx("th",{scope:"col","aria-sort":Y,className:zn(P,ue,"text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",PS(K.align),K.widthClassName,K.headerClassName),children:K.srOnlyHeader?g.jsx("span",{className:"sr-only",children:K.header}):K.sortable?g.jsxs("button",{type:"button",onClick:ie,className:zn("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",cO(K.align)),children:[g.jsx("span",{children:K.header}),g.jsx("span",{className:zn("flex-none rounded-sm text-gray-400 dark:text-gray-500",se?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:g.jsx(sO,{"aria-hidden":"true",className:zn("size-5 transition-transform",se&&q==="asc"&&"rotate-180")})})]}):K.header},K.key)})})}),g.jsx("tbody",{className:zn("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?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:zn($,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):W.length===0?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:zn($,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:y})}):W.map((K,J)=>{const ue=t?t(K,J):String(J);return g.jsx("tr",{className:zn(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?.(K,J)),onClick:()=>_?.(K),onContextMenu:E?se=>{se.preventDefault(),E(K,se)}:void 0,children:s.map((se,q)=>{const Y=BS(q,s.length),ie=se.cell?.(K,J)??se.accessor?.(K)??K?.[se.key];return g.jsx("td",{className:zn($,Y,"text-sm whitespace-nowrap",PS(se.align),se.className,se.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:ie},se.key)})},ue)})})]})})})})})})]})}function OA({children:s,content:e}){const t=w.useRef(null),i=w.useRef(null),[n,r]=w.useState(!1),[a,u]=w.useState(null),c=w.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)},y=()=>{f()},v=()=>{d(),r(!1)},b=()=>{const E=t.current,L=i.current;if(!E||!L)return;const I=8,R=8,$=E.getBoundingClientRect(),P=L.getBoundingClientRect();let B=$.bottom+I;if(B+P.height>window.innerHeight-R){const D=$.top-P.height-I;D>=R?B=D:B=Math.max(R,window.innerHeight-P.height-R)}let H=$.left;H+P.width>window.innerWidth-R&&(H=window.innerWidth-P.width-R),H=Math.max(R,H),u({left:H,top:B})};w.useLayoutEffect(()=>{if(!n)return;const E=requestAnimationFrame(()=>b());return()=>cancelAnimationFrame(E)},[n]),w.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]),w.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n,{close:v}):e;return g.jsxs(g.Fragment,{children:[g.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:p,onMouseLeave:y,children:s}),n&&Ec.createPortal(g.jsx("div",{ref:i,className:"fixed z-50",style:{left:a?.left??-9999,top:a?.top??-9999,visibility:a?"visible":"hidden"},onMouseEnter:p,onMouseLeave:y,children:g.jsx(Ca,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:_()})}),document.body)]})}const tp=!0,dO=!1;function ip(s,e){if(!s)return;const t=e?.muted??tp;s.muted=t,s.defaultMuted=t,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","")}function tb({job:s,getFileName:e,durationSeconds:t,onDuration:i,animated:n=!1,animatedMode:r="frames",animatedTrigger:a="always",autoTickMs:u=15e3,thumbStepSec:c,thumbSpread:d,thumbSamples:f,clipSeconds:p=1,variant:y="thumb",className:v,showPopover:b=!0,blur:_=!1,inlineVideo:E=!1,inlineNonce:L=0,inlineControls:I=!1,inlineLoop:R=!0,assetNonce:$=0,muted:P=tp,popoverMuted:B=tp,noGenerateTeaser:O}){const H=e(s.output||""),D=_?"blur-md":"",M={muted:P,playsInline:!0,preload:"metadata"},[W,K]=w.useState(!0),[J,ue]=w.useState(!0),[se,q]=w.useState(!1),[Y,ie]=w.useState(!1),[Q,oe]=w.useState(!0),F=w.useRef(null),[ee,he]=w.useState(!1),[be,pe]=w.useState(!1),[Ce,Re]=w.useState(0),[Ze,Ge]=w.useState(!1),it=E===!0||E==="always"?"always":E==="hover"?"hover":"never",dt=Ke=>Ke.startsWith("HOT ")?Ke.slice(4):Ke,ot=w.useMemo(()=>{const Ke=e(s.output||"");if(!Ke)return"";const Lt=Ke.replace(/\.[^.]+$/,"");return dt(Lt).trim()},[s.output,e]),nt=w.useMemo(()=>H?`/api/record/video?file=${encodeURIComponent(H)}`:"",[H]),ft=typeof t=="number"&&Number.isFinite(t)&&t>0,gt=y==="fill"?"w-full h-full":"w-20 h-16",je=w.useRef(null),bt=w.useRef(null),vt=w.useRef(null),jt=Ke=>{if(Ke){try{Ke.pause()}catch{}try{Ke.removeAttribute("src"),Ke.src="",Ke.load()}catch{}}};w.useEffect(()=>{ie(!1),oe(!0)},[ot,$,O]),w.useEffect(()=>{const Ke=Lt=>{const Qt=String(Lt?.detail?.file??"");!Qt||Qt!==H||(jt(je.current),jt(bt.current),jt(vt.current))};return window.addEventListener("player:release",Ke),window.addEventListener("player:close",Ke),()=>{window.removeEventListener("player:release",Ke),window.removeEventListener("player:close",Ke)}},[H]),w.useEffect(()=>{const Ke=F.current;if(!Ke)return;const Lt=new IntersectionObserver(Qt=>{const Ut=!!Qt[0]?.isIntersecting;he(Ut),Ut&&pe(!0)},{threshold:.01,rootMargin:"350px 0px"});return Lt.observe(Ke),()=>Lt.disconnect()},[]),w.useEffect(()=>{if(!n||r!=="frames"||!ee||document.hidden)return;const Ke=window.setInterval(()=>Re(Lt=>Lt+1),u);return()=>window.clearInterval(Ke)},[n,r,ee,u]);const We=w.useMemo(()=>{if(!n||r!=="frames"||!ft)return null;const Ke=t,Lt=Math.max(.25,c??3);if(d){const ci=Math.max(4,Math.min(f??16,Math.floor(Ke))),vi=Ce%ci,ei=Math.max(.1,Ke-Lt),Bi=Math.min(.25,ei*.02),yt=vi/ci*ei+Bi;return Math.min(Ke-.05,Math.max(.05,yt))}const Qt=Math.max(Ke-.1,Lt),Ut=Ce*Lt%Qt;return Math.min(Ke-.05,Math.max(.05,Ut))},[n,r,ft,t,Ce,c,d,f]),ut=$??0,ge=w.useMemo(()=>ot?We==null?`/api/record/preview?id=${encodeURIComponent(ot)}&v=${ut}`:`/api/record/preview?id=${encodeURIComponent(ot)}&t=${We}&v=${ut}-${Ce}`:"",[ot,We,Ce,ut]),Je=w.useMemo(()=>{if(!ot)return"";const Ke=O?"&noGenerate=1":"";return`/api/generated/teaser?id=${encodeURIComponent(ot)}${Ke}&v=${ut}`},[ot,ut,O]),Ye=Ke=>{if(q(!0),!i)return;const Lt=Ke.currentTarget.duration;Number.isFinite(Lt)&&Lt>0&&i(s,Lt)};if(w.useEffect(()=>{K(!0),ue(!0)},[ot,$]),!nt)return g.jsx("div",{className:[gt,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});const Qe=it!=="never"&&ee&&J&&(it==="always"||it==="hover"&&Ze),mt=n&&ee&&!document.hidden&&J&&!Qe&&(a==="always"||Ze)&&(r==="teaser"&&Q&&!!Je||r==="clips"&&ft),ct=it==="hover"||n&&(r==="clips"||r==="teaser")&&a==="hover",et=be||ct&&Ze,Gt=w.useMemo(()=>{if(!n)return[];if(r!=="clips")return[];if(!ft)return[];const Ke=t,Lt=Math.max(.25,p),Qt=Math.max(8,Math.min(f??18,Math.floor(Ke))),Ut=Math.max(.1,Ke-Lt),ci=Math.min(.25,Ut*.02),vi=[];for(let ei=0;eiGt.map(Ke=>Ke.toFixed(2)).join(","),[Gt]),It=w.useRef(0),Ft=w.useRef(0);w.useEffect(()=>{const Ke=bt.current;if(!Ke)return;if(!(mt&&r==="teaser")){try{Ke.pause()}catch{}return}ip(Ke,{muted:P});const Qt=Ke.play?.();Qt&&typeof Qt.catch=="function"&&Qt.catch(()=>{})},[mt,r,Je,P]),w.useEffect(()=>{Qe&&ip(je.current,{muted:P})},[Qe,P]),w.useEffect(()=>{const Ke=vt.current;if(!Ke)return;if(!(mt&&r==="clips")){mt||Ke.pause();return}if(!Gt.length)return;It.current=It.current%Gt.length,Ft.current=Gt[It.current];const Lt=()=>{try{Ke.currentTime=Ft.current}catch{}const ci=Ke.play();ci&&typeof ci.catch=="function"&&ci.catch(()=>{})},Qt=()=>Lt(),Ut=()=>{if(Gt.length&&Ke.currentTime-Ft.current>=p){It.current=(It.current+1)%Gt.length,Ft.current=Gt[It.current];try{Ke.currentTime=Ft.current+.01}catch{}}};return Ke.addEventListener("loadedmetadata",Qt),Ke.addEventListener("timeupdate",Ut),Ke.readyState>=1&&Lt(),()=>{Ke.removeEventListener("loadedmetadata",Qt),Ke.removeEventListener("timeupdate",Ut),Ke.pause()}},[mt,r,Jt,p,Gt]);const $t=g.jsxs("div",{ref:F,className:["rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",gt,v??""].join(" "),onMouseEnter:ct?()=>Ge(!0):void 0,onMouseLeave:ct?()=>Ge(!1):void 0,onFocus:ct?()=>Ge(!0):void 0,onBlur:ct?()=>Ge(!1):void 0,children:[et&&ge&&W?g.jsx("img",{src:ge,loading:"lazy",decoding:"async",alt:H,className:["absolute inset-0 w-full h-full object-cover",D].filter(Boolean).join(" "),onError:()=>K(!1)}):g.jsx("div",{className:"absolute inset-0 bg-black/10 dark:bg-white/10"}),Qe?w.createElement("video",{...M,ref:je,key:`inline-${ot}-${L}`,src:nt,className:["absolute inset-0 w-full h-full object-cover",D,I?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),autoPlay:!0,muted:P,controls:I,loop:R,poster:et&&ge||void 0,onLoadedMetadata:Ye,onError:()=>ue(!1)}):null,!Qe&&mt&&r==="teaser"?g.jsx("video",{ref:bt,src:Je,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",D,Y?"opacity-100":"opacity-0","transition-opacity duration-150"].filter(Boolean).join(" "),muted:P,playsInline:!0,autoPlay:!0,loop:!0,preload:"metadata",poster:et&&ge||void 0,onLoadedData:()=>ie(!0),onPlaying:()=>ie(!0),onError:()=>{oe(!1),ie(!1)}},`teaser-mp4-${ot}`):null,!Qe&&mt&&r==="clips"?g.jsx("video",{ref:vt,src:nt,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",D].filter(Boolean).join(" "),muted:P,playsInline:!0,preload:"metadata",poster:et&&ge||void 0,onError:()=>ue(!1)},`clips-${ot}-${Jt}`):null,ee&&i&&!ft&&!se&&!Qe&&g.jsx("video",{src:nt,preload:"metadata",muted:P,playsInline:!0,className:"hidden",onLoadedMetadata:Ye})]});return b?g.jsx(OA,{content:Ke=>Ke&&g.jsx("div",{className:"w-[420px]",children:g.jsx("div",{className:"aspect-video",children:g.jsx("video",{src:nt,className:["w-full h-full bg-black",D].filter(Boolean).join(" "),muted:B,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:Lt=>Lt.stopPropagation(),onMouseDown:Lt=>Lt.stopPropagation()})})}),children:$t}):$t}function by(...s){return s.filter(Boolean).join(" ")}const hO={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 fO({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const a=hO[i];return g.jsx("span",{className:by("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,y=!u.label&&!!u.icon;return g.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:by("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",y?"px-2 py-2":a.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[y&&u.srLabel?g.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?g.jsx("span",{className:by("shrink-0",y?"":"-ml-0.5",d?"text-indigo-600 dark:text-indigo-200":"text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?g.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function mO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const pO=w.forwardRef(mO);function gO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const US=w.forwardRef(gO);function yO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 Ty=w.forwardRef(yO);function vO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 xO=w.forwardRef(vO);function bO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 TO=w.forwardRef(bO);function _O({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 Qv=w.forwardRef(_O);function SO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 jS=w.forwardRef(SO);function EO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 wO=w.forwardRef(EO);function AO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 CO=w.forwardRef(AO);function kO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 DO=w.forwardRef(kO);function LO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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"}),w.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const Zv=w.forwardRef(LO);function RO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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"}),w.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 $S=w.forwardRef(RO);function IO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 sp=w.forwardRef(IO);function NO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 OO=w.forwardRef(NO);function MO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 PO=w.forwardRef(MO);function BO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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=w.forwardRef(BO);function UO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 jO=w.forwardRef(UO);function $O({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 HS=w.forwardRef($O);function HO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}),w.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 GO=w.forwardRef(HO);function VO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 zO=w.forwardRef(VO);function qO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 KO=w.forwardRef(qO);function WO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 GS=w.forwardRef(WO);function YO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 XO=w.forwardRef(YO);function QO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 Jv=w.forwardRef(QO);function ZO({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 JO=w.forwardRef(ZO);function eM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 ex=w.forwardRef(eM);function tM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 iM=w.forwardRef(tM);function sM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 nM=w.forwardRef(sM);function rM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const ib=w.forwardRef(rM);function hm(...s){return s.filter(Boolean).join(" ")}const aM=w.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:a,className:u,leftAction:c={label:g.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[g.jsx(Qv,{className:"h-6 w-6","aria-hidden":"true"}),g.jsx("span",{children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:g.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[g.jsx(ex,{className:"h-6 w-6","aria-hidden":"true"}),g.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=180,thresholdRatio:p=.1,ignoreFromBottomPx:y=72,ignoreSelector:v="[data-swipe-ignore]",snapMs:b=180,commitMs:_=180,tapIgnoreSelector:E="button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]",onDoubleTap:L,hotTargetSelector:I="[data-hot-target]",doubleTapMs:R=360,doubleTapMaxMovePx:$=48},P){const B=w.useRef(null),O=w.useRef(!1),H=w.useRef(0),D=w.useRef(null),M=w.useRef(0),W=w.useRef(null),K=w.useRef(null),J=w.useRef(null),ue=w.useRef(null),se=w.useRef({id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1}),[q,Y]=w.useState(0),[ie,Q]=w.useState(null),[oe,F]=w.useState(0),ee=w.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),H.current=0,B.current&&(B.current.style.touchAction="pan-y"),F(b),Y(0),Q(null),window.setTimeout(()=>F(0),b)},[b]),he=w.useCallback(async(Re,Ze)=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),B.current&&(B.current.style.touchAction="pan-y");const it=B.current?.offsetWidth||360;F(_),Q(Re==="right"?"right":"left");const dt=Re==="right"?it+40:-(it+40);H.current=dt,Y(dt);let ot=!0;if(Ze)try{ot=Re==="right"?await a():await r()}catch{ot=!1}return ot===!1?(F(b),Q(null),Y(0),window.setTimeout(()=>F(0),b),!1):!0},[_,r,a,b]),be=w.useCallback(()=>{K.current!=null&&(window.clearTimeout(K.current),K.current=null)},[]),pe=w.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),H.current=0,F(0),Y(0),Q(null);try{const Re=B.current;Re&&(Re.style.touchAction="pan-y")}catch{}},[]),Ce=w.useCallback((Re,Ze)=>{const Ge=W.current,it=B.current;if(!Ge||!it)return;const dt=ue.current;if(!dt)return;const ot=Ge.getBoundingClientRect();let nt=ot.width/2,ft=ot.height/2;typeof Re=="number"&&typeof Ze=="number"&&(nt=Re-ot.left,ft=Ze-ot.top,nt=Math.max(0,Math.min(ot.width,nt)),ft=Math.max(0,Math.min(ot.height,ft)));const gt=I?it.querySelector(I):null;let je=nt,bt=ft;if(gt){const et=gt.getBoundingClientRect();je=et.left-ot.left+et.width/2,bt=et.top-ot.top+et.height/2}const vt=je-nt,jt=bt-ft,We=document.createElement("div");We.textContent="🔥",We.style.position="absolute",We.style.left=`${nt}px`,We.style.top=`${ft}px`,We.style.transform="translate(-50%, -50%)",We.style.fontSize="30px",We.style.filter="drop-shadow(0 10px 16px rgba(0,0,0,0.22))",We.style.pointerEvents="none",We.style.willChange="transform, opacity",dt.appendChild(We);const ut=200,ge=500,Je=400,Ye=ut+ge+Je,Qe=ut/Ye,mt=(ut+ge)/Ye,ct=We.animate([{transform:"translate(-50%, -50%) scale(0.15)",opacity:0,offset:0},{transform:"translate(-50%, -50%) scale(1.25)",opacity:1,offset:Qe*.55},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:Qe},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:mt},{transform:`translate(calc(-50% + ${vt}px), calc(-50% + ${jt}px)) scale(0.85)`,opacity:.95,offset:mt+(1-mt)*.75},{transform:`translate(calc(-50% + ${vt}px), calc(-50% + ${jt}px)) scale(0.55)`,opacity:0,offset:1}],{duration:Ye,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)",fill:"forwards"});gt&&window.setTimeout(()=>{try{gt.animate([{transform:"translateZ(0) scale(1)",filter:"brightness(1)"},{transform:"translateZ(0) scale(1.10)",filter:"brightness(1.25)",offset:.35},{transform:"translateZ(0) scale(1)",filter:"brightness(1)"}],{duration:260,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)"})}catch{}},ut+ge+Math.round(Je*.75)),ct.onfinish=()=>We.remove()},[I]);return w.useEffect(()=>()=>{K.current!=null&&window.clearTimeout(K.current)},[]),w.useImperativeHandle(P,()=>({swipeLeft:Re=>he("left",Re?.runAction??!0),swipeRight:Re=>he("right",Re?.runAction??!0),reset:()=>ee()}),[he,ee]),g.jsxs("div",{ref:W,className:hm("relative isolate overflow-hidden rounded-lg",u),children:[g.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[g.jsx("div",{className:hm("absolute inset-0 transition-opacity duration-200 ease-out",q===0?"opacity-0":"opacity-100",q>0?c.className:d.className)}),g.jsx("div",{className:hm("absolute inset-0 flex items-center transition-all duration-200 ease-out"),style:{transform:`translateX(${Math.max(-24,Math.min(24,q/8))}px)`,opacity:q===0?0:1,justifyContent:q>0?"flex-start":"flex-end",paddingLeft:q>0?16:0,paddingRight:q>0?0:16},children:q>0?c.label:d.label})]}),g.jsx("div",{ref:ue,className:"pointer-events-none absolute inset-0 z-50"}),g.jsx("div",{ref:B,className:"relative",style:{transform:q!==0?`translate3d(${q}px,0,0)`:void 0,transition:oe?`transform ${oe}ms ease`:void 0,touchAction:"pan-y",willChange:q!==0?"transform":void 0},onPointerDown:Re=>{if(!t||i)return;const Ze=Re.target,Ge=!!(E&&Ze?.closest?.(E));if(v&&Ze?.closest?.(v))return;const it=Re.currentTarget,ot=Array.from(it.querySelectorAll("video")).find(bt=>bt.controls);if(ot){const bt=ot.getBoundingClientRect();if(Re.clientX>=bt.left&&Re.clientX<=bt.right&&Re.clientY>=bt.top&&Re.clientY<=bt.bottom){if(bt.bottom-Re.clientY<=72)return;const ut=64,ge=Re.clientX-bt.left,Je=bt.right-Re.clientX;if(!(ge<=ut||Je<=ut))return}}const ft=Re.currentTarget.getBoundingClientRect().bottom-Re.clientY;if(y&&ft<=y)return;se.current={id:Re.pointerId,x:Re.clientX,y:Re.clientY,dragging:!1,captured:!1,tapIgnored:Ge};const je=B.current?.offsetWidth||360;M.current=Math.min(f,je*p),H.current=0},onPointerMove:Re=>{if(!t||i||se.current.id!==Re.pointerId)return;const Ze=Re.clientX-se.current.x,Ge=Re.clientY-se.current.y;if(!se.current.dragging){if(Math.abs(Ge)>Math.abs(Ze)&&Math.abs(Ge)>8){se.current.id=null;return}if(Math.abs(Ze)<12)return;se.current.dragging=!0,Re.currentTarget.style.touchAction="none",F(0);try{Re.currentTarget.setPointerCapture(Re.pointerId),se.current.captured=!0}catch{se.current.captured=!1}}H.current=Ze,D.current==null&&(D.current=requestAnimationFrame(()=>{D.current=null,Y(H.current)}));const it=M.current,dt=Ze>it?"right":Ze<-it?"left":null;Q(ot=>ot===dt?ot:dt)},onPointerUp:Re=>{if(!t||i||se.current.id!==Re.pointerId)return;const Ze=M.current||Math.min(f,(B.current?.offsetWidth||360)*p),Ge=se.current.dragging,it=se.current.captured,dt=se.current.tapIgnored;if(se.current.id=null,se.current.dragging=!1,se.current.captured=!1,it)try{Re.currentTarget.releasePointerCapture(Re.pointerId)}catch{}if(Re.currentTarget.style.touchAction="pan-y",!Ge){if(dt){F(0),Y(0),Q(null);return}const nt=Date.now(),ft=J.current,gt=ft&&Math.hypot(Re.clientX-ft.x,Re.clientY-ft.y)<=$;if(!!L&&ft&&nt-ft.t<=R&>){if(J.current=null,be(),O.current)return;O.current=!0,requestAnimationFrame(()=>{try{Ce(Re.clientX,Re.clientY)}catch{}}),(async()=>{try{await L?.()}catch{}finally{O.current=!1}})();return}pe(),J.current={t:nt,x:Re.clientX,y:Re.clientY},be(),K.current=window.setTimeout(()=>{K.current=null,J.current=null,n?.()},L?R:0);return}const ot=H.current;D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),ot>Ze?he("right",!0):ot<-Ze?he("left",!0):ee(),H.current=0},onPointerCancel:Re=>{if(!(!t||i)){if(se.current.captured&&se.current.id!=null)try{Re.currentTarget.releasePointerCapture(se.current.id)}catch{}se.current={id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1},D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),H.current=0;try{Re.currentTarget.style.touchAction="pan-y"}catch{}ee()}},children:g.jsxs("div",{className:"relative",children:[g.jsx("div",{className:"relative z-10",children:e}),g.jsx("div",{className:hm("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",ie==="right"&&"bg-emerald-500/20 opacity-100",ie==="left"&&"bg-red-500/20 opacity-100",ie===null&&"opacity-0")})]})})]})});function oM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{fillRule:"evenodd",d:"M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z",clipRule:"evenodd"}))}const lM=w.forwardRef(oM);function uM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.createElement("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"}),w.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 Ac=w.forwardRef(uM);function cM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 VS=w.forwardRef(cM);function dM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 hM=w.forwardRef(dM);function fM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 Cc=w.forwardRef(fM);function mM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 pM=w.forwardRef(mM);function gM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 yM=w.forwardRef(gM);function vM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 xM=w.forwardRef(vM);function bM({title:s,titleId:e,...t},i){return w.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?w.createElement("title",{id:e},s):null,w.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 Sh=w.forwardRef(bM);function Kr({tag:s,children:e,title:t,active:i,onClick:n,maxWidthClassName:r="max-w-[11rem]",className:a,stopPropagation:u=!0}){const c=s??(typeof e=="string"||typeof e=="number"?String(e):""),d=mi("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"),y=mi(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":"",a),v=_=>_.stopPropagation(),b=u?{onPointerDown:v,onMouseDown:v}:{};return n?g.jsx("button",{type:"button",className:y,title:t??c,"aria-pressed":!!i,...b,onClick:_=>{u&&(_.preventDefault(),_.stopPropagation()),c&&n(c)},children:e??s}):g.jsx("span",{className:y,title:t??c,...b,onClick:u?v:void 0,children:e??s})}function gi(...s){return s.filter(Boolean).join(" ")}const TM=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",_M=s=>s.startsWith("HOT ")?s.slice(4):s,SM=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function EM(s){const t=_M(TM(s||"")).replace(/\.[^.]+$/,""),i=t.match(SM);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function Aa({job:s,variant:e="overlay",collapseToMenu:t=!1,inlineCount:i,busy:n=!1,compact:r=!1,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onToggleFavorite:f,onToggleLike:p,onToggleHot:y,onKeep:v,onDelete:b,onToggleWatch:_,onAddToDownloads:E,order:L,className:I}){const R=e==="overlay"?r?"p-1.5":"p-2":"p-1.5",$=r?"size-4":"size-5",P="h-full w-full",B=e==="table"?`inline-flex items-center justify-center rounded-md ${R} 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 ${R} 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`,O=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"},H=L??["watch","favorite","like","hot","keep","delete","details"],D=yt=>H.includes(yt),M=String(s?.sourceUrl??"").trim(),W=EM(s.output||""),K=W?`Mehr zu ${W} anzeigen`:"Mehr anzeigen",J=D("favorite"),ue=D("like"),se=D("hot"),q=D("watch"),Y=D("keep"),ie=D("delete"),Q=D("details")&&!!W,oe=D("add"),[F,ee]=w.useState("idle"),he=w.useRef(null);w.useEffect(()=>()=>{he.current&&window.clearTimeout(he.current)},[]);const be=()=>{ee("ok"),he.current&&window.clearTimeout(he.current),he.current=window.setTimeout(()=>ee("idle"),800)},pe=async()=>{if(n||F==="busy"||!E&&!!!M)return!1;ee("busy");try{let z=!0;return E?z=await E(s)!==!1:M?(window.dispatchEvent(new CustomEvent("downloads:add-url",{detail:{url:M}})),z=!0):z=!1,z?be():ee("idle"),z}catch{return ee("idle"),!1}},[Ce,Re]=w.useState(0),[Ze,Ge]=w.useState(4),it=yt=>z=>{z.preventDefault(),z.stopPropagation(),!(n||!yt)&&Promise.resolve(yt(s)).catch(()=>{})},dt=Q?g.jsxs("button",{type:"button",className:gi(B),title:K,"aria-label":K,disabled:n,onClick:yt=>{yt.preventDefault(),yt.stopPropagation(),!n&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:W}}))},children:[g.jsx("span",{className:gi("inline-flex items-center justify-center",$),children:g.jsx(HS,{className:gi(P,O.off)})}),g.jsx("span",{className:"sr-only",children:K})]}):null,ot=oe?g.jsxs("button",{type:"button",className:gi(B),title:M?"URL zu Downloads hinzufügen":"Keine URL vorhanden","aria-label":"Zu Downloads hinzufügen",disabled:n||F==="busy"||!E&&!M,onClick:async yt=>{yt.preventDefault(),yt.stopPropagation(),await pe()},children:[g.jsx("span",{className:gi("inline-flex items-center justify-center",$),children:F==="ok"?g.jsx(lM,{className:gi(P,"text-emerald-600 dark:text-emerald-300")}):g.jsx(US,{className:gi(P,O.off)})}),g.jsx("span",{className:"sr-only",children:"Zu Downloads"})]}):null,nt=J?g.jsx("button",{type:"button",className:B,title:u?"Favorit entfernen":"Als Favorit markieren","aria-label":u?"Favorit entfernen":"Als Favorit markieren","aria-pressed":u,disabled:n||!f,onClick:it(f),children:g.jsxs("span",{className:gi("relative inline-block",$),children:[g.jsx(Jv,{className:gi("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",P,O.off)}),g.jsx(Sh,{className:gi("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",P,O.favOn)})]})}):null,ft=ue?g.jsx("button",{type:"button",className:B,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||!p,onClick:it(p),children:g.jsxs("span",{className:gi("relative inline-block",$),children:[g.jsx(sp,{className:gi("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",P,O.off)}),g.jsx(Cc,{className:gi("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",P,O.likeOn)})]})}):null,gt=se?g.jsx("button",{type:"button","data-hot-target":!0,className:B,title:a?"HOT entfernen":"Als HOT markieren","aria-label":a?"HOT entfernen":"Als HOT markieren","aria-pressed":a,disabled:n||!y,onClick:it(y),children:g.jsxs("span",{className:gi("relative inline-block",$),children:[g.jsx($S,{className:gi("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",P,O.off)}),g.jsx(VS,{className:gi("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",P,O.hotOn)})]})}):null,je=q?g.jsx("button",{type:"button",className:B,title:d?"Watched entfernen":"Als Watched markieren","aria-label":d?"Watched entfernen":"Als Watched markieren","aria-pressed":d,disabled:n||!_,onClick:it(_),children:g.jsxs("span",{className:gi("relative inline-block",$),children:[g.jsx(Zv,{className:gi("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",P,O.off)}),g.jsx(Ac,{className:gi("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",P,O.watchOn)})]})}):null,bt=Y?g.jsx("button",{type:"button",className:B,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:n||!v,onClick:it(v),children:g.jsx("span",{className:gi("inline-flex items-center justify-center",$),children:g.jsx(Qv,{className:gi(P,O.keep)})})}):null,vt=ie?g.jsx("button",{type:"button",className:B,title:"Löschen","aria-label":"Löschen",disabled:n||!b,onClick:it(b),children:g.jsx("span",{className:gi("inline-flex items-center justify-center",$),children:g.jsx(ex,{className:gi(P,O.del)})})}):null,jt={details:dt,add:ot,favorite:nt,like:ft,watch:je,hot:gt,keep:bt,delete:vt},We=t&&e==="overlay",ut=H.filter(yt=>!!jt[yt]),ge=We&&typeof i!="number",Qe=(r?16:20)+(e==="overlay"?r?6:8:6)*2,mt=r?2:3,ct=w.useMemo(()=>{if(!ge)return i??mt;const yt=Ce||0;if(yt<=0)return Math.min(ut.length,mt);for(let z=ut.length;z>=0;z--)if(z*Qe+Qe+(z>0?z*Ze:0)<=yt)return z;return 0},[ge,i,mt,Ce,ut.length,Qe,Ze]),et=We?ut.slice(0,ct):ut,Gt=We?ut.slice(ct):[],[Jt,It]=w.useState(!1),Ft=w.useRef(null);w.useLayoutEffect(()=>{const yt=Ft.current;if(!yt||typeof window>"u")return;const z=()=>{const te=Ft.current;if(!te)return;const _e=Math.floor(te.getBoundingClientRect().width||0);_e>0&&Re(_e);const Oe=window.getComputedStyle(te),tt=Oe.columnGap||Oe.gap||"0",Ot=parseFloat(tt);Number.isFinite(Ot)&&Ot>=0&&Ge(Ot)};z();const V=new ResizeObserver(()=>z());return V.observe(yt),window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),V.disconnect()}},[]);const $t=w.useRef(null),Ke=w.useRef(null),Lt=208,Qt=4,Ut=8,[ci,vi]=w.useState(null);w.useEffect(()=>{if(!Jt)return;const yt=V=>{V.key==="Escape"&&It(!1)},z=V=>{const te=Ft.current,_e=Ke.current,Oe=V.target;te&&te.contains(Oe)||_e&&_e.contains(Oe)||It(!1)};return window.addEventListener("keydown",yt),window.addEventListener("mousedown",z),()=>{window.removeEventListener("keydown",yt),window.removeEventListener("mousedown",z)}},[Jt]),w.useLayoutEffect(()=>{if(!Jt){vi(null);return}const yt=()=>{const z=$t.current;if(!z)return;const V=z.getBoundingClientRect(),te=window.innerWidth,_e=window.innerHeight;let Oe=V.right-Lt;Oe=Math.max(Ut,Math.min(Oe,te-Lt-Ut));let tt=V.bottom+Qt;tt=Math.max(Ut,Math.min(tt,_e-Ut));const Ot=Math.max(120,_e-tt-Ut);vi({top:tt,left:Oe,maxH:Ot})};return yt(),window.addEventListener("resize",yt),window.addEventListener("scroll",yt,!0),()=>{window.removeEventListener("resize",yt),window.removeEventListener("scroll",yt,!0)}},[Jt]);const ei=()=>{W&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:W}}))},Bi=yt=>yt==="details"?g.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:z=>{z.preventDefault(),z.stopPropagation(),It(!1),ei()},children:[g.jsx(HS,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:"Details"})]},"details"):yt==="add"?g.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||!E&&!M,onClick:async z=>{z.preventDefault(),z.stopPropagation(),It(!1),await pe()},children:[g.jsx(US,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:"Zu Downloads"})]},"add"):yt==="favorite"?g.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||!f,onClick:async z=>{z.preventDefault(),z.stopPropagation(),It(!1),await f?.(s)},children:[u?g.jsx(Sh,{className:gi("size-4",O.favOn)}):g.jsx(Jv,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:u?"Favorit entfernen":"Als Favorit markieren"})]},"favorite"):yt==="like"?g.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||!p,onClick:async z=>{z.preventDefault(),z.stopPropagation(),It(!1),await p?.(s)},children:[c?g.jsx(Cc,{className:gi("size-4",O.favOn)}):g.jsx(sp,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:c?"Gefällt mir entfernen":"Gefällt mir"})]},"like"):yt==="watch"?g.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:async z=>{z.preventDefault(),z.stopPropagation(),It(!1),await _?.(s)},children:[d?g.jsx(Ac,{className:gi("size-4",O.favOn)}):g.jsx(Zv,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:d?"Watched entfernen":"Watched"})]},"watch"):yt==="hot"?g.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||!y,onClick:async z=>{z.preventDefault(),z.stopPropagation(),It(!1),await y?.(s)},children:[a?g.jsx(VS,{className:gi("size-4",O.favOn)}):g.jsx($S,{className:gi("size-4",O.off)}),g.jsx("span",{className:"truncate",children:a?"HOT entfernen":"Als HOT markieren"})]},"hot"):yt==="keep"?g.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 z=>{z.preventDefault(),z.stopPropagation(),It(!1),await v?.(s)},children:[g.jsx(Qv,{className:gi("size-4",O.keep)}),g.jsx("span",{className:"truncate",children:"Behalten"})]},"keep"):yt==="delete"?g.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 z=>{z.preventDefault(),z.stopPropagation(),It(!1),await b?.(s)},children:[g.jsx(ex,{className:gi("size-4",O.del)}),g.jsx("span",{className:"truncate",children:"Löschen"})]},"delete"):null;return g.jsxs("div",{ref:Ft,className:gi("relative flex items-center flex-nowrap",I??"gap-2"),children:[et.map(yt=>{const z=jt[yt];return z?g.jsx(w.Fragment,{children:z},yt):null}),We&&Gt.length>0?g.jsxs("div",{className:"relative",children:[g.jsx("button",{ref:$t,type:"button",className:B,"aria-label":"Mehr",title:"Mehr","aria-haspopup":"menu","aria-expanded":Jt,disabled:n,onClick:yt=>{yt.preventDefault(),yt.stopPropagation(),!n&&It(z=>!z)},children:g.jsx("span",{className:gi("inline-flex items-center justify-center",$),children:g.jsx(CO,{className:gi(P,O.off)})})}),Jt&&ci&&typeof document<"u"?Ec.createPortal(g.jsx("div",{ref:Ke,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:ci.top,left:ci.left,width:Lt,maxHeight:ci.maxH},onClick:yt=>yt.stopPropagation(),children:Gt.map(Bi)}),document.body):null]}):null]})}const MA=/^HOT[ \u00A0]+/i,PA=s=>String(s||"").replaceAll(" "," "),rc=s=>MA.test(PA(s)),uo=s=>PA(s).replace(MA,"");function wM(...s){return s.filter(Boolean).join(" ")}const AM=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n};function CM({rows:s,isSmall:e,teaserPlayback:t,teaserAudio:i,hoverTeaserKey:n,blurPreviews:r,teaserKey:a,inlinePlay:u,setInlinePlay:c,deletingKeys:d,keepingKeys:f,removingKeys:p,swipeRefs:y,assetNonce:v,keyFor:b,baseName:_,modelNameFromOutput:E,runtimeOf:L,sizeBytesOf:I,formatBytes:R,lower:$,onHoverPreviewKeyChange:P,onOpenPlayer:B,openPlayer:O,startInline:H,tryAutoplayInline:D,registerTeaserHost:M,deleteVideo:W,keepVideo:K,releasePlayingFile:J,modelsByKey:ue,activeTagSet:se,onToggleTagFilter:q,onToggleHot:Y,onToggleFavorite:ie,onToggleLike:Q,onToggleWatch:oe}){const[F,ee]=w.useState(null),he=w.useRef(null);return w.useEffect(()=>{if(!F)return;const be=Ce=>{Ce.key==="Escape"&&ee(null)},pe=Ce=>{const Re=he.current;Re&&(Re.contains(Ce.target)||ee(null))};return document.addEventListener("keydown",be),document.addEventListener("pointerdown",pe),()=>{document.removeEventListener("keydown",be),document.removeEventListener("pointerdown",pe)}},[F]),w.useEffect(()=>{if(!F)return;s.some(pe=>b(pe)===F)||ee(null)},[s,b,F]),g.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:s.map(be=>{const pe=b(be),Ce=u?.key===pe,Ze=!(!!i&&(Ce||n===pe)),Ge=Ce?u?.nonce??0:0,it=d.has(pe)||f.has(pe)||p.has(pe),dt=E(be.output),ot=_(be.output||""),nt=rc(ot),ft=ue[$(dt)],gt=!!ft?.favorite,je=ft?.liked===!0,bt=!!ft?.watching,vt=AM(ft?.tags),jt=vt.slice(0,6),We=vt.length-jt.length,ut=vt.join(", "),ge=be.status==="failed"?"bg-red-500/35":be.status==="finished"?"bg-emerald-500/35":be.status==="stopped"?"bg-amber-500/35":"bg-black/40",Je=L(be),Ye=R(I(be)),Qe=`inline-prev-${encodeURIComponent(pe)}`,mt=e?"":"transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none",ct=g.jsx("div",{role:"button",tabIndex:0,className:["group","content-visibility-auto","[contain-intrinsic-size:180px_120px]",mt,"rounded-xl","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",it&&"pointer-events-none",d.has(pe)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30 animate-pulse",f.has(pe)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30 animate-pulse",p.has(pe)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),onClick:e?void 0:()=>O(be),onKeyDown:et=>{(et.key==="Enter"||et.key===" ")&&B(be)},children:g.jsxs(Ca,{noBodyPadding:!0,className:"overflow-hidden",children:[g.jsxs("div",{id:Qe,ref:M(pe),className:"relative aspect-video bg-black/5 dark:bg-white/5",onMouseEnter:e?void 0:()=>P?.(pe),onMouseLeave:e?void 0:()=>P?.(null),onClick:et=>{et.preventDefault(),et.stopPropagation(),!e&&H(pe)},children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(tb,{job:be,getFileName:_,className:"w-full h-full",showPopover:!1,blur:e||Ce?!1:r,animated:t==="all"?!0:t==="hover"?a===pe:!1,animatedMode:"teaser",animatedTrigger:"always",inlineVideo:Ce?"always":!1,inlineNonce:Ge,inlineControls:Ce,inlineLoop:!1,muted:Ze,popoverMuted:Ze,assetNonce:v??0})}),g.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",Ce?"opacity-0":"opacity-100"].join(" ")}),g.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white","transition-opacity duration-150",Ce?"opacity-0":"opacity-100"].join(" "),children:g.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] opacity-90",children:[g.jsx("span",{className:wM("rounded px-1.5 py-0.5 font-semibold",ge),children:be.status}),g.jsxs("div",{className:"flex items-center gap-1.5",children:[g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Je}),g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Ye})]})]})}),!e&&u?.key===pe&&g.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:et=>{et.preventDefault(),et.stopPropagation(),c(Gt=>({key:pe,nonce:Gt?.key===pe?Gt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}),g.jsx("div",{className:"absolute right-2 top-2 flex items-center gap-2",onClick:et=>et.stopPropagation(),onMouseDown:et=>et.stopPropagation(),children:g.jsx(Aa,{job:be,variant:"overlay",busy:it,isHot:nt,isFavorite:gt,isLiked:je,isWatching:bt,onToggleWatch:oe,onToggleFavorite:ie,onToggleLike:Q,onToggleHot:Y?async et=>{const Gt=_(et.output||"");Gt&&(await J(Gt,{close:!0}),await new Promise(Jt=>setTimeout(Jt,150))),await Y(et)}:void 0,onKeep:K,onDelete:W,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"flex items-center gap-2"})})]}),g.jsxs("div",{className:["px-4 py-3 rounded-b-lg border-t border-gray-200/60 dark:border-white/10",e?"bg-white/90 dark:bg-gray-950/80":"bg-white/60 backdrop-blur dark:bg-white/5"].join(" "),children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:dt}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[bt?g.jsx(Ac,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,je?g.jsx(Cc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,gt?g.jsx(Sh,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsx("span",{className:"truncate",children:uo(ot)||"—"}),nt?g.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]}),g.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:et=>et.stopPropagation(),onMouseDown:et=>et.stopPropagation(),children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:jt.length>0?jt.map(et=>g.jsx(Kr,{tag:et,active:se.has($(et)),onClick:q},et)):g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),We>0?g.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:ut,"aria-haspopup":"dialog","aria-expanded":F===pe,onPointerDown:et=>et.stopPropagation(),onClick:et=>{et.preventDefault(),et.stopPropagation(),ee(Gt=>Gt===pe?null:pe)},children:["+",We]}):null,F===pe?g.jsxs("div",{ref:he,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",e?"":"backdrop-blur","dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10"].join(" "),onClick:et=>et.stopPropagation(),onMouseDown:et=>et.stopPropagation(),children:[g.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:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),g.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:()=>ee(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),g.jsx("div",{className:"max-h-48 overflow-auto p-2",children:g.jsx("div",{className:"flex flex-wrap gap-1.5",children:vt.map(et=>g.jsx(Kr,{tag:et,active:se.has($(et)),onClick:q},et))})})]}):null]})]})]})});return e?g.jsx(aM,{ref:et=>{et?y.current.set(pe,et):y.current.delete(pe)},enabled:!0,disabled:it,ignoreFromBottomPx:110,doubleTapMs:360,doubleTapMaxMovePx:48,onTap:()=>{const et=`inline-prev-${encodeURIComponent(pe)}`;H(pe),requestAnimationFrame(()=>{D(et)||requestAnimationFrame(()=>D(et))})},onDoubleTap:Y?async()=>{if(nt)return!1;try{const et=_(be.output||"");return et&&(u?.key===pe||(await J(et,{close:!0}),await new Promise(Jt=>setTimeout(Jt,150)))),await Y(be),!0}catch{return!1}}:void 0,onSwipeLeft:()=>W(be),onSwipeRight:()=>K(be),children:ct},pe):g.jsx(w.Fragment,{children:ct},pe)})})}function kM({rows:s,columns:e,getRowKey:t,sort:i,onSortChange:n,onRowClick:r,rowClassName:a}){return g.jsx(fh,{rows:s,columns:e,getRowKey:t,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,sort:i,onSortChange:n,onRowClick:r,rowClassName:a})}function DM({rows:s,blurPreviews:e,durations:t,teaserPlayback:i,teaserAudio:n,hoverTeaserKey:r,teaserKey:a,handleDuration:u,keyFor:c,baseName:d,modelNameFromOutput:f,runtimeOf:p,sizeBytesOf:y,formatBytes:v,deletingKeys:b,keepingKeys:_,removingKeys:E,deletedKeys:L,registerTeaserHost:I,onHoverPreviewKeyChange:R,onOpenPlayer:$,deleteVideo:P,keepVideo:B,onToggleHot:O,lower:H,modelsByKey:D,activeTagSet:M,onToggleTagFilter:W,onToggleFavorite:K,onToggleLike:J,onToggleWatch:ue}){const[se,q]=w.useState(null),Y=w.useRef(null),ie=i==="hover"||i==="all",Q=w.useCallback(F=>ee=>{if(!ie){I(F)(null);return}I(F)(ee)},[I,ie]);w.useEffect(()=>{if(!se)return;const F=he=>{he.key==="Escape"&&q(null)},ee=he=>{const be=Y.current;be&&(be.contains(he.target)||q(null))};return document.addEventListener("keydown",F),document.addEventListener("pointerdown",ee),()=>{document.removeEventListener("keydown",F),document.removeEventListener("pointerdown",ee)}},[se]),w.useEffect(()=>{if(!se)return;s.some(ee=>c(ee)===se)||q(null)},[s,c,se]);const oe=F=>{const ee=String(F??"").trim();if(!ee)return[];const he=ee.split(/[\n,;|]+/g).map(Ce=>Ce.trim()).filter(Boolean),be=new Set,pe=[];for(const Ce of he){const Re=Ce.toLowerCase();be.has(Re)||(be.add(Re),pe.push(Ce))}return pe};return g.jsx(g.Fragment,{children:g.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:s.map(F=>{const ee=c(F),be=!(!!n&&r===ee),pe=f(F.output),Ce=H(pe),Re=D[Ce],Ze=!!Re?.favorite,Ge=Re?.liked===!0,it=!!Re?.watching,dt=oe(Re?.tags),ot=dt.slice(0,6),nt=dt.length-ot.length,ft=dt.join(", "),gt=d(F.output||""),je=rc(gt),bt=uo(gt),vt=p(F),jt=v(y(F)),We=b.has(ee)||_.has(ee)||E.has(ee),ut=L.has(ee);return g.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",We&&"pointer-events-none opacity-70",b.has(ee)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",E.has(ee)&&"opacity-0 translate-y-2 scale-[0.98]",ut&&"hidden"].filter(Boolean).join(" "),onClick:()=>$(F),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&$(F)},children:[g.jsxs("div",{className:"group relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",ref:Q(ee),onMouseEnter:()=>R?.(ee),onMouseLeave:()=>R?.(null),children:[g.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-t-lg",children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(tb,{job:F,getFileName:ge=>uo(d(ge)),durationSeconds:t[ee]??F?.durationSeconds,onDuration:u,variant:"fill",showPopover:!1,blur:e,animated:i==="all"?!0:i==="hover"?a===ee:!1,animatedMode:"teaser",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,muted:be,popoverMuted:be})}),g.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 - `}),g.jsx("div",{className:` - pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white - `,children:g.jsxs("div",{className:"flex items-end justify-between gap-2",children:[g.jsx("div",{className:"min-w-0",children:g.jsx("div",{children:g.jsx("span",{className:["inline-block rounded px-1.5 py-0.5 text-[11px] font-semibold",F.status==="finished"?"bg-emerald-600/70":F.status==="stopped"?"bg-amber-600/70":F.status==="failed"?"bg-red-600/70":"bg-black/50"].join(" "),children:F.status})})}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:vt}),g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:jt})]})]})})]}),g.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:ge=>ge.stopPropagation(),children:g.jsx(Aa,{job:F,variant:"overlay",busy:We,collapseToMenu:!0,isHot:je,isFavorite:Ze,isLiked:Ge,isWatching:it,onToggleWatch:ue,onToggleFavorite:K,onToggleLike:J,onToggleHot:O,onKeep:B,onDelete:P,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"w-full justify-end gap-1"})})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:pe}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[it?g.jsx(Ac,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,Ge?g.jsx(Cc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Ze?g.jsx(Sh,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsx("span",{className:"truncate",children:uo(bt)||"—"}),je?g.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]}),g.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:ot.length>0?ot.map(ge=>g.jsx(Kr,{tag:ge,active:M.has(H(ge)),onClick:W},ge)):g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),nt>0?g.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:ft,"aria-haspopup":"dialog","aria-expanded":se===ee,onPointerDown:ge=>ge.stopPropagation(),onClick:ge=>{ge.preventDefault(),ge.stopPropagation(),q(Je=>Je===ee?null:ee)},children:["+",nt]}):null,se===ee?g.jsxs("div",{ref:Y,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:ge=>ge.stopPropagation(),onMouseDown:ge=>ge.stopPropagation(),children:[g.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:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),g.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:()=>q(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),g.jsx("div",{className:"max-h-48 overflow-auto p-2",children:g.jsx("div",{className:"flex flex-wrap gap-1.5",children:dt.map(ge=>g.jsx(Kr,{tag:ge,active:M.has(H(ge)),onClick:W},ge))})})]}):null]})]})]},ee)})})})}function zS(s,e,t){return Math.max(e,Math.min(t,s))}function _y(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function LM(s,e,t,i){if(s<=1)return[1];const n=1,r=s,a=_y(n,Math.min(t,r)),u=_y(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(...a),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const p=new Set;return f.filter(y=>{const v=String(y);return p.has(v)?!1:(p.add(v),!0)})}function RM({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const a=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return g.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:mi("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",a,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 BA({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:a=!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))),y=zS(s||1,1,p);if(p<=1)return null;const v=t===0?0:(y-1)*e+1,b=Math.min(y*e,t),_=LM(p,y,r,n),E=L=>i(zS(L,1,p));return g.jsxs("div",{className:mi("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:[g.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[g.jsx("button",{type:"button",onClick:()=>E(y-1),disabled:y<=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}),g.jsx("button",{type:"button",onClick:()=>E(y+1),disabled:y>=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})]}),g.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[g.jsx("div",{children:a?g.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",g.jsx("span",{className:"font-medium",children:v})," to"," ",g.jsx("span",{className:"font-medium",children:b})," of"," ",g.jsx("span",{className:"font-medium",children:t})," results"]}):null}),g.jsx("div",{children:g.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[g.jsxs("button",{type:"button",onClick:()=>E(y-1),disabled:y<=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:[g.jsx("span",{className:"sr-only",children:d}),g.jsx(rO,{"aria-hidden":"true",className:"size-5"})]}),_.map((L,I)=>L==="ellipsis"?g.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}`):g.jsx(RM,{active:L===y,onClick:()=>E(L),rounded:"none",children:L},L)),g.jsxs("button",{type:"button",onClick:()=>E(y+1),disabled:y>=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:[g.jsx("span",{className:"sr-only",children:f}),g.jsx(oO,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}const FA=w.createContext(null);function IM(s){switch(s){case"success":return{Icon:wO,cls:"text-emerald-500"};case"error":return{Icon:nM,cls:"text-rose-500"};case"warning":return{Icon:DO,cls:"text-amber-500"};default:return{Icon:PO,cls:"text-sky-500"}}}function NM(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 MM(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function PM({children:s,maxToasts:e=3,defaultDurationMs:t=3500,position:i="bottom-right"}){const[n,r]=w.useState([]),a=w.useCallback(v=>{r(b=>b.filter(_=>_.id!==v))},[]),u=w.useCallback(()=>r([]),[]),c=w.useCallback(v=>{const b=MM(),_=v.durationMs??t;return r(E=>[{...v,id:b,durationMs:_},...E].slice(0,Math.max(1,e))),_&&_>0&&window.setTimeout(()=>a(b),_),b},[t,e,a]),d=w.useMemo(()=>({push:c,remove:a,clear:u}),[c,a,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",y=i.startsWith("top")?"top-0 bottom-auto":"bottom-0 top-auto";return g.jsxs(FA.Provider,{value:d,children:[s,g.jsx("div",{"aria-live":"assertive",className:["pointer-events-none fixed z-[80] inset-x-0",y].join(" "),children:g.jsx("div",{className:["flex w-full px-4 py-6 sm:p-6",f].join(" "),children:g.jsx("div",{className:["flex w-full flex-col space-y-3",p].join(" "),children:n.map(v=>{const{Icon:b,cls:_}=IM(v.type),E=(v.title||"").trim()||OM(v.type),L=(v.message||"").trim();return g.jsx(hh,{appear:!0,show:!0,children:g.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",NM(v.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:g.jsx("div",{className:"p-4",children:g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsx("div",{className:"shrink-0",children:g.jsx(b,{className:["size-6",_].join(" "),"aria-hidden":"true"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:E}),L?g.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300 break-words",children:L}):null]}),g.jsxs("button",{type:"button",onClick:()=>a(v.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:[g.jsx("span",{className:"sr-only",children:"Close"}),g.jsx(uO,{"aria-hidden":"true",className:"size-5"})]})]})})})},v.id)})})})})]})}function BM(){const s=w.useContext(FA);if(!s)throw new Error("useToast must be used within ");return s}function UA(){const{push:s,remove:e,clear:t}=BM(),i=n=>(r,a,u)=>s({type:n,title:r,message:a,...u});return{push:s,remove:e,clear:t,success:i("success"),error:i("error"),info:i("info"),warning:i("warning")}}const sb=s=>(s||"").replaceAll("\\","/"),bn=s=>{const t=sb(s).split("/");return t[t.length-1]||""},qn=s=>bn(s.output||"")||s.id,FM=s=>{const e=sb(String(s??""));return e.includes("/.trash/")||e.endsWith("/.trash")};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 Sy(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 KS(s){const[e,t]=w.useState(!1);return w.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 UM=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},Qo=s=>{const e=bn(s||""),t=uo(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},An=s=>(s||"").trim().toLowerCase(),WS=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n},fm=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 jM({jobs:s,doneJobs:e,blurPreviews:t,teaserPlayback:i,teaserAudio:n,onOpenPlayer:r,onDeleteJob:a,onToggleHot:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,doneTotal:p,page:y,pageSize:v,onPageChange:b,assetNonce:_,sortMode:E,onSortModeChange:L,modelsByKey:I}){const R=i??"hover",$=KS("(hover: hover) and (pointer: fine)"),P=UA(),B=w.useRef(new Map),[O,H]=w.useState(null),[D,M]=w.useState(null),W=w.useRef(null),K=w.useRef(new WeakMap),[J,ue]=w.useState(()=>new Set),[se,q]=w.useState(()=>new Set),[Y,ie]=w.useState(null),[Q,oe]=w.useState(!1),[F,ee]=w.useState({}),[he,be]=w.useState(null),[pe,Ce]=w.useState(null),[Re,Ze]=w.useState(0),Ge=w.useRef(null),it=w.useCallback(()=>{Ge.current&&window.clearTimeout(Ge.current),Ge.current=window.setTimeout(()=>Ze(ye=>ye+1),80)},[]),[dt,ot]=w.useState(null),nt="finishedDownloads_view",ft="finishedDownloads_includeKeep_v2",gt="finishedDownloads_mobileOptionsOpen_v1",[je,bt]=w.useState("table"),[vt,jt]=w.useState(!1),[We,ut]=w.useState(!1),ge=w.useRef(new Map),Je=w.useCallback(async()=>{if(!Y||Q)return;oe(!0);const ye=X=>{ue(ae=>{const re=new Set(ae);return re.delete(X),re}),q(ae=>{const re=new Set(ae);return re.delete(X),re}),Vi(ae=>{const re=new Set(ae);return re.delete(X),re}),Ai(ae=>{const re=new Set(ae);return re.delete(X),re})};try{if(Y.kind==="delete"){const X=await fetch(`/api/record/restore?token=${encodeURIComponent(Y.undoToken)}`,{method:"POST"});if(!X.ok){const xe=await X.text().catch(()=>"");throw new Error(xe||`HTTP ${X.status}`)}const ae=await X.json().catch(()=>null),re=String(ae?.restoredFile||Y.originalFile);ye(Y.originalFile),ye(re),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),it(),ie(null);return}if(Y.kind==="keep"){const X=await fetch(`/api/record/unkeep?file=${encodeURIComponent(Y.keptFile)}`,{method:"POST"});if(!X.ok){const xe=await X.text().catch(()=>"");throw new Error(xe||`HTTP ${X.status}`)}const ae=await X.json().catch(()=>null),re=String(ae?.newFile||Y.originalFile);ye(Y.originalFile),ye(re),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),it(),ie(null);return}if(Y.kind==="hot"){const X=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(Y.currentFile)}`,{method:"POST"});if(!X.ok){const we=await X.text().catch(()=>"");throw new Error(we||`HTTP ${X.status}`)}const ae=await X.json().catch(()=>null),re=String(ae?.oldFile||Y.currentFile),xe=String(ae?.newFile||"");xe&&ti(re,xe),it(),ie(null);return}}catch(X){P.error("Undo fehlgeschlagen",String(X?.message||X))}finally{oe(!1)}},[Y,Q,P,it]),[Ye,Qe]=w.useState([]),mt=w.useMemo(()=>new Set(Ye.map(An)),[Ye]),ct=w.useMemo(()=>{const ye={},X={};for(const[ae,re]of Object.entries(I??{})){const xe=An(ae),we=WS(re?.tags);ye[xe]=we,X[xe]=new Set(we.map(An))}return{tagsByModelKey:ye,tagSetByModelKey:X}},[I]),[et,Gt]=w.useState(""),Jt=w.useDeferredValue(et),It=w.useMemo(()=>An(Jt).split(/\s+/g).map(ye=>ye.trim()).filter(Boolean),[Jt]),Ft=w.useCallback(()=>Gt(""),[]),$t=w.useCallback(ye=>{const X=An(ye);Qe(ae=>ae.some(xe=>An(xe)===X)?ae.filter(xe=>An(xe)!==X):[...ae,ye])},[]),Ke=It.length>0||mt.size>0,Lt=w.useCallback(async ye=>{const X=await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(E)}&withCount=1${vt?"&includeKeep=1":""}`,{cache:"no-store",signal:ye});if(!X.ok)return;const ae=await X.json().catch(()=>null),re=Array.isArray(ae?.items)?ae.items:[],xe=Number(ae?.count??ae?.totalCount??re.length);be(re),Ce(Number.isFinite(xe)?xe:re.length)},[E,vt]),Qt=w.useCallback(()=>Qe([]),[]);w.useEffect(()=>{try{const ye=localStorage.getItem("finishedDownloads_pendingTags");if(!ye)return;const X=JSON.parse(ye),ae=Array.isArray(X)?X.map(re=>String(re||"").trim()).filter(Boolean):[];if(ae.length===0)return;Ec.flushSync(()=>Qe(ae)),y!==1&&b(1)}catch{}finally{try{localStorage.removeItem("finishedDownloads_pendingTags")}catch{}}},[]),w.useEffect(()=>{if(!Ke)return;const ye=new AbortController,X=window.setTimeout(()=>{Lt(ye.signal).catch(()=>{})},250);return()=>{window.clearTimeout(X),ye.abort()}},[Ke,Lt]),w.useEffect(()=>{if(Re===0)return;if(Ke){const X=new AbortController;return(async()=>{try{await Lt(X.signal)}catch{}})(),()=>X.abort()}const ye=new AbortController;return(async()=>{try{const X=await fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(E)}&withCount=1${vt?"&includeKeep=1":""}`,{cache:"no-store",signal:ye.signal});if(X.ok){const ae=await X.json().catch(()=>null),re=Array.isArray(ae?.items)?ae.items:[],xe=Number(ae?.count??ae?.totalCount??re.length);if(be(re),Number.isFinite(xe)&&xe>=0){Ce(xe);const we=Math.max(1,Math.ceil(xe/v));if(y>we){b(we),be(null);return}}}}catch{}})(),()=>ye.abort()},[Re,y,v,b,E,Ke,Lt,vt]),w.useEffect(()=>{Ke||(be(null),Ce(null))},[y,v,E,vt,Ke]),w.useEffect(()=>{if(!vt){Ke||(be(null),Ce(null));return}if(Ke)return;const ye=new AbortController;return(async()=>{try{const X=await fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(E)}&withCount=1&includeKeep=1`,{cache:"no-store",signal:ye.signal});if(!X.ok)return;const ae=await X.json().catch(()=>null),re=Array.isArray(ae?.items)?ae.items:[],xe=Number(ae?.count??ae?.totalCount??re.length);be(re),Ce(Number.isFinite(xe)?xe:re.length)}catch{}})(),()=>ye.abort()},[vt,Ke,y,v,E]),w.useEffect(()=>{try{const ye=localStorage.getItem(nt);bt(ye==="table"||ye==="cards"||ye==="gallery"?ye:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{bt("table")}},[]),w.useEffect(()=>{try{localStorage.setItem(nt,je)}catch{}},[je]),w.useEffect(()=>{try{const ye=localStorage.getItem(ft);jt(ye==="1"||ye==="true"||ye==="yes")}catch{jt(!1)}},[]),w.useEffect(()=>{try{localStorage.setItem(ft,vt?"1":"0")}catch{}},[vt]),w.useEffect(()=>{try{const ye=localStorage.getItem(gt);ut(ye==="1"||ye==="true"||ye==="yes")}catch{ut(!1)}},[]),w.useEffect(()=>{try{localStorage.setItem(gt,We?"1":"0")}catch{}},[We]);const[Ut,ci]=w.useState({}),vi=w.useRef({}),ei=w.useRef(null);w.useEffect(()=>{vi.current=Ut},[Ut]);const Bi=w.useCallback(()=>{ei.current==null&&(ei.current=window.setTimeout(()=>{ei.current=null,ci({...vi.current})},200))},[]);w.useEffect(()=>()=>{ei.current!=null&&(window.clearTimeout(ei.current),ei.current=null)},[]);const[yt,z]=w.useState(null),V=!n,te=w.useCallback(ye=>{const ae=document.getElementById(ye)?.querySelector("video");if(!ae)return!1;ip(ae,{muted:V});const re=ae.play?.();return re&&typeof re.catch=="function"&&re.catch(()=>{}),!0},[V]),_e=w.useCallback(ye=>{z(X=>X?.key===ye?{key:ye,nonce:X.nonce+1}:{key:ye,nonce:1})},[]),Oe=w.useCallback(ye=>{z(null),r(ye)},[r]),tt=w.useCallback((ye,X)=>{q(ae=>{const re=new Set(ae);return X?re.add(ye):re.delete(ye),re})},[]),Ot=w.useCallback(ye=>{ue(X=>{const ae=new Set(X);return ae.add(ye),ae})},[]),[xi,Vi]=w.useState(()=>new Set),zi=w.useCallback((ye,X)=>{Vi(ae=>{const re=new Set(ae);return X?re.add(ye):re.delete(ye),re})},[]),[Oi,Ai]=w.useState(()=>new Set),Ci=w.useCallback((ye,X)=>{Ai(ae=>{const re=new Set(ae);return X?re.add(ye):re.delete(ye),re})},[]),Fi=w.useCallback(ye=>{Ci(ye,!0),window.setTimeout(()=>{Ot(ye),Ci(ye,!1),it()},320)},[Ot,Ci,it]),Mi=w.useCallback(async(ye,X)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:ye}})),X?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:ye}})),await new Promise(ae=>window.setTimeout(ae,250))},[]),Li=w.useCallback(async ye=>{const X=bn(ye.output||""),ae=qn(ye);if(!X)return P.error("Löschen nicht möglich","Kein Dateiname gefunden – kann nicht löschen."),!1;if(se.has(ae))return!1;tt(ae,!0);try{if(await Mi(X,{close:!0}),a){const st=(await a(ye))?.undoToken;return ie(typeof st=="string"&&st?{kind:"delete",undoToken:st,originalFile:X}:null),Fi(ae),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}const re=await fetch(`/api/record/delete?file=${encodeURIComponent(X)}`,{method:"POST"});if(!re.ok){const He=await re.text().catch(()=>"");throw new Error(He||`HTTP ${re.status}`)}const xe=await re.json().catch(()=>null),we=typeof xe?.undoToken=="string"?xe.undoToken:"";return ie(we?{kind:"delete",undoToken:we,originalFile:X}:null),Fi(ae),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(re){return P.error("Löschen fehlgeschlagen",String(re?.message||re)),!1}finally{tt(ae,!1)}},[se,tt,Mi,a,Fi,P,ie]),oi=w.useCallback(async ye=>{const X=bn(ye.output||""),ae=qn(ye);if(!X)return P.error("Keep nicht möglich","Kein Dateiname gefunden – kann nicht behalten."),!1;if(xi.has(ae)||se.has(ae))return!1;zi(ae,!0);try{await Mi(X,{close:!0});const re=await fetch(`/api/record/keep?file=${encodeURIComponent(X)}`,{method:"POST"});if(!re.ok){const He=await re.text().catch(()=>"");throw new Error(He||`HTTP ${re.status}`)}const xe=await re.json().catch(()=>null),we=typeof xe?.newFile=="string"&&xe.newFile?xe.newFile:X;return ie({kind:"keep",keptFile:we,originalFile:X}),Fi(ae),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(re){return P.error("Keep fehlgeschlagen",String(re?.message||re)),!1}finally{zi(ae,!1)}},[xi,se,zi,Mi,Fi,P,ie]),ti=w.useCallback((ye,X)=>{if(!ye||!X||ye===X)return;ee(xe=>{const we={...xe};for(const[He,st]of Object.entries(we))(He===ye||He===X||st===ye||st===X)&&delete we[He];return we[ye]=X,we}),z(xe=>xe?.key===ye?{...xe,key:X}:xe),H(xe=>xe===ye?X:xe),M(xe=>xe===ye?X:xe);const ae=vi.current||{},re=ae[ye];if(typeof re=="number"){const xe={...ae};delete xe[ye],xe[X]=re,vi.current=xe,ci(xe)}else if(ye in ae){const xe={...ae};delete xe[ye],vi.current=xe,ci(xe)}},[]),Kt=w.useCallback(async ye=>{const X=bn(ye.output||"");if(!X){P.error("HOT nicht möglich","Kein Dateiname gefunden – kann nicht HOT togglen.");return}const ae=He=>rc(He)?uo(He):`HOT ${He}`,re=(He,st)=>{!He||!st||He===st||ti(He,st)},xe=X,we=ae(xe);ti(xe,we);try{if(await Mi(xe,{close:!0}),u){const Tt=await u(ye),Bt=typeof Tt?.oldFile=="string"?Tt.oldFile:"",lt=typeof Tt?.newFile=="string"?Tt.newFile:"";Bt&<&&re(Bt,lt),ie({kind:"hot",currentFile:lt||we}),it();return}const He=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(xe)}`,{method:"POST"});if(!He.ok){const Tt=await He.text().catch(()=>"");throw new Error(Tt||`HTTP ${He.status}`)}const st=await He.json().catch(()=>null),Xe=typeof st?.oldFile=="string"&&st.oldFile?st.oldFile:xe,kt=typeof st?.newFile=="string"&&st.newFile?st.newFile:we;Xe!==kt&&re(Xe,kt),ie({kind:"hot",currentFile:kt}),it()}catch(He){ti(we,xe),ie(null),P.error("HOT umbenennen fehlgeschlagen",String(He?.message||He))}},[bn,P,ti,Mi,u,it,ie]),Gs=w.useCallback(ye=>{const X=ye?.durationSeconds;if(typeof X=="number"&&Number.isFinite(X)&&X>0)return X;const ae=Date.parse(String(ye?.startedAt||"")),re=Date.parse(String(ye?.endedAt||""));if(Number.isFinite(ae)&&Number.isFinite(re)&&re>ae){const xe=(re-ae)/1e3;if(xe>=1&&xe<=1440*60)return xe}return Number.POSITIVE_INFINITY},[]),qi=w.useCallback(ye=>{const X=sb(ye.output||""),ae=bn(X),re=F[ae];if(!re)return ye;const xe=X.lastIndexOf("/"),we=xe>=0?X.slice(0,xe+1):"";return{...ye,output:we+re}},[F,bn]),fn=he??e,tr=pe??p,bi=w.useMemo(()=>{const ye=new Map;for(const ae of fn){const re=qi(ae);ye.set(qn(re),re)}for(const ae of s){const re=qi(ae),xe=qn(re);ye.has(xe)&&ye.set(xe,{...ye.get(xe),...re})}return Array.from(ye.values()).filter(ae=>J.has(qn(ae))||FM(ae.output)?!1:ae.status==="finished"||ae.status==="failed"||ae.status==="stopped")},[s,fn,J,qi]);w.useEffect(()=>{const ye=X=>{const ae=X.detail;if(!ae?.file)return;const re=ae.file;ae.phase==="start"?(tt(re,!0),je==="cards"?window.setTimeout(()=>{Ot(re)},320):Fi(re)):ae.phase==="error"?(tt(re,!1),je==="cards"&&ge.current.get(re)?.reset()):ae.phase==="success"&&(tt(re,!1),it())};return window.addEventListener("finished-downloads:delete",ye),()=>window.removeEventListener("finished-downloads:delete",ye)},[Fi,tt,Ot,je,it]),w.useEffect(()=>{const ye=X=>{const ae=X.detail,re=String(ae?.oldFile??"").trim(),xe=String(ae?.newFile??"").trim();!re||!xe||re===xe||ti(re,xe)};return window.addEventListener("finished-downloads:rename",ye),()=>window.removeEventListener("finished-downloads:rename",ye)},[ti]);const ks=w.useMemo(()=>{const ye=bi.filter(ae=>!J.has(qn(ae))),X=It.length?ye.filter(ae=>{const re=bn(ae.output||""),xe=Qo(ae.output),we=An(xe),He=ct.tagsByModelKey[we]??[],st=An([re,uo(re),xe,ae.id,ae.status,He.join(" ")].join(" "));for(const Xe of It)if(!st.includes(Xe))return!1;return!0}):ye;return mt.size===0?X:X.filter(ae=>{const re=An(Qo(ae.output)),xe=ct.tagSetByModelKey[re];if(!xe||xe.size===0)return!1;for(const we of mt)if(!xe.has(we))return!1;return!0})},[bi,J,mt,ct,It]),Os=Ke?ks.length:tr,Vs=w.useMemo(()=>{if(!Ke)return ks;const ye=(y-1)*v,X=ye+v;return ks.slice(Math.max(0,ye),Math.max(0,X))},[Ke,ks,y,v]),zs=!Ke&&Os===0,ki=Ke&&ks.length===0;w.useEffect(()=>{if(!Ke)return;const ye=Math.max(1,Math.ceil(ks.length/v));y>ye&&b(ye)},[Ke,ks.length,y,v,b]),w.useEffect(()=>{if(!(R==="hover"&&!$&&(je==="cards"||je==="gallery"||je==="table"))){H(null),W.current?.disconnect(),W.current=null;return}if(je==="cards"&&yt?.key){H(yt.key);return}W.current?.disconnect();const X=new IntersectionObserver(ae=>{let re=null,xe=0;for(const we of ae){if(!we.isIntersecting)continue;const He=K.current.get(we.target);He&&we.intersectionRatio>xe&&(xe=we.intersectionRatio,re=He)}re&&H(we=>we===re?we:re)},{threshold:[0,.15,.3,.5,.7,.9],rootMargin:"0px"});W.current=X;for(const[ae,re]of B.current)K.current.set(re,ae),X.observe(re);return()=>{X.disconnect(),W.current===X&&(W.current=null)}},[je,R,$,yt?.key]);const qs=ye=>{const X=qn(ye),ae=Ut[X]??ye?.durationSeconds;if(typeof ae=="number"&&Number.isFinite(ae)&&ae>0)return qS(ae*1e3);const re=Date.parse(String(ye.startedAt||"")),xe=Date.parse(String(ye.endedAt||""));return Number.isFinite(re)&&Number.isFinite(xe)&&xe>re?qS(xe-re):"—"},ls=w.useCallback(ye=>X=>{const ae=B.current.get(ye);ae&&W.current&&W.current.unobserve(ae),X?(B.current.set(ye,X),K.current.set(X,ye),W.current?.observe(X)):B.current.delete(ye)},[]),ns=w.useCallback((ye,X)=>{if(!Number.isFinite(X)||X<=0)return;const ae=qn(ye),re=vi.current[ae];typeof re=="number"&&Math.abs(re-X)<.5||(vi.current={...vi.current,[ae]:X},Bi())},[Bi]),Di=[{key:"preview",header:"Vorschau",widthClassName:"w-[140px]",cell:ye=>{const X=qn(ye),re=!(!!n&&D===X);return g.jsx("div",{ref:ls(X),className:"py-1",onClick:xe=>xe.stopPropagation(),onMouseDown:xe=>xe.stopPropagation(),onMouseEnter:()=>{$&&M(X)},onMouseLeave:()=>{$&&M(null)},children:g.jsx(tb,{job:ye,getFileName:bn,durationSeconds:Ut[X],muted:re,popoverMuted:re,onDuration:ns,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"?O===X:!1,animatedMode:"teaser",animatedTrigger:"always",assetNonce:_})})}},{key:"Model",header:"Model",sortable:!0,sortValue:ye=>{const X=bn(ye.output||""),ae=rc(X),re=Qo(ye.output),xe=uo(X);return`${re} ${ae?"HOT":""} ${xe}`.trim()},cell:ye=>{const X=bn(ye.output||""),ae=rc(X),re=uo(X),xe=Qo(ye.output),we=An(Qo(ye.output)),He=WS(I[we]?.tags),st=He.slice(0,6),Xe=He.length-st.length,kt=He.join(", ");return g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:xe}),g.jsxs("div",{className:"mt-0.5 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"truncate",title:re,children:re||"—"}),ae?g.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]}),st.length>0?g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 min-w-0",children:[st.map(Tt=>g.jsx(Kr,{tag:Tt,active:mt.has(An(Tt)),onClick:$t},Tt)),Xe>0?g.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:kt,children:["+",Xe]}):null]}):null]})]})}},{key:"status",header:"Status",sortable:!0,sortValue:ye=>ye.status==="finished"?0:ye.status==="stopped"?1:ye.status==="failed"?2:9,cell:ye=>{const X="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset";if(ye.status==="failed"){const ae=UM(ye.error),re=ae?`failed (${ae})`:"failed";return g.jsx("span",{className:`${X} bg-red-50 text-red-700 ring-red-200 dark:bg-red-500/10 dark:text-red-300 dark:ring-red-500/30`,title:ye.error||"",children:re})}return ye.status==="finished"?g.jsx("span",{className:`${X} 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"}):ye.status==="stopped"?g.jsx("span",{className:`${X} 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"}):g.jsx("span",{className:`${X} bg-gray-50 text-gray-700 ring-gray-200 dark:bg-white/5 dark:text-gray-300 dark:ring-white/10`,children:ye.status})}},{key:"completedAt",header:"Fertiggestellt am",sortable:!0,widthClassName:"w-[150px]",sortValue:ye=>{const X=Date.parse(String(ye.endedAt||""));return Number.isFinite(X)?X:Number.NEGATIVE_INFINITY},cell:ye=>{const X=Date.parse(String(ye.endedAt||""));if(!Number.isFinite(X))return g.jsx("span",{className:"text-xs text-gray-400",children:"—"});const ae=new Date(X),re=ae.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),xe=ae.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"});return g.jsxs("time",{dateTime:ae.toISOString(),title:`${re} ${xe}`,className:"tabular-nums whitespace-nowrap text-sm text-gray-900 dark:text-white",children:[g.jsx("span",{className:"font-medium",children:re}),g.jsx("span",{className:"mx-1 text-gray-400 dark:text-gray-600",children:"·"}),g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:xe})]})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:ye=>Gs(ye),cell:ye=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:qs(ye)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:ye=>{const X=fm(ye);return typeof X=="number"?X:Number.NEGATIVE_INFINITY},cell:ye=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Sy(fm(ye))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:ye=>{const X=qn(ye),ae=se.has(X)||xi.has(X)||Oi.has(X),re=bn(ye.output||""),xe=rc(re),we=An(Qo(ye.output)),He=I[we],st=!!He?.favorite,Xe=He?.liked===!0,kt=!!He?.watching;return g.jsx(Aa,{job:ye,variant:"table",busy:ae,isHot:xe,isFavorite:st,isLiked:Xe,isWatching:kt,onToggleWatch:f,onToggleFavorite:c,onToggleLike:d,onToggleHot:Kt,onKeep:oi,onDelete:Li,order:["watch","favorite","like","hot","details","add","keep","delete"],className:"flex items-center justify-end gap-1"})}}],Ms=ye=>{if(!ye)return"completed_desc";const X=ye,ae=String(X.key??X.columnKey??X.id??""),re=String(X.dir??X.direction??X.order??"").toLowerCase(),xe=re==="asc"||re==="1"||re==="true";return ae==="completedAt"?xe?"completed_asc":"completed_desc":ae==="runtime"?xe?"duration_asc":"duration_desc":ae==="size"?xe?"size_asc":"size_desc":ae==="Model"||ae==="video"?xe?"file_asc":"file_desc":xe?"completed_asc":"completed_desc"},mn=ye=>{ot(ye);const X=Ms(ye);L(X),y!==1&&b(1)},rs=KS("(max-width: 639px)");return w.useEffect(()=>{rs||(ge.current=new Map)},[rs]),w.useEffect(()=>{let ye=null,X=!1,ae=null,re=null;const xe=()=>{re==null&&(re=window.setTimeout(()=>{re=null,zs&&y!==1&&b(1),it()},80))},we=()=>{if(!X)try{ye=new EventSource("/api/record/done/stream"),ye.onmessage=()=>{xe()},ye.onerror=()=>{try{ye?.close()}catch{}ye=null,!X&&(ae!=null&&window.clearTimeout(ae),ae=window.setTimeout(we,1e3))}}catch{ae!=null&&window.clearTimeout(ae),ae=window.setTimeout(we,1e3)}};return we(),()=>{X=!0,ae!=null&&window.clearTimeout(ae),re!=null&&window.clearTimeout(re);try{ye?.close()}catch{}}},[it,zs,y,b]),w.useEffect(()=>{zs&&y!==1&&b(1)},[zs,y,b]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:[g.jsxs("div",{className:"flex items-center gap-3 p-3",children:[g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Os})]}),g.jsxs("div",{className:"sm:hidden flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Os})]}),g.jsxs("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:[g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("input",{value:et,onChange:ye=>Gt(ye.target.value),placeholder:"Suchen…",className:` - h-9 w-full max-w-[420px] 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] - `}),(et||"").trim()!==""?g.jsx(Zt,{size:"sm",variant:"soft",onClick:Ft,children:"Leeren"}):null]}),g.jsx("div",{className:"hidden sm:block",children:g.jsx(nl,{label:"Behaltene Downloads anzeigen",checked:vt,onChange:ye=>{y!==1&&b(1),jt(ye),it()}})}),je!=="table"&&g.jsxs("div",{className:"hidden sm:block",children:[g.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort",value:E,onChange:ye=>{const X=ye.target.value;L(X),y!==1&&b(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:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),g.jsx(Zt,{size:rs?"sm":"md",variant:"soft",disabled:!Y||Q,onClick:Je,title:Y?`Letzte Aktion rückgängig machen (${Y.kind})`:"Keine Aktion zum Rückgängig machen",children:"Undo"}),g.jsx(fO,{value:je,onChange:ye=>bt(ye),size:rs?"sm":"md",ariaLabel:"Ansicht",items:[{id:"table",icon:g.jsx(JO,{className:rs?"size-4":"size-5"}),label:rs?void 0:"Tabelle",srLabel:"Tabelle"},{id:"cards",icon:g.jsx(KO,{className:rs?"size-4":"size-5"}),label:rs?void 0:"Cards",srLabel:"Cards"},{id:"gallery",icon:g.jsx(XO,{className:rs?"size-4":"size-5"}),label:rs?void 0:"Galerie",srLabel:"Galerie"}]}),g.jsxs("button",{type:"button",className:`sm:hidden relative inline-flex items-center justify-center rounded-md border border-gray-200 bg-white p-2 shadow-sm - hover:bg-gray-50 dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:hover:bg-white/10`,onClick:()=>ut(ye=>!ye),"aria-expanded":We,"aria-controls":"finished-mobile-options","aria-label":"Filter & Optionen",children:[g.jsx(pO,{className:"size-5"}),Ke||vt?g.jsx("span",{className:"absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-indigo-500 ring-2 ring-white dark:ring-gray-950"}):null]})]})]}),Ye.length>0?g.jsxs("div",{className:"hidden sm:flex items-center gap-2 border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Ye.map(ye=>g.jsx(Kr,{tag:ye,active:!0,onClick:$t},ye)),g.jsx(Zt,{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:Qt,children:"Zurücksetzen"})]})]}):null,g.jsxs("div",{id:"finished-mobile-options",className:["sm:hidden overflow-hidden transition-[max-height,opacity] duration-200 ease-in-out",We?"max-h-[720px] opacity-100":"max-h-0 opacity-0"].join(" "),children:[g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 p-3",children:g.jsxs("div",{className:"space-y-2",children:[g.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("input",{value:et,onChange:ye=>Gt(ye.target.value),placeholder:"Suchen…",className:` - h-10 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 - focus:outline-none focus:ring-2 focus:ring-indigo-500 - dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] - `}),(et||"").trim()!==""?g.jsx(Zt,{size:"sm",variant:"soft",onClick:Ft,children:"Clear"}):null]})}),g.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-100",children:"Keep anzeigen"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Behaltene Downloads in der Liste"})]}),g.jsx(Xv,{checked:vt,onChange:ye=>{y!==1&&b(1),jt(ye),it()},ariaLabel:"Behaltene Downloads anzeigen",size:"default"})]})}),je!=="table"?g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:[g.jsx("div",{className:"text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort-mobile",value:E,onChange:ye=>{const X=ye.target.value;L(X),y!==1&&b(1)},className:` - w-full h-10 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm - dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] - `,children:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}):null]})}),Ye.length>0?g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Ye.map(ye=>g.jsx(Kr,{tag:ye,active:!0,onClick:$t},ye)),g.jsx(Zt,{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:Qt,children:"Zurücksetzen"})]})]})}):null]})]})}),zs?g.jsx(Ca,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"📁"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine abgeschlossenen Downloads"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Im Zielordner ist aktuell nichts vorhanden."})]})]})}):ki?g.jsxs(Ca,{grayBody:!0,children:[g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Treffer für die aktuellen Filter."}),Ye.length>0||(et||"").trim()!==""?g.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ye.length>0?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Qt,children:"Tag-Filter zurücksetzen"}):null,(et||"").trim()!==""?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Ft,children:"Suche zurücksetzen"}):null]}):null]}):g.jsxs(g.Fragment,{children:[je==="cards"&&g.jsx(CM,{rows:Vs,isSmall:rs,blurPreviews:t,durations:Ut,teaserKey:O,teaserPlayback:R,teaserAudio:n,hoverTeaserKey:D,inlinePlay:yt,setInlinePlay:z,deletingKeys:se,keepingKeys:xi,removingKeys:Oi,swipeRefs:ge,keyFor:qn,baseName:bn,modelNameFromOutput:Qo,runtimeOf:qs,sizeBytesOf:fm,formatBytes:Sy,lower:An,onOpenPlayer:r,openPlayer:Oe,startInline:_e,tryAutoplayInline:te,registerTeaserHost:ls,handleDuration:ns,deleteVideo:Li,keepVideo:oi,releasePlayingFile:Mi,modelsByKey:I,onToggleHot:Kt,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:mt,onToggleTagFilter:$t,onHoverPreviewKeyChange:M,assetNonce:_??0}),je==="table"&&g.jsx(kM,{rows:Vs,columns:Di,getRowKey:ye=>qn(ye),sort:dt,onSortChange:mn,onRowClick:r,rowClassName:ye=>{const X=qn(ye);return["transition-all duration-300",(se.has(X)||Oi.has(X))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",se.has(X)&&"animate-pulse",(xi.has(X)||Oi.has(X))&&"pointer-events-none",xi.has(X)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",Oi.has(X)&&"opacity-0"].filter(Boolean).join(" ")}}),je==="gallery"&&g.jsx(DM,{rows:Vs,blurPreviews:t,durations:Ut,handleDuration:ns,teaserKey:O,teaserPlayback:R,teaserAudio:n,hoverTeaserKey:D,keyFor:qn,baseName:bn,modelNameFromOutput:Qo,runtimeOf:qs,sizeBytesOf:fm,formatBytes:Sy,deletingKeys:se,keepingKeys:xi,removingKeys:Oi,deletedKeys:J,registerTeaserHost:ls,onOpenPlayer:r,deleteVideo:Li,keepVideo:oi,onToggleHot:Kt,lower:An,modelsByKey:I,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:mt,onToggleTagFilter:$t,onHoverPreviewKeyChange:M}),g.jsx(BA,{page:y,pageSize:v,totalItems:Os,onPageChange:ye=>{Ec.flushSync(()=>{z(null),H(null),M(null)});for(const X of Vs){const ae=bn(X.output||"");ae&&(window.dispatchEvent(new CustomEvent("player:release",{detail:{file:ae}})),window.dispatchEvent(new CustomEvent("player:close",{detail:{file:ae}})))}window.scrollTo({top:0,behavior:"auto"}),b(ye)},showSummary:!1,prevLabel:"Zurück",nextLabel:"Weiter",className:"mt-4"})]})]})}var Ey,YS;function qp(){if(YS)return Ey;YS=1;var s;return typeof window<"u"?s=window:typeof Qm<"u"?s=Qm:typeof self<"u"?s=self:s={},Ey=s,Ey}var $M=qp();const fe=jc($M),HM={},GM=Object.freeze(Object.defineProperty({__proto__:null,default:HM},Symbol.toStringTag,{value:"Module"})),VM=DI(GM);var wy,XS;function jA(){if(XS)return wy;XS=1;var s=typeof Qm<"u"?Qm:typeof window<"u"?window:{},e=VM,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),wy=t,wy}var zM=jA();const at=jc(zM);var mm={exports:{}},Ay={exports:{}},QS;function qM(){return QS||(QS=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 a=Object.prototype.toString.call(n).slice(8,-1);if(a==="Object"&&n.constructor&&(a=n.constructor.name),a==="Map"||a==="Set")return Array.from(n);if(a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var a=0,u=new Array(r);a=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 a=r.split("="),u=a[0],c=a[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Ly=e,Ly}var iE;function QM(){if(iE)return mm.exports;iE=1;var s=qp(),e=qM(),t=KM(),i=WM(),n=YM();d.httpHandler=XM(),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(),R=E.slice(L+1).trim();typeof _[I]>"u"?_[I]=R:Array.isArray(_[I])?_[I].push(R):_[I]=[_[I],R]}),_};mm.exports=d,mm.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||y,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,a(["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 a(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(ie,Q,oe){E||(E=!0,v.callback(ie,Q,oe))};function I(){B.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(P,0)}function R(){var Y=void 0;if(B.response?Y=B.response:Y=B.responseText||p(B),ue)try{Y=JSON.parse(Y)}catch{}return Y}function $(Y){if(clearTimeout(se),clearTimeout(v.retryTimeout),Y instanceof Error||(Y=new Error(""+(Y||"Unknown XMLHttpRequest Error"))),Y.statusCode=0,!H&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=B,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ie={headers:q.headers||{},body:q.body,responseUrl:B.responseURL,responseType:B.responseType},Q=d.responseInterceptorsStorage.execute(v.requestType,ie);q.body=Q.body,q.headers=Q.headers}return L(Y,q)}function P(){if(!H){var Y;clearTimeout(se),clearTimeout(v.retryTimeout),v.useXDR&&B.status===void 0?Y=200:Y=B.status===1223?204:B.status;var ie=q,Q=null;if(Y!==0?(ie={body:R(),statusCode:Y,method:M,headers:{},url:D,rawRequest:B},B.getAllResponseHeaders&&(ie.headers=r(B.getAllResponseHeaders()))):Q=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var oe={headers:ie.headers||{},body:ie.body,responseUrl:B.responseURL,responseType:B.responseType},F=d.responseInterceptorsStorage.execute(v.requestType,oe);ie.body=F.body,ie.headers=F.headers}return L(Q,ie,ie.body)}}var B=v.xhr||null;B||(v.cors||v.useXDR?B=new d.XDomainRequest:B=new d.XMLHttpRequest);var O,H,D=B.url=v.uri||v.url,M=B.method=v.method||"GET",W=v.body||v.data,K=B.headers=v.headers||{},J=!!v.sync,ue=!1,se,q={body:void 0,headers:{},statusCode:0,method:M,url:D,rawRequest:B};if("json"in v&&v.json!==!1&&(ue=!0,K.accept||K.Accept||(K.Accept="application/json"),M!=="GET"&&M!=="HEAD"&&(K["content-type"]||K["Content-Type"]||(K["Content-Type"]="application/json"),W=JSON.stringify(v.json===!0?W:v.json))),B.onreadystatechange=I,B.onload=P,B.onerror=$,B.onprogress=function(){},B.onabort=function(){H=!0,clearTimeout(v.retryTimeout)},B.ontimeout=$,B.open(M,D,!J,v.username,v.password),J||(B.withCredentials=!!v.withCredentials),!J&&v.timeout>0&&(se=setTimeout(function(){if(!H){H=!0,B.abort("timeout");var Y=new Error("XMLHttpRequest timeout");Y.code="ETIMEDOUT",$(Y)}},v.timeout)),B.setRequestHeader)for(O in K)K.hasOwnProperty(O)&&B.setRequestHeader(O,K[O]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&(B.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend(B),B.send(W||null),B}function p(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 y(){}return mm.exports}var ZM=QM();const $A=jc(ZM);var Ry={exports:{}},Iy,sE;function JM(){if(sE)return Iy;sE=1;var s=jA(),e=Object.create||(function(){function D(){}return function(M){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return D.prototype=M,new D}})();function t(D,M){this.name="ParsingError",this.code=D.code,this.message=M||D.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(D){function M(K,J,ue,se){return(K|0)*3600+(J|0)*60+(ue|0)+(se|0)/1e3}var W=D.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return W?W[3]?M(W[1],W[2],W[3].replace(":",""),W[4]):W[1]>59?M(W[1],W[2],0,W[4]):M(0,W[1],W[2],W[4]):null}function n(){this.values=e(null)}n.prototype={set:function(D,M){!this.get(D)&&M!==""&&(this.values[D]=M)},get:function(D,M,W){return W?this.has(D)?this.values[D]:M[W]:this.has(D)?this.values[D]:M},has:function(D){return D in this.values},alt:function(D,M,W){for(var K=0;K=0&&M<=100)?(this.set(D,M),!0):!1}};function r(D,M,W,K){var J=K?D.split(K):[D];for(var ue in J)if(typeof J[ue]=="string"){var se=J[ue].split(W);if(se.length===2){var q=se[0].trim(),Y=se[1].trim();M(q,Y)}}}function a(D,M,W){var K=D;function J(){var q=i(D);if(q===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+K);return D=D.replace(/^[^\sa-zA-Z-]+/,""),q}function ue(q,Y){var ie=new n;r(q,function(Q,oe){switch(Q){case"region":for(var F=W.length-1;F>=0;F--)if(W[F].id===oe){ie.set(Q,W[F].region);break}break;case"vertical":ie.alt(Q,oe,["rl","lr"]);break;case"line":var ee=oe.split(","),he=ee[0];ie.integer(Q,he),ie.percent(Q,he)&&ie.set("snapToLines",!1),ie.alt(Q,he,["auto"]),ee.length===2&&ie.alt("lineAlign",ee[1],["start","center","end"]);break;case"position":ee=oe.split(","),ie.percent(Q,ee[0]),ee.length===2&&ie.alt("positionAlign",ee[1],["start","center","end"]);break;case"size":ie.percent(Q,oe);break;case"align":ie.alt(Q,oe,["start","center","end","left","right"]);break}},/:/,/\s/),Y.region=ie.get("region",null),Y.vertical=ie.get("vertical","");try{Y.line=ie.get("line","auto")}catch{}Y.lineAlign=ie.get("lineAlign","start"),Y.snapToLines=ie.get("snapToLines",!0),Y.size=ie.get("size",100);try{Y.align=ie.get("align","center")}catch{Y.align=ie.get("align","middle")}try{Y.position=ie.get("position","auto")}catch{Y.position=ie.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},Y.align)}Y.positionAlign=ie.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},Y.align)}function se(){D=D.replace(/^\s+/,"")}if(se(),M.startTime=J(),se(),D.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+K);D=D.substr(3),se(),M.endTime=J(),se(),ue(D,M)}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 y(D,M){function W(){if(!M)return null;function he(pe){return M=M.substr(pe.length),pe}var be=M.match(/^([^<]*)(<[^>]*>?)?/);return he(be[1]?be[1]:be[2])}function K(he){return u.innerHTML=he,he=u.textContent,u.textContent="",he}function J(he,be){return!p[be.localName]||p[be.localName]===he.localName}function ue(he,be){var pe=c[he];if(!pe)return null;var Ce=D.document.createElement(pe),Re=f[he];return Re&&be&&(Ce[Re]=be.trim()),Ce}for(var se=D.document.createElement("div"),q=se,Y,ie=[];(Y=W())!==null;){if(Y[0]==="<"){if(Y[1]==="/"){ie.length&&ie[ie.length-1]===Y.substr(2).replace(">","")&&(ie.pop(),q=q.parentNode);continue}var Q=i(Y.substr(1,Y.length-2)),oe;if(Q){oe=D.document.createProcessingInstruction("timestamp",Q),q.appendChild(oe);continue}var F=Y.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!F||(oe=ue(F[1],F[3]),!oe)||!J(q,oe))continue;if(F[2]){var ee=F[2].split(".");ee.forEach(function(he){var be=/^bg_/.test(he),pe=be?he.slice(3):he;if(d.hasOwnProperty(pe)){var Ce=be?"background-color":"color",Re=d[pe];oe.style[Ce]=Re}}),oe.className=ee.join(" ")}ie.push(F[1]),q.appendChild(oe),q=oe;continue}q.appendChild(D.document.createTextNode(K(Y)))}return se}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(D){for(var M=0;M=W[0]&&D<=W[1])return!0}return!1}function _(D){var M=[],W="",K;if(!D||!D.childNodes)return"ltr";function J(q,Y){for(var ie=Y.childNodes.length-1;ie>=0;ie--)q.push(Y.childNodes[ie])}function ue(q){if(!q||!q.length)return null;var Y=q.pop(),ie=Y.textContent||Y.innerText;if(ie){var Q=ie.match(/^.*(\n|\r)/);return Q?(q.length=0,Q[0]):ie}if(Y.tagName==="ruby")return ue(q);if(Y.childNodes)return J(q,Y),ue(q)}for(J(M,D);W=ue(M);)for(var se=0;se=0&&D.line<=100))return D.line;if(!D.track||!D.track.textTrackList||!D.track.textTrackList.mediaElement)return-1;for(var M=D.track,W=M.textTrackList,K=0,J=0;JD.left&&this.topD.top},R.prototype.overlapsAny=function(D){for(var M=0;M=D.top&&this.bottom<=D.bottom&&this.left>=D.left&&this.right<=D.right},R.prototype.overlapsOppositeAxis=function(D,M){switch(M){case"+x":return this.leftD.right;case"+y":return this.topD.bottom}},R.prototype.intersectPercentage=function(D){var M=Math.max(0,Math.min(this.right,D.right)-Math.max(this.left,D.left)),W=Math.max(0,Math.min(this.bottom,D.bottom)-Math.max(this.top,D.top)),K=M*W;return K/(this.height*this.width)},R.prototype.toCSSCompatValues=function(D){return{top:this.top-D.top,bottom:D.bottom-this.bottom,left:this.left-D.left,right:D.right-this.right,height:this.height,width:this.width}},R.getSimpleBoxPosition=function(D){var M=D.div?D.div.offsetHeight:D.tagName?D.offsetHeight:0,W=D.div?D.div.offsetWidth:D.tagName?D.offsetWidth:0,K=D.div?D.div.offsetTop:D.tagName?D.offsetTop:0;D=D.div?D.div.getBoundingClientRect():D.tagName?D.getBoundingClientRect():D;var J={left:D.left,right:D.right,top:D.top||K,height:D.height||M,bottom:D.bottom||K+(D.height||M),width:D.width||W};return J};function $(D,M,W,K){function J(pe,Ce){for(var Re,Ze=new R(pe),Ge=1,it=0;itdt&&(Re=new R(pe),Ge=dt),pe=new R(Ze)}return Re||Ze}var ue=new R(M),se=M.cue,q=E(se),Y=[];if(se.snapToLines){var ie;switch(se.vertical){case"":Y=["+y","-y"],ie="height";break;case"rl":Y=["+x","-x"],ie="width";break;case"lr":Y=["-x","+x"],ie="width";break}var Q=ue.lineHeight,oe=Q*Math.round(q),F=W[ie]+Q,ee=Y[0];Math.abs(oe)>F&&(oe=oe<0?-1:1,oe*=Math.ceil(F/Q)*Q),q<0&&(oe+=se.vertical===""?W.height:W.width,Y=Y.reverse()),ue.move(ee,oe)}else{var he=ue.lineHeight/W.height*100;switch(se.lineAlign){case"center":q-=he/2;break;case"end":q-=he;break}switch(se.vertical){case"":M.applyStyles({top:M.formatStyle(q,"%")});break;case"rl":M.applyStyles({left:M.formatStyle(q,"%")});break;case"lr":M.applyStyles({right:M.formatStyle(q,"%")});break}Y=["+y","-x","+x","-y"],ue=new R(M)}var be=J(ue,Y);M.move(be.toCSSCompatValues(W))}function P(){}P.StringDecoder=function(){return{decode:function(D){if(!D)return"";if(typeof D!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(D))}}},P.convertCueToDOMTree=function(D,M){return!D||!M?null:y(D,M)};var B=.05,O="sans-serif",H="1.5%";return P.processCues=function(D,M,W){if(!D||!M||!W)return null;for(;W.firstChild;)W.removeChild(W.firstChild);var K=D.document.createElement("div");K.style.position="absolute",K.style.left="0",K.style.right="0",K.style.top="0",K.style.bottom="0",K.style.margin=H,W.appendChild(K);function J(Q){for(var oe=0;oe")===-1){M.cue.id=se;continue}case"CUE":try{a(se,M.cue,M.regionList)}catch(Q){M.reportOrThrowError(Q),M.cue=null,M.state="BADCUE";continue}M.state="CUETEXT";continue;case"CUETEXT":var ie=se.indexOf("-->")!==-1;if(!se||ie&&(Y=!0)){M.oncue&&M.oncue(M.cue),M.cue=null,M.state="ID";continue}M.cue.text&&(M.cue.text+=` -`),M.cue.text+=se.replace(/\u2028/g,` -`).replace(/u2029/g,` -`);continue;case"BADCUE":se||(M.state="ID");continue}}}catch(Q){M.reportOrThrowError(Q),M.state==="CUETEXT"&&M.cue&&M.oncue&&M.oncue(M.cue),M.cue=null,M.state=M.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var D=this;try{if(D.buffer+=D.decoder.decode(),(D.cue||D.state==="HEADER")&&(D.buffer+=` - -`,D.parse()),D.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(M){D.reportOrThrowError(M)}return D.onflush&&D.onflush(),this}},Iy=P,Iy}var Ny,nE;function e3(){if(nE)return Ny;nE=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(a){if(typeof a!="string")return!1;var u=e[a.toLowerCase()];return u?a.toLowerCase():!1}function n(a){if(typeof a!="string")return!1;var u=t[a.toLowerCase()];return u?a.toLowerCase():!1}function r(a,u,c){this.hasBeenReset=!1;var d="",f=!1,p=a,y=u,v=c,b=null,_="",E=!0,L="auto",I="start",R="auto",$="auto",P=100,B="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return d},set:function(O){d=""+O}},pauseOnExit:{enumerable:!0,get:function(){return f},set:function(O){f=!!O}},startTime:{enumerable:!0,get:function(){return p},set:function(O){if(typeof O!="number")throw new TypeError("Start time must be set to a number.");p=O,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return y},set:function(O){if(typeof O!="number")throw new TypeError("End time must be set to a number.");y=O,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return v},set:function(O){v=""+O,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return b},set:function(O){b=O,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _},set:function(O){var H=i(O);if(H===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_=H,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return E},set:function(O){E=!!O,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return L},set:function(O){if(typeof O!="number"&&O!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");L=O,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return I},set:function(O){var H=n(O);H?(I=H,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return R},set:function(O){if(O<0||O>100)throw new Error("Position must be between 0 and 100.");R=O,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return $},set:function(O){var H=n(O);H?($=H,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return P},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");P=O,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return B},set:function(O){var H=n(O);if(!H)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");B=H,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Ny=r,Ny}var Oy,rE;function t3(){if(rE)return Oy;rE=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,a=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 a},set:function(p){if(!t(p))throw new Error("RegionAnchorY must be between 0 and 100.");a=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 y=e(p);y===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=y}}})}return Oy=i,Oy}var aE;function i3(){if(aE)return Ry.exports;aE=1;var s=qp(),e=Ry.exports={WebVTT:JM(),VTTCue:e3(),VTTRegion:t3()};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(),Ry.exports}var s3=i3();const oE=jc(s3);function Ns(){return Ns=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,a=0;a-1;t=this.buffer.indexOf(` -`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const a3=" ",My=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},o3=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},Cn=function(s){const e={};if(!s)return e;const t=s.split(o3());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},uE=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 l3 extends nb{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,a)=>{const u=a(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let a=0;ar),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 u3=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),Zo=function(s){const e={};return Object.keys(s).forEach(function(t){e[u3(t)]=s[t]}),e},Py=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",a="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&&a&&(n.key=a),!n.timeline&&typeof p=="number"&&(n.timeline=p),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 R in _.attributes)typeof _.attributes[R]=="string"&&(_.attributes[R]=_.attributes[R].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=y)),"offset"in _&&(n.byterange=I,I.offset=_.offset),y=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"){a=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:HA(_.attributes.URI.split(",")[1])};return}_.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),a={method:_.attributes.METHOD||"AES-128",uri:_.attributes.URI},typeof _.attributes.IV<"u"&&(a.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),a&&(r.key=a)},"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={}),Ns(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(){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((R,$)=>($.programDateTime=R-$.duration*1e3,$.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(_.duration)||_.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+_.duration});return}this.manifest.targetDuration=_.duration,Py.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=Zo(_.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",_.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const I=this.manifest.segments.length,R=Zo(_.attributes);n.parts=n.parts||[],n.parts.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=v),v=R.byterange.offset+R.byterange.length);const $=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${$} for segment #${I}`,_.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((P,B)=>{P.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${B} lacks required attribute(s): LAST-PART`})})},"server-control"(){const I=this.manifest.serverControl=Zo(_.attributes);I.hasOwnProperty("canBlockReload")||(I.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Py.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,R=Zo(_.attributes),$=R.type&&R.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=$?v:0,$&&(v=R.byterange.offset+R.byterange.length)));const P=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${P} for segment #${I}`,_.attributes,["TYPE","URI"]),!!R.type)for(let B=0;BB.id===R.id);this.manifest.dateRanges[P]=Ns(this.manifest.dateRanges[P],R),b[R.id]=Ns(b[R.id],R),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=Zo(_.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",_.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const I=(R,$)=>{if(R in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${R}`});return}this.manifest.definitions[R]=$};if("QUERYPARAM"in _.attributes){if("NAME"in _.attributes||"IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const R=this.params.get(_.attributes.QUERYPARAM);if(!R){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${_.attributes.QUERYPARAM}`});return}I(_.attributes.QUERYPARAM,decodeURIComponent(R));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),a&&(n.key=a),n.timeline=p,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){(ep&&(f-=p,f-=p,f-=cn(2))}return Number(f)},T3=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=cn(e);for(var a=v3(e),u=new Uint8Array(new ArrayBuffer(a)),c=0;c=t.length&&d.call(t,function(f,p){var y=c[p]?c[p]&e[a+p]:e[a+p];return f===y})},S3=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var a in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][a];i(u,n,r,a)}})},Kd={},Ja={},Hl={},hE;function Wp(){if(hE)return Hl;hE=1;function s(r,a,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,a);for(var c=0;c=0&&z=0){for(var Oe=V.length-1;_e0},lookupPrefix:function(z){for(var V=this;V;){var te=V._nsMap;if(te){for(var _e in te)if(Object.prototype.hasOwnProperty.call(te,_e)&&te[_e]===z)return _e}V=V.nodeType==y?V.ownerDocument:V.parentNode}return null},lookupNamespaceURI:function(z){for(var V=this;V;){var te=V._nsMap;if(te&&Object.prototype.hasOwnProperty.call(te,z))return te[z];V=V.nodeType==y?V.ownerDocument:V.parentNode}return null},isDefaultNamespace:function(z){var V=this.lookupPrefix(z);return V==null}};function ee(z){return z=="<"&&"<"||z==">"&&">"||z=="&"&&"&"||z=='"'&&"""||"&#"+z.charCodeAt()+";"}c(f,F),c(f,F.prototype);function he(z,V){if(V(z))return!0;if(z=z.firstChild)do if(he(z,V))return!0;while(z=z.nextSibling)}function be(){this.ownerDocument=this}function pe(z,V,te){z&&z._inc++;var _e=te.namespaceURI;_e===t.XMLNS&&(V._nsMap[te.prefix?te.localName:""]=te.value)}function Ce(z,V,te,_e){z&&z._inc++;var Oe=te.namespaceURI;Oe===t.XMLNS&&delete V._nsMap[te.prefix?te.localName:""]}function Re(z,V,te){if(z&&z._inc){z._inc++;var _e=V.childNodes;if(te)_e[_e.length++]=te;else{for(var Oe=V.firstChild,tt=0;Oe;)_e[tt++]=Oe,Oe=Oe.nextSibling;_e.length=tt,delete _e[_e.length]}}}function Ze(z,V){var te=V.previousSibling,_e=V.nextSibling;return te?te.nextSibling=_e:z.firstChild=_e,_e?_e.previousSibling=te:z.lastChild=te,V.parentNode=null,V.previousSibling=null,V.nextSibling=null,Re(z.ownerDocument,z),V}function Ge(z){return z&&(z.nodeType===F.DOCUMENT_NODE||z.nodeType===F.DOCUMENT_FRAGMENT_NODE||z.nodeType===F.ELEMENT_NODE)}function it(z){return z&&(ot(z)||nt(z)||dt(z)||z.nodeType===F.DOCUMENT_FRAGMENT_NODE||z.nodeType===F.COMMENT_NODE||z.nodeType===F.PROCESSING_INSTRUCTION_NODE)}function dt(z){return z&&z.nodeType===F.DOCUMENT_TYPE_NODE}function ot(z){return z&&z.nodeType===F.ELEMENT_NODE}function nt(z){return z&&z.nodeType===F.TEXT_NODE}function ft(z,V){var te=z.childNodes||[];if(e(te,ot)||dt(V))return!1;var _e=e(te,dt);return!(V&&_e&&te.indexOf(_e)>te.indexOf(V))}function gt(z,V){var te=z.childNodes||[];function _e(tt){return ot(tt)&&tt!==V}if(e(te,_e))return!1;var Oe=e(te,dt);return!(V&&Oe&&te.indexOf(Oe)>te.indexOf(V))}function je(z,V,te){if(!Ge(z))throw new K(D,"Unexpected parent node type "+z.nodeType);if(te&&te.parentNode!==z)throw new K(M,"child not in parent");if(!it(V)||dt(V)&&z.nodeType!==F.DOCUMENT_NODE)throw new K(D,"Unexpected node type "+V.nodeType+" for parent node type "+z.nodeType)}function bt(z,V,te){var _e=z.childNodes||[],Oe=V.childNodes||[];if(V.nodeType===F.DOCUMENT_FRAGMENT_NODE){var tt=Oe.filter(ot);if(tt.length>1||e(Oe,nt))throw new K(D,"More than one element or text in fragment");if(tt.length===1&&!ft(z,te))throw new K(D,"Element in fragment can not be inserted before doctype")}if(ot(V)&&!ft(z,te))throw new K(D,"Only one element can be added and only after doctype");if(dt(V)){if(e(_e,dt))throw new K(D,"Only one doctype is allowed");var Ot=e(_e,ot);if(te&&_e.indexOf(Ot)<_e.indexOf(te))throw new K(D,"Doctype can only be inserted before an element");if(!te&&Ot)throw new K(D,"Doctype can not be appended since element is present")}}function vt(z,V,te){var _e=z.childNodes||[],Oe=V.childNodes||[];if(V.nodeType===F.DOCUMENT_FRAGMENT_NODE){var tt=Oe.filter(ot);if(tt.length>1||e(Oe,nt))throw new K(D,"More than one element or text in fragment");if(tt.length===1&&!gt(z,te))throw new K(D,"Element in fragment can not be inserted before doctype")}if(ot(V)&&!gt(z,te))throw new K(D,"Only one element can be added and only after doctype");if(dt(V)){let Vi=function(zi){return dt(zi)&&zi!==te};var xi=Vi;if(e(_e,Vi))throw new K(D,"Only one doctype is allowed");var Ot=e(_e,ot);if(te&&_e.indexOf(Ot)<_e.indexOf(te))throw new K(D,"Doctype can only be inserted before an element")}}function jt(z,V,te,_e){je(z,V,te),z.nodeType===F.DOCUMENT_NODE&&(_e||bt)(z,V,te);var Oe=V.parentNode;if(Oe&&Oe.removeChild(V),V.nodeType===P){var tt=V.firstChild;if(tt==null)return V;var Ot=V.lastChild}else tt=Ot=V;var xi=te?te.previousSibling:z.lastChild;tt.previousSibling=xi,Ot.nextSibling=te,xi?xi.nextSibling=tt:z.firstChild=tt,te==null?z.lastChild=Ot:te.previousSibling=Ot;do{tt.parentNode=z;var Vi=z.ownerDocument||z;We(tt,Vi)}while(tt!==Ot&&(tt=tt.nextSibling));return Re(z.ownerDocument||z,z),V.nodeType==P&&(V.firstChild=V.lastChild=null),V}function We(z,V){if(z.ownerDocument!==V){if(z.ownerDocument=V,z.nodeType===p&&z.attributes)for(var te=0;te0&&he(te.documentElement,function(Oe){if(Oe!==te&&Oe.nodeType===p){var tt=Oe.getAttribute("class");if(tt){var Ot=z===tt;if(!Ot){var xi=a(tt);Ot=V.every(u(xi))}Ot&&_e.push(Oe)}}}),_e})},createElement:function(z){var V=new ge;V.ownerDocument=this,V.nodeName=z,V.tagName=z,V.localName=z,V.childNodes=new J;var te=V.attributes=new q;return te._ownerElement=V,V},createDocumentFragment:function(){var z=new Ft;return z.ownerDocument=this,z.childNodes=new J,z},createTextNode:function(z){var V=new Qe;return V.ownerDocument=this,V.appendData(z),V},createComment:function(z){var V=new mt;return V.ownerDocument=this,V.appendData(z),V},createCDATASection:function(z){var V=new ct;return V.ownerDocument=this,V.appendData(z),V},createProcessingInstruction:function(z,V){var te=new $t;return te.ownerDocument=this,te.tagName=te.nodeName=te.target=z,te.nodeValue=te.data=V,te},createAttribute:function(z){var V=new Je;return V.ownerDocument=this,V.name=z,V.nodeName=z,V.localName=z,V.specified=!0,V},createEntityReference:function(z){var V=new It;return V.ownerDocument=this,V.nodeName=z,V},createElementNS:function(z,V){var te=new ge,_e=V.split(":"),Oe=te.attributes=new q;return te.childNodes=new J,te.ownerDocument=this,te.nodeName=V,te.tagName=V,te.namespaceURI=z,_e.length==2?(te.prefix=_e[0],te.localName=_e[1]):te.localName=V,Oe._ownerElement=te,te},createAttributeNS:function(z,V){var te=new Je,_e=V.split(":");return te.ownerDocument=this,te.nodeName=V,te.name=V,te.namespaceURI=z,te.specified=!0,_e.length==2?(te.prefix=_e[0],te.localName=_e[1]):te.localName=V,te}},d(be,F);function ge(){this._nsMap={}}ge.prototype={nodeType:p,hasAttribute:function(z){return this.getAttributeNode(z)!=null},getAttribute:function(z){var V=this.getAttributeNode(z);return V&&V.value||""},getAttributeNode:function(z){return this.attributes.getNamedItem(z)},setAttribute:function(z,V){var te=this.ownerDocument.createAttribute(z);te.value=te.nodeValue=""+V,this.setAttributeNode(te)},removeAttribute:function(z){var V=this.getAttributeNode(z);V&&this.removeAttributeNode(V)},appendChild:function(z){return z.nodeType===P?this.insertBefore(z,null):ut(this,z)},setAttributeNode:function(z){return this.attributes.setNamedItem(z)},setAttributeNodeNS:function(z){return this.attributes.setNamedItemNS(z)},removeAttributeNode:function(z){return this.attributes.removeNamedItem(z.nodeName)},removeAttributeNS:function(z,V){var te=this.getAttributeNodeNS(z,V);te&&this.removeAttributeNode(te)},hasAttributeNS:function(z,V){return this.getAttributeNodeNS(z,V)!=null},getAttributeNS:function(z,V){var te=this.getAttributeNodeNS(z,V);return te&&te.value||""},setAttributeNS:function(z,V,te){var _e=this.ownerDocument.createAttributeNS(z,V);_e.value=_e.nodeValue=""+te,this.setAttributeNode(_e)},getAttributeNodeNS:function(z,V){return this.attributes.getNamedItemNS(z,V)},getElementsByTagName:function(z){return new ue(this,function(V){var te=[];return he(V,function(_e){_e!==V&&_e.nodeType==p&&(z==="*"||_e.tagName==z)&&te.push(_e)}),te})},getElementsByTagNameNS:function(z,V){return new ue(this,function(te){var _e=[];return he(te,function(Oe){Oe!==te&&Oe.nodeType===p&&(z==="*"||Oe.namespaceURI===z)&&(V==="*"||Oe.localName==V)&&_e.push(Oe)}),_e})}},be.prototype.getElementsByTagName=ge.prototype.getElementsByTagName,be.prototype.getElementsByTagNameNS=ge.prototype.getElementsByTagNameNS,d(ge,F);function Je(){}Je.prototype.nodeType=y,d(Je,F);function Ye(){}Ye.prototype={data:"",substringData:function(z,V){return this.data.substring(z,z+V)},appendData:function(z){z=this.data+z,this.nodeValue=this.data=z,this.length=z.length},insertData:function(z,V){this.replaceData(z,0,V)},appendChild:function(z){throw new Error(H[D])},deleteData:function(z,V){this.replaceData(z,V,"")},replaceData:function(z,V,te){var _e=this.data.substring(0,z),Oe=this.data.substring(z+V);te=_e+te+Oe,this.nodeValue=this.data=te,this.length=te.length}},d(Ye,F);function Qe(){}Qe.prototype={nodeName:"#text",nodeType:v,splitText:function(z){var V=this.data,te=V.substring(z);V=V.substring(0,z),this.data=this.nodeValue=V,this.length=V.length;var _e=this.ownerDocument.createTextNode(te);return this.parentNode&&this.parentNode.insertBefore(_e,this.nextSibling),_e}},d(Qe,Ye);function mt(){}mt.prototype={nodeName:"#comment",nodeType:I},d(mt,Ye);function ct(){}ct.prototype={nodeName:"#cdata-section",nodeType:b},d(ct,Ye);function et(){}et.prototype.nodeType=$,d(et,F);function Gt(){}Gt.prototype.nodeType=B,d(Gt,F);function Jt(){}Jt.prototype.nodeType=E,d(Jt,F);function It(){}It.prototype.nodeType=_,d(It,F);function Ft(){}Ft.prototype.nodeName="#document-fragment",Ft.prototype.nodeType=P,d(Ft,F);function $t(){}$t.prototype.nodeType=L,d($t,F);function Ke(){}Ke.prototype.serializeToString=function(z,V,te){return Lt.call(z,V,te)},F.prototype.toString=Lt;function Lt(z,V){var te=[],_e=this.nodeType==9&&this.documentElement||this,Oe=_e.prefix,tt=_e.namespaceURI;if(tt&&Oe==null){var Oe=_e.lookupPrefix(tt);if(Oe==null)var Ot=[{namespace:tt,prefix:null}]}return ci(this,te,z,V,Ot),te.join("")}function Qt(z,V,te){var _e=z.prefix||"",Oe=z.namespaceURI;if(!Oe||_e==="xml"&&Oe===t.XML||Oe===t.XMLNS)return!1;for(var tt=te.length;tt--;){var Ot=te[tt];if(Ot.prefix===_e)return Ot.namespace!==Oe}return!0}function Ut(z,V,te){z.push(" ",V,'="',te.replace(/[<>&"\t\n\r]/g,ee),'"')}function ci(z,V,te,_e,Oe){if(Oe||(Oe=[]),_e)if(z=_e(z),z){if(typeof z=="string"){V.push(z);return}}else return;switch(z.nodeType){case p:var tt=z.attributes,Ot=tt.length,ti=z.firstChild,xi=z.tagName;te=t.isHTML(z.namespaceURI)||te;var Vi=xi;if(!te&&!z.prefix&&z.namespaceURI){for(var zi,Oi=0;Oi=0;Ai--){var Ci=Oe[Ai];if(Ci.prefix===""&&Ci.namespace===z.namespaceURI){zi=Ci.namespace;break}}if(zi!==z.namespaceURI)for(var Ai=Oe.length-1;Ai>=0;Ai--){var Ci=Oe[Ai];if(Ci.namespace===z.namespaceURI){Ci.prefix&&(Vi=Ci.prefix+":"+xi);break}}}V.push("<",Vi);for(var Fi=0;Fi"),te&&/^script$/i.test(xi))for(;ti;)ti.data?V.push(ti.data):ci(ti,V,te,_e,Oe.slice()),ti=ti.nextSibling;else for(;ti;)ci(ti,V,te,_e,Oe.slice()),ti=ti.nextSibling;V.push("")}else V.push("/>");return;case R:case P:for(var ti=z.firstChild;ti;)ci(ti,V,te,_e,Oe.slice()),ti=ti.nextSibling;return;case y:return Ut(V,z.name,z.value);case v:return V.push(z.data.replace(/[<&>]/g,ee));case b:return V.push("");case I:return V.push("");case $:var Kt=z.publicId,Gs=z.systemId;if(V.push("");else if(Gs&&Gs!=".")V.push(" SYSTEM ",Gs,">");else{var qi=z.internalSubset;qi&&V.push(" [",qi,"]"),V.push(">")}return;case L:return V.push("");case _:return V.push("&",z.nodeName,";");default:V.push("??",z.nodeName)}}function vi(z,V,te){var _e;switch(V.nodeType){case p:_e=V.cloneNode(!1),_e.ownerDocument=z;case P:break;case y:te=!0;break}if(_e||(_e=V.cloneNode(!1)),_e.ownerDocument=z,_e.parentNode=null,te)for(var Oe=V.firstChild;Oe;)_e.appendChild(vi(z,Oe,te)),Oe=Oe.nextSibling;return _e}function ei(z,V,te){var _e=new V.constructor;for(var Oe in V)if(Object.prototype.hasOwnProperty.call(V,Oe)){var tt=V[Oe];typeof tt!="object"&&tt!=_e[Oe]&&(_e[Oe]=tt)}switch(V.childNodes&&(_e.childNodes=new J),_e.ownerDocument=z,_e.nodeType){case p:var Ot=V.attributes,xi=_e.attributes=new q,Vi=Ot.length;xi._ownerElement=_e;for(var zi=0;zi",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})(Fy)),Fy}var pm={},pE;function w3(){if(pE)return pm;pE=1;var s=Wp().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,a=2,u=3,c=4,d=5,f=6,p=7;function y(D,M){this.message=D,this.locator=M,Error.captureStackTrace&&Error.captureStackTrace(this,y)}y.prototype=new Error,y.prototype.name=y.name;function v(){}v.prototype={parse:function(D,M,W){var K=this.domBuilder;K.startDocument(),$(M,M={}),b(D,M,W,K,this.errorHandler),K.endDocument()}};function b(D,M,W,K,J){function ue(ut){if(ut>65535){ut-=65536;var ge=55296+(ut>>10),Je=56320+(ut&1023);return String.fromCharCode(ge,Je)}else return String.fromCharCode(ut)}function se(ut){var ge=ut.slice(1,-1);return Object.hasOwnProperty.call(W,ge)?W[ge]:ge.charAt(0)==="#"?ue(parseInt(ge.substr(1).replace("x","0x"))):(J.error("entity not found:"+ut),ut)}function q(ut){if(ut>be){var ge=D.substring(be,ut).replace(/&#?\w+;/g,se);F&&Y(be),K.characters(ge,0,ut-be),be=ut}}function Y(ut,ge){for(;ut>=Q&&(ge=oe.exec(D));)ie=ge.index,Q=ie+ge[0].length,F.lineNumber++;F.columnNumber=ut-ie+1}for(var ie=0,Q=0,oe=/.*(?:\r\n?|\n)|.*$/g,F=K.locator,ee=[{currentNSMap:M}],he={},be=0;;){try{var pe=D.indexOf("<",be);if(pe<0){if(!D.substr(be).match(/^\s*$/)){var Ce=K.doc,Re=Ce.createTextNode(D.substr(be));Ce.appendChild(Re),K.currentElement=Re}return}switch(pe>be&&q(pe),D.charAt(pe+1)){case"/":var je=D.indexOf(">",pe+3),Ze=D.substring(pe+2,je).replace(/[ \t\n\r]+$/g,""),Ge=ee.pop();je<0?(Ze=D.substring(pe+2).replace(/[\s<].*/,""),J.error("end tag name: "+Ze+" is not complete:"+Ge.tagName),je=pe+1+Ze.length):Ze.match(/\sbe?be=je:q(Math.max(pe,be)+1)}}function _(D,M){return M.lineNumber=D.lineNumber,M.columnNumber=D.columnNumber,M}function E(D,M,W,K,J,ue){function se(F,ee,he){W.attributeNames.hasOwnProperty(F)&&ue.fatalError("Attribute "+F+" redefined"),W.addValue(F,ee.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,J),he)}for(var q,Y,ie=++M,Q=n;;){var oe=D.charAt(ie);switch(oe){case"=":if(Q===r)q=D.slice(M,ie),Q=u;else if(Q===a)Q=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(Q===u||Q===r)if(Q===r&&(ue.warning('attribute value must after "="'),q=D.slice(M,ie)),M=ie+1,ie=D.indexOf(oe,M),ie>0)Y=D.slice(M,ie),se(q,Y,M-1),Q=d;else throw new Error("attribute value no end '"+oe+"' match");else if(Q==c)Y=D.slice(M,ie),se(q,Y,M),ue.warning('attribute "'+q+'" missed start quot('+oe+")!!"),M=ie+1,Q=d;else throw new Error('attribute value must after "="');break;case"/":switch(Q){case n:W.setTagName(D.slice(M,ie));case d:case f:case p:Q=p,W.closed=!0;case c:case r:break;case a:W.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return ue.error("unexpected end of input"),Q==n&&W.setTagName(D.slice(M,ie)),ie;case">":switch(Q){case n:W.setTagName(D.slice(M,ie));case d:case f:case p:break;case c:case r:Y=D.slice(M,ie),Y.slice(-1)==="/"&&(W.closed=!0,Y=Y.slice(0,-1));case a:Q===a&&(Y=q),Q==c?(ue.warning('attribute "'+Y+'" missed quot(")!'),se(q,Y,M)):((!s.isHTML(K[""])||!Y.match(/^(?:disabled|checked|selected)$/i))&&ue.warning('attribute "'+Y+'" missed value!! "'+Y+'" instead!!'),se(Y,Y,M));break;case u:throw new Error("attribute value missed!!")}return ie;case"€":oe=" ";default:if(oe<=" ")switch(Q){case n:W.setTagName(D.slice(M,ie)),Q=f;break;case r:q=D.slice(M,ie),Q=a;break;case c:var Y=D.slice(M,ie);ue.warning('attribute "'+Y+'" missed quot(")!!'),se(q,Y,M);case d:Q=f;break}else switch(Q){case a:W.tagName,(!s.isHTML(K[""])||!q.match(/^(?:disabled|checked|selected)$/i))&&ue.warning('attribute "'+q+'" missed value!! "'+q+'" instead2!!'),se(q,q,M),M=ie,Q=r;break;case d:ue.warning('attribute space is required"'+q+'"!!');case f:Q=r,M=ie;break;case u:Q=c,M=ie;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}ie++}}function L(D,M,W){for(var K=D.tagName,J=null,oe=D.length;oe--;){var ue=D[oe],se=ue.qName,q=ue.value,F=se.indexOf(":");if(F>0)var Y=ue.prefix=se.slice(0,F),ie=se.slice(F+1),Q=Y==="xmlns"&&ie;else ie=se,Y=null,Q=se==="xmlns"&&"";ue.localName=ie,Q!==!1&&(J==null&&(J={},$(W,W={})),W[Q]=J[Q]=q,ue.uri=s.XMLNS,M.startPrefixMapping(Q,q))}for(var oe=D.length;oe--;){ue=D[oe];var Y=ue.prefix;Y&&(Y==="xml"&&(ue.uri=s.XML),Y!=="xmlns"&&(ue.uri=W[Y||""]))}var F=K.indexOf(":");F>0?(Y=D.prefix=K.slice(0,F),ie=D.localName=K.slice(F+1)):(Y=null,ie=D.localName=K);var ee=D.uri=W[Y||""];if(M.startElement(ee,ie,K,D),D.closed){if(M.endElement(ee,ie,K),J)for(Y in J)Object.prototype.hasOwnProperty.call(J,Y)&&M.endPrefixMapping(Y)}else return D.currentNSMap=W,D.localNSMap=J,!0}function I(D,M,W,K,J){if(/^(?:script|textarea)$/i.test(W)){var ue=D.indexOf("",M),se=D.substring(M+1,ue);if(/[&<]/.test(se))return/^script$/i.test(W)?(J.characters(se,0,se.length),ue):(se=se.replace(/&#?\w+;/g,K),J.characters(se,0,se.length),ue)}return M+1}function R(D,M,W,K){var J=K[W];return J==null&&(J=D.lastIndexOf(""),J",M+4);return ue>M?(W.comment(D,M+4,ue-M-4),ue+3):(K.error("Unclosed comment"),-1)}else return-1;default:if(D.substr(M+3,6)=="CDATA["){var ue=D.indexOf("]]>",M+9);return W.startCDATA(),W.characters(D,M+9,ue-M-9),W.endCDATA(),ue+3}var se=H(D,M),q=se.length;if(q>1&&/!doctype/i.test(se[0][0])){var Y=se[1][0],ie=!1,Q=!1;q>3&&(/^public$/i.test(se[2][0])?(ie=se[3][0],Q=q>4&&se[4][0]):/^system$/i.test(se[2][0])&&(Q=se[3][0]));var oe=se[q-1];return W.startDTD(Y,ie,Q),W.endDTD(),oe.index+oe[0].length}}return-1}function B(D,M,W){var K=D.indexOf("?>",M);if(K){var J=D.substring(M,K).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return J?(J[0].length,W.processingInstruction(J[1],J[2]),K+2):-1}return-1}function O(){this.attributeNames={}}O.prototype={setTagName:function(D){if(!i.test(D))throw new Error("invalid tagName:"+D);this.tagName=D},addValue:function(D,M,W){if(!i.test(D))throw new Error("invalid attribute:"+D);this.attributeNames[D]=this.length,this[this.length++]={qName:D,value:M,offset:W}},length:0,getLocalName:function(D){return this[D].localName},getLocator:function(D){return this[D].locator},getQName:function(D){return this[D].qName},getURI:function(D){return this[D].uri},getValue:function(D){return this[D].value}};function H(D,M){var W,K=[],J=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(J.lastIndex=M,J.exec(D);W=J.exec(D);)if(K.push(W),W[1])return K}return pm.XMLReader=v,pm.ParseError=y,pm}var gE;function A3(){if(gE)return Wd;gE=1;var s=Wp(),e=WA(),t=E3(),i=w3(),n=e.DOMImplementation,r=s.NAMESPACE,a=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,R=new u,$=I.domBuilder||new p,P=I.errorHandler,B=I.locator,O=I.xmlns||{},H=/\/x?html?$/.test(L),D=H?t.HTML_ENTITIES:t.XML_ENTITIES;B&&$.setDocumentLocator(B),R.errorHandler=f(P,$,B),R.domBuilder=I.domBuilder||$,H&&(O[""]=r.HTML),O.xml=O.xml||r.XML;var M=I.normalizeLineEndings||c;return E&&typeof E=="string"?R.parse(M(E),O,D):R.errorHandler.error("invalid doc source"),$.doc};function f(E,L,I){if(!E){if(L instanceof p)return L;E=L}var R={},$=E instanceof Function;I=I||{};function P(B){var O=E[B];!O&&$&&(O=E.length==2?function(H){E(B,H)}:E),R[B]=O&&function(H){O("[xmldom "+B+"] "+H+v(I))}||function(){}}return P("warning"),P("error"),P("fatalError"),R}function p(){this.cdata=!1}function y(E,L){L.lineNumber=E.lineNumber,L.columnNumber=E.columnNumber}p.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(E,L,I,R){var $=this.doc,P=$.createElementNS(E,I||L),B=R.length;_(this,P),this.currentElement=P,this.locator&&y(this.locator,P);for(var O=0;O=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){p.prototype[E]=function(){return null}});function _(E,L){E.currentElement?E.currentElement.appendChild(L):E.doc.appendChild(L)}return Wd.__DOMHandler=p,Wd.normalizeLineEndings=c,Wd.DOMParser=d,Wd}var yE;function C3(){if(yE)return Kd;yE=1;var s=WA();return Kd.DOMImplementation=s.DOMImplementation,Kd.XMLSerializer=s.XMLSerializer,Kd.DOMParser=A3().DOMParser,Kd}var k3=C3();const vE=s=>!!s&&typeof s=="object",nn=(...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]):vE(e[i])&&vE(t[i])?e[i]=nn(e[i],t[i]):e[i]=t[i]}),e),{}),YA=s=>Object.keys(s).map(e=>s[e]),D3=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),XA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),R3=(s,e)=>YA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var Lc={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 Eh=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:Kp(s||"",e)};if(t||i){const a=(t||i).split("-");let u=fe.BigInt?fe.BigInt(a[0]):parseInt(a[0],10),c=fe.BigInt?fe.BigInt(a[1]):parseInt(a[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=fe.BigInt(s.offset)+fe.BigInt(s.length)-fe.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},xE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),N3={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=xE(s.endNumber),a=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/a}:{start:0,end:i/a}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:a=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=xE(s.endNumber),f=(e+t)/1e3,p=i+a,v=f+u-p,b=Math.ceil(v*n/r),_=Math.floor((f-p-c)*n/r),E=Math.floor((f-p)*n/r);return{start:Math.max(0,_),end:typeof d=="number"?d:Math.min(b,E)}}},O3=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}},rb=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:a,end:u}=N3[e](s),c=D3(a,u).map(O3(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},QA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:a,number:u=0,duration:c}=s;if(!e)throw new Error(Lc.NO_BASE_URL);const d=Eh({baseUrl:e,source:t.sourceURL,range:t.range}),f=Eh({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const p=rb(s);p.length&&(f.duration=p[0].duration,f.timeline=p[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=a||r,f.number=u,[f]},ab=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,a=s.sidx.byterange,u=a.offset+a.length,c=e.timescale,d=e.references.filter(E=>E.referenceType!==1),f=[],p=s.endList?"static":"dynamic",y=s.sidx.timeline;let v=y,b=s.mediaSequence||0,_;typeof e.firstOffset=="bigint"?_=fe.BigInt(u)+e.firstOffset:_=u+e.firstOffset;for(let E=0;ER3(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),B3=(s,e)=>{for(let t=0;t{let e=[];return S3(s,M3,(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})},F3=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=B3(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],a=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[a].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),TE({playlist:i,mediaSequence:n.segments[a].number})})},U3=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(bE(s)),i=e.playlists.concat(bE(e));return e.timelineStarts=ZA([s.timelineStarts,e.timelineStarts]),F3({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},Yp=s=>s&&s.uri+"-"+I3(s.byterange),Uy=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=YA(i.reduce((r,a)=>{const u=a.attributes.id+(a.attributes.lang||"");return r[u]?(a.segments&&(a.segments[0]&&(a.segments[0].discontinuity=!0),r[u].segments.push(...a.segments)),a.attributes.contentProtection&&(r[u].attributes.contentProtection=a.attributes.contentProtection)):(r[u]=a,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:a.attributes.periodStart,timeline:a.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=L3(i.segments||[],"discontinuity"),i))},ob=(s,e)=>{const t=Yp(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&ab(s,i,s.sidx.resolvedUri),s},j3=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=ob(s[t],e);return s},$3=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},a)=>{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),a&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},H3=({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 a={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&&(a.attributes.serviceLocation=s.serviceLocation),a},G3=(s,e={},t=!1)=>{let i;const n=s.reduce((r,a)=>{const u=a.attributes.role&&a.attributes.role.value||"",c=a.attributes.lang||"";let d=a.attributes.label||"main";if(c&&!a.attributes.label){const p=u?` (${u})`:"";d=`${a.attributes.lang}${p}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=ob($3(a,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=a,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},V3=(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(ob(H3(i),e)),t},{}),z3=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),{}),q3=({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},K3=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",W3=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",Y3=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",X3=(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})})},_E=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],Q3=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:a,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=Uy(s.filter(K3)).map(q3),p=Uy(s.filter(W3)),y=Uy(s.filter(Y3)),v=s.map($=>$.attributes.captionServices).filter(Boolean),b={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:a,playlists:j3(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=p.length?G3(p,i,_):null,L=y.length?V3(y,i):null,I=f.concat(_E(E),_E(L)),R=I.map(({timelineStarts:$})=>$);return b.timelineStarts=ZA(R),X3(I,b.timelineStarts),E&&(b.mediaGroups.AUDIO.audio=E),L&&(b.mediaGroups.SUBTITLES.subs=L),v.length&&(b.mediaGroups["CLOSED-CAPTIONS"].cc=z3(v)),n?U3({oldManifest:n,newManifest:b}):b},Z3=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:a=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,y=d+c-f;return Math.ceil((y*a-e)/t)},JA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:a=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let p=0;pf&&(f=_);let E;if(b<0){const R=p+1;R===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?E=Z3(s,f,v):E=(r*a-f)/v:E=(e[R].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}`},SE=(s,e)=>s.replace(J3,eP(e)),tP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?rb(s):JA(s,e),iP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=Eh({baseUrl:s.baseUrl,source:SE(i.sourceURL,t),range:i.range});return tP(s,e).map(a=>{t.Number=a.number,t.Time=a.time;const u=SE(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(a.time-d)/c;return{uri:u,timeline:a.timeline,duration:a.duration,resolvedUri:Kp(s.baseUrl||"",u),map:n,number:a.number,presentationTime:f}})},sP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=Eh({baseUrl:t,source:i.sourceURL,range:i.range}),r=Eh({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},nP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(Lc.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>sP(s,c));let a;return t&&(a=rb(s)),e&&(a=JA(s,e)),a.map((c,d)=>{if(r[d]){const f=r[d],p=s.timescale||1,y=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-y)/p,f}}).filter(c=>c)},rP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=iP,t=nn(s,e.template)):e.base?(i=QA,t=nn(s,e.base)):e.list&&(i=nP,t=nn(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:a,timescale:u=1}=t;t.duration=a/u}else r.length?t.duration=r.reduce((a,u)=>Math.max(a,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},aP=s=>s.map(rP),gs=(s,e)=>XA(s.childNodes).filter(({tagName:t})=>t===e),Uh=s=>s.textContent.trim(),oP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),qu=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,y,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(p||0)*3600+parseFloat(y||0)*60+parseFloat(v||0)},lP=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),EE={mediaPresentationDuration(s){return qu(s)},availabilityStartTime(s){return lP(s)/1e3},minimumUpdatePeriod(s){return qu(s)},suggestedPresentationDelay(s){return qu(s)},type(s){return s},timeShiftBufferDepth(s){return qu(s)},start(s){return qu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return oP(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)?qu(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}},Hs=s=>s&&s.attributes?XA(s.attributes).reduce((e,t)=>{const i=EE[t.name]||EE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},uP={"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"},Xp=(s,e)=>e.length?Dc(s.map(function(t){return e.map(function(i){const n=Uh(i),r=Kp(t.baseUrl,n),a=nn(Hs(i),{baseUrl:r});return r!==n&&!a.serviceLocation&&t.serviceLocation&&(a.serviceLocation=t.serviceLocation),a})})):s,lb=s=>{const e=gs(s,"SegmentTemplate")[0],t=gs(s,"SegmentList")[0],i=t&&gs(t,"SegmentURL").map(p=>nn({tag:"SegmentURL"},Hs(p))),n=gs(s,"SegmentBase")[0],r=t||e,a=r&&gs(r,"SegmentTimeline")[0],u=t||n||e,c=u&&gs(u,"Initialization")[0],d=e&&Hs(e);d&&c?d.initialization=c&&Hs(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:a&&gs(a,"S").map(p=>Hs(p)),list:t&&nn(Hs(t),{segmentUrls:i,initialization:Hs(c)}),base:n&&nn(Hs(n),{initialization:Hs(c)})};return Object.keys(f).forEach(p=>{f[p]||delete f[p]}),f},cP=(s,e,t)=>i=>{const n=gs(i,"BaseURL"),r=Xp(e,n),a=nn(s,Hs(i)),u=lb(i);return r.map(c=>({segmentInfo:nn(t,u),attributes:nn(a,c)}))},dP=s=>s.reduce((e,t)=>{const i=Hs(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=uP[i.schemeIdUri];if(n){e[n]={attributes:i};const r=gs(t,"cenc:pssh")[0];if(r){const a=Uh(r);e[n].pssh=a&&HA(a)}}return e},{}),hP=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(a=>{const[u,c]=a.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})},fP=s=>Dc(gs(s.node,"EventStream").map(e=>{const t=Hs(e),i=t.schemeIdUri;return gs(e,"Event").map(n=>{const r=Hs(n),a=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=a/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:Uh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),mP=(s,e,t)=>i=>{const n=Hs(i),r=Xp(e,gs(i,"BaseURL")),a=gs(i,"Role")[0],u={role:Hs(a)};let c=nn(s,n,u);const d=gs(i,"Accessibility")[0],f=hP(Hs(d));f&&(c=nn(c,{captionServices:f}));const p=gs(i,"Label")[0];if(p&&p.childNodes.length){const E=p.childNodes[0].nodeValue.trim();c=nn(c,{label:E})}const y=dP(gs(i,"ContentProtection"));Object.keys(y).length&&(c=nn(c,{contentProtection:y}));const v=lb(i),b=gs(i,"Representation"),_=nn(t,v);return Dc(b.map(cP(c,r,_)))},pP=(s,e)=>(t,i)=>{const n=Xp(e,gs(t.node,"BaseURL")),r=nn(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const a=gs(t.node,"AdaptationSet"),u=lb(t.node);return Dc(a.map(mP(r,n,u)))},gP=(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=nn({serverURL:Uh(s[0])},Hs(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},yP=({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,vP=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,a=gs(s,"Period");if(!a.length)throw new Error(Lc.INVALID_NUMBER_OF_PERIOD);const u=gs(s,"Location"),c=Hs(s),d=Xp([{baseUrl:t}],gs(s,"BaseURL")),f=gs(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(Uh));const p=[];return a.forEach((y,v)=>{const b=Hs(y),_=p[v-1];b.start=yP({attributes:b,priorPeriodAttributes:_?_.attributes:null,mpdType:c.type}),p.push({node:y,attributes:b})}),{locations:c.locations,contentSteeringInfo:gP(f,r),representationInfo:Dc(p.map(pP(c,d))),eventStream:Dc(p.map(fP))}},eC=s=>{if(s==="")throw new Error(Lc.DASH_EMPTY_MANIFEST);const e=new k3.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(Lc.DASH_INVALID_XML);return i},xP=s=>{const e=gs(s,"UTCTiming")[0];if(!e)return null;const t=Hs(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(Lc.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},bP=(s,e={})=>{const t=vP(eC(s),e),i=aP(t.representationInfo);return Q3({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},TP=s=>xP(eC(s));var jy,wE;function _P(){if(wE)return jy;wE=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,a--)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 $y=e,$y}var EP=SP();const wP=jc(EP);var AP=qt([73,68,51]),CP=function(e,t){t===void 0&&(t=0),e=qt(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},rh=function s(e,t){return t===void 0&&(t=0),e=qt(e),e.length-t<10||!ps(e,AP,{offset:t})?t:(t+=CP(e,t),s(e,t))},CE=function(e){return typeof e=="string"?KA(e):e},kP=function(e){return Array.isArray(e)?e.map(function(t){return CE(t)}):[CE(e)]},DP=function s(e,t,i){i===void 0&&(i=!1),t=kP(t),e=qt(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(a===0)break;var c=r+a;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);ps(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},gm={EBML:qt([26,69,223,163]),DocType:qt([66,130]),Segment:qt([24,83,128,103]),SegmentInfo:qt([21,73,169,102]),Tracks:qt([22,84,174,107]),Track:qt([174]),TrackNumber:qt([215]),DefaultDuration:qt([35,227,131]),TrackEntry:qt([174]),TrackType:qt([131]),FlagDefault:qt([136]),CodecID:qt([134]),CodecPrivate:qt([99,162]),VideoTrack:qt([224]),AudioTrack:qt([225]),Cluster:qt([31,67,182,117]),Timestamp:qt([231]),TimestampScale:qt([42,215,177]),BlockGroup:qt([160]),BlockDuration:qt([155]),Block:qt([161]),SimpleBlock:qt([163])},ix=[128,64,32,16,8,4,2,1],LP=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=np(t,i,!1);if(ps(e.bytes,n.bytes))return i;var r=np(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},DE=function s(e,t){t=RP(t),e=qt(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+a.value,d=e.subarray(u,c);ps(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+a.length+d.length;n+=f}return i},NP=qt([0,0,0,1]),OP=qt([0,0,1]),MP=qt([0,0,3]),PP=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(a=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},BP=function(e,t,i){return tC(e,"h264",t,i)},FP=function(e,t,i){return tC(e,"h265",t,i)},kn={webm:qt([119,101,98,109]),matroska:qt([109,97,116,114,111,115,107,97]),flac:qt([102,76,97,67]),ogg:qt([79,103,103,83]),ac3:qt([11,119]),riff:qt([82,73,70,70]),avi:qt([65,86,73]),wav:qt([87,65,86,69]),"3gp":qt([102,116,121,112,51,103]),mp4:qt([102,116,121,112]),fmp4:qt([115,116,121,112]),mov:qt([102,116,121,112,113,116]),moov:qt([109,111,111,118]),moof:qt([109,111,111,102])},Rc={aac:function(e){var t=rh(e);return ps(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=rh(e);return ps(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=DE(e,[gm.EBML,gm.DocType])[0];return ps(t,kn.webm)},mkv:function(e){var t=DE(e,[gm.EBML,gm.DocType])[0];return ps(t,kn.matroska)},mp4:function(e){if(Rc["3gp"](e)||Rc.mov(e))return!1;if(ps(e,kn.mp4,{offset:4})||ps(e,kn.fmp4,{offset:4})||ps(e,kn.moof,{offset:4})||ps(e,kn.moov,{offset:4}))return!0},mov:function(e){return ps(e,kn.mov,{offset:4})},"3gp":function(e){return ps(e,kn["3gp"],{offset:4})},ac3:function(e){var t=rh(e);return ps(e,kn.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},Hy,LE;function $P(){if(LE)return Hy;LE=1;var s=9e4,e,t,i,n,r,a,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))},a=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},Hy={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:a,metadataTsToSeconds:u},Hy}var eu=$P();var nx="8.23.4";const oo={},ml=function(s,e){return oo[s]=oo[s]||[],e&&(oo[s]=oo[s].concat(e)),oo[s]},HP=function(s,e){ml(s,e)},iC=function(s,e){const t=ml(s).indexOf(e);return t<=-1?!1:(oo[s]=oo[s].slice(),oo[s].splice(t,1),!0)},GP=function(s,e){ml(s,[].concat(e).map(t=>{const i=(...n)=>(iC(s,i),t(...n));return i}))},rp={prefixed:!0},Um=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],RE=Um[0];let ah;for(let s=0;s(i,n,r)=>{const a=e.levels[n],u=new RegExp(`^(${a})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),Wn){Wn.push([].concat(r));const f=Wn.length-1e3;Wn.splice(0,f>0?f:0)}if(!fe.console)return;let d=fe.console[i];!d&&i==="debug"&&(d=fe.console.info||fe.console.log),!(!d||!a||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](fe.console,r)};function rx(s,e=":",t=""){let i="info",n;function r(...a){n("log",i,a)}return n=VP(s,r,t),r.createLogger=(a,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,p=`${s} ${d} ${a}`;return rx(p,d,f)},r.createNewLogger=(a,u,c)=>rx(a,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=a=>{if(typeof a=="string"){if(!r.levels.hasOwnProperty(a))throw new Error(`"${a}" in not a valid log level`);i=a}return i},r.history=()=>Wn?[].concat(Wn):[],r.history.filter=a=>(Wn||[]).filter(u=>new RegExp(`.*${a}.*`).test(u[0])),r.history.clear=()=>{Wn&&(Wn.length=0)},r.history.disable=()=>{Wn!==null&&(Wn.length=0,Wn=null)},r.history.enable=()=>{Wn===null&&(Wn=[])},r.error=(...a)=>n("error",i,a),r.warn=(...a)=>n("warn",i,a),r.debug=(...a)=>n("debug",i,a),r}const fi=rx("VIDEOJS"),sC=fi.createLogger,zP=Object.prototype.toString,nC=function(s){return ka(s)?Object.keys(s):[]};function dc(s,e){nC(s).forEach(t=>e(s[t],t))}function rC(s,e,t=0){return nC(s).reduce((i,n)=>e(i,s[n],n),t)}function ka(s){return!!s&&typeof s=="object"}function Ic(s){return ka(s)&&zP.call(s)==="[object Object]"&&s.constructor===Object}function Xi(...s){const e={};return s.forEach(t=>{t&&dc(t,(i,n)=>{if(!Ic(i)){e[n]=i;return}Ic(e[n])||(e[n]={}),e[n]=Xi(e[n],i)})}),e}function aC(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function Qp(s,e,t,i=!0){const n=a=>Object.defineProperty(s,e,{value:a,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const a=t();return n(a),a}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var qP=Object.freeze({__proto__:null,each:dc,reduce:rC,isObject:ka,isPlain:Ic,merge:Xi,values:aC,defineLazyProperty:Qp});let cb=!1,oC=null,Yr=!1,lC,uC=!1,hc=!1,fc=!1,Da=!1,db=null,Zp=null;const KP=!!(fe.cast&&fe.cast.framework&&fe.cast.framework.CastReceiverContext);let cC=null,ap=!1,Jp=!1,op=!1,e0=!1,lp=!1,up=!1,cp=!1;const wh=!!($c()&&("ontouchstart"in fe||fe.navigator.maxTouchPoints||fe.DocumentTouch&&fe.document instanceof fe.DocumentTouch)),Jo=fe.navigator&&fe.navigator.userAgentData;Jo&&Jo.platform&&Jo.brands&&(Yr=Jo.platform==="Android",hc=!!Jo.brands.find(s=>s.brand==="Microsoft Edge"),fc=!!Jo.brands.find(s=>s.brand==="Chromium"),Da=!hc&&fc,db=Zp=(Jo.brands.find(s=>s.brand==="Chromium")||{}).version||null,Jp=Jo.platform==="Windows");if(!fc){const s=fe.navigator&&fe.navigator.userAgent||"";cb=/iPod/i.test(s),oC=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),Yr=/Android/i.test(s),lC=(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})(),uC=/Firefox/i.test(s),hc=/Edg/i.test(s),fc=/Chrome/i.test(s)||/CriOS/i.test(s),Da=!hc&&fc,db=Zp=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),cC=(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})(),lp=/Tizen/i.test(s),up=/Web0S/i.test(s),cp=lp||up,ap=/Safari/i.test(s)&&!Da&&!Yr&&!hc&&!cp,Jp=/Windows/i.test(s),op=/iPad/i.test(s)||ap&&wh&&!/iPhone/i.test(s),e0=/iPhone/i.test(s)&&!op}const Tn=e0||op||cb,t0=(ap||Tn)&&!Da;var dC=Object.freeze({__proto__:null,get IS_IPOD(){return cb},get IOS_VERSION(){return oC},get IS_ANDROID(){return Yr},get ANDROID_VERSION(){return lC},get IS_FIREFOX(){return uC},get IS_EDGE(){return hc},get IS_CHROMIUM(){return fc},get IS_CHROME(){return Da},get CHROMIUM_VERSION(){return db},get CHROME_VERSION(){return Zp},IS_CHROMECAST_RECEIVER:KP,get IE_VERSION(){return cC},get IS_SAFARI(){return ap},get IS_WINDOWS(){return Jp},get IS_IPAD(){return op},get IS_IPHONE(){return e0},get IS_TIZEN(){return lp},get IS_WEBOS(){return up},get IS_SMART_TV(){return cp},TOUCH_ENABLED:wh,IS_IOS:Tn,IS_ANY_SAFARI:t0});function IE(s){return typeof s=="string"&&!!s.trim()}function WP(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function $c(){return at===fe.document}function Hc(s){return ka(s)&&s.nodeType===1}function hC(){try{return fe.parent!==fe.self}catch{return!0}}function fC(s){return function(e,t){if(!IE(e))return at[s](null);IE(t)&&(t=at.querySelector(t));const i=Hc(t)?t:at;return i[s]&&i[s](e)}}function Xt(s="div",e={},t={},i){const n=at.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const a=e[r];r==="textContent"?vl(n,a):(n[r]!==a||r==="tabIndex")&&(n[r]=a)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&hb(n,i),n}function vl(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function ax(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function ph(s,e){return WP(e),s.classList.contains(e)}function su(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function i0(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(fi.warn("removeClass was called with an element that doesn't exist"),null)}function mC(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 pC(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 rl(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 a=i[n].value;t.includes(r)&&(a=a!==null),e[r]=a}}return e}function gC(s,e){return s.getAttribute(e)}function Nc(s,e,t){s.setAttribute(e,t)}function s0(s,e){s.removeAttribute(e)}function yC(){at.body.focus(),at.onselectstart=function(){return!1}}function vC(){at.onselectstart=function(){return!0}}function Oc(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(Mc(s,"height"))),t.width||(t.width=parseFloat(Mc(s,"width"))),t}}function Ah(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!==at[rp.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function n0(s,e){const t={x:0,y:0};if(Tn){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const p=Mc(f,"transform");if(/^matrix/.test(p)){const y=p.slice(7,-1).split(/,\s/).map(Number);t.x+=y[4],t.y+=y[5]}else if(/^matrix3d/.test(p)){const y=p.slice(9,-1).split(/,\s/).map(Number);t.x+=y[12],t.y+=y[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&fe.WebKitCSSMatrix){const y=fe.getComputedStyle(f.assignedSlot.parentElement).transform,v=new fe.WebKitCSSMatrix(y);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=Ah(e.target),r=Ah(s),a=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,Tn&&(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/a)),i}function xC(s){return ka(s)&&s.nodeType===3}function r0(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function bC(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),Hc(e)||xC(e))return e;if(typeof e=="string"&&/\S/.test(e))return at.createTextNode(e)}).filter(e=>e)}function hb(s,e){return bC(e).forEach(t=>s.appendChild(t)),s}function TC(s,e){return hb(r0(s),e)}function Ch(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 pl=fC("querySelector"),_C=fC("querySelectorAll");function Mc(s,e){if(!s||!e)return"";if(typeof fe.getComputedStyle=="function"){let t;try{t=fe.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function SC(s){[...at.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=at.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=at.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var EC=Object.freeze({__proto__:null,isReal:$c,isEl:Hc,isInFrame:hC,createEl:Xt,textContent:vl,prependTo:ax,hasClass:ph,addClass:su,removeClass:i0,toggleClass:mC,setAttributes:pC,getAttributes:rl,getAttribute:gC,setAttribute:Nc,removeAttribute:s0,blockTextSelection:yC,unblockTextSelection:vC,getBoundingClientRect:Oc,findPosition:Ah,getPointerPosition:n0,isTextNode:xC,emptyEl:r0,normalizeContent:bC,appendContent:hb,insertContent:TC,isSingleLeftClick:Ch,$:pl,$$:_C,computedStyle:Mc,copyStyleSheetsToWindow:SC});let wC=!1,ox;const YP=function(){if(ox.options.autoSetup===!1)return;const s=Array.prototype.slice.call(at.getElementsByTagName("video")),e=Array.prototype.slice.call(at.getElementsByTagName("audio")),t=Array.prototype.slice.call(at.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 _n(s,e,t){if(!Rn.has(s))return;const i=Rn.get(s);if(!i.handlers)return;if(Array.isArray(e))return fb(_n,s,e,t);const n=function(a,u){i.handlers[u]=[],NE(a,u)};if(e===void 0){for(const a in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},a)&&n(s,a);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let a=0;a=e&&(s(...n),t=r)}},kC=function(s,e,t,i=fe){let n;const r=()=>{i.clearTimeout(n),n=null},a=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 a.cancel=r,a};var t4=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:Rr,bind_:os,throttle:La,debounce:kC});let Yd;class Tr{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},br(this,e,t),this.addEventListener=i}off(e,t){_n(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},o0(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},mb(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=a0(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Gc(this,e)}queueTrigger(e){Yd||(Yd=new Map);const t=e.type||e;let i=Yd.get(this);i||(i=new Map,Yd.set(this,i));const n=i.get(t);i.delete(t),fe.clearTimeout(n);const r=fe.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,Yd.delete(this)),this.trigger(e)},0);i.set(t,r)}}Tr.prototype.allowedEvents_={};Tr.prototype.addEventListener=Tr.prototype.on;Tr.prototype.removeEventListener=Tr.prototype.off;Tr.prototype.dispatchEvent=Tr.prototype.trigger;const l0=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,ho=s=>s instanceof Tr||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),i4=(s,e)=>{ho(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},cx=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,dp=(s,e,t)=>{if(!s||!s.nodeName&&!ho(s))throw new Error(`Invalid target for ${l0(e)}#${t}; must be a DOM node or evented object.`)},DC=(s,e,t)=>{if(!cx(s))throw new Error(`Invalid event type for ${l0(e)}#${t}; must be a non-empty string or array.`)},LC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${l0(e)}#${t}; must be a function.`)},Gy=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,a;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,a]=e):(n=e[0],r=e[1],a=e[2]),dp(n,s,t),DC(r,s,t),LC(a,s,t),a=os(s,a),{isTargetingSelf:i,target:n,type:r,listener:a}},Gl=(s,e,t,i)=>{dp(s,s,e),s.nodeName?e4[e](s,t,i):s[e](t,i)},s4={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Gy(this,s,"on");if(Gl(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const a=()=>this.off("dispose",r);a.guid=n.guid,Gl(this,"on","dispose",r),Gl(t,"on","dispose",a)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Gy(this,s,"one");if(e)Gl(t,"one",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,Gl(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=Gy(this,s,"any");if(e)Gl(t,"any",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,Gl(t,"any",i,r)}},off(s,e,t){if(!s||cx(s))_n(this.eventBusEl_,s,e);else{const i=s,n=e;dp(i,this,"off"),DC(n,this,"off"),LC(t,this,"off"),t=os(this,t),this.off("dispose",t),i.nodeName?(_n(i,n,t),_n(i,"dispose",t)):ho(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){dp(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!cx(t))throw new Error(`Invalid event type for ${l0(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Gc(this.eventBusEl_,s,e)}};function pb(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_=Xt("span",{className:"vjs-event-bus"});return Object.assign(s,s4),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&Rn.has(i)&&Rn.delete(i)}),fe.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const n4={state:{},setState(s){typeof s=="function"&&(s=s());let e;return dc(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&ho(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function RC(s,e){return Object.assign(s,n4),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&ho(s)&&s.on("statechanged",s.handleStateChanged),s}const gh=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},Cs=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},IC=function(s,e){return Cs(s)===Cs(e)};var r4=Object.freeze({__proto__:null,toLowerCase:gh,toTitleCase:Cs,titleCaseEquals:IC});class Fe{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=Xi({},this.options_),t=this.options_=Xi(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_${Lr()}`}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&&(pb(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),RC(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_=Xi(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return Xt(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),a=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return a&&a[e]?d=a[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,p){const y=t[p-1];let v=y;return typeof y>"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_[Cs(e.name())]=null,this.childNameIndex_[gh(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=a=>{const u=a.name;let c=a.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=Fe.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(a){return!n.some(function(u){return typeof u=="string"?a===u:a===u.name})})).map(a=>{let u,c;return typeof a=="string"?(u=a,c=e[u]||this.options_[u]||{}):(u=a.name,c=a),{name:u,opts:c}}).filter(a=>{const u=Fe.getComponent(a.opts.componentClass||Cs(a.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 pl(e,t||this.contentEl())}$$(e,t){return _C(e,t||this.contentEl())}hasClass(e){return ph(this.el_,e)}addClass(...e){su(this.el_,...e)}removeClass(...e){i0(this.el_,...e)}toggleClass(e,t){mC(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 gC(this.el_,e)}setAttribute(e,t){Nc(this.el_,e,t)}removeAttribute(e){s0(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"+Cs(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Mc(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${Cs(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=fe.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 a=function(){r=!1};this.on("touchleave",a),this.on("touchcancel",a),this.on("touchend",function(u){t=null,r===!0&&fe.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),fe.clearTimeout(e)),e}setInterval(e,t){e=os(this,e),this.clearTimersOnDispose_();const i=fe.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),fe.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=os(this,e),t=fe.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=os(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),fe.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 a=fe.getComputedStyle(r,null),u=a.getPropertyValue("visibility");return a.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||fe.getComputedStyle(r).height==="0px"||fe.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const a={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(a.x<0||a.x>(at.documentElement.clientWidth||fe.innerWidth)||a.y<0||a.y>(at.documentElement.clientHeight||fe.innerHeight))return!1;let u=at.elementFromPoint(a.x,a.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=Fe.getComponent("Tech"),n=i&&i.isTech(t),r=Fe===t||Fe.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=Cs(e),Fe.components_||(Fe.components_={});const a=Fe.getComponent("Player");if(e==="Player"&&a&&a.players){const u=a.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 OE(s,e,t,i){return a4(s,i,t.length-1),t[i][e]}function Vy(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:OE.bind(null,"start",0,s),end:OE.bind(null,"end",1,s)},fe.Symbol&&fe.Symbol.iterator&&(e[fe.Symbol.iterator]=()=>(s||[]).values()),e}function Wr(s,e){return Array.isArray(s)?Vy(s):s===void 0||e===void 0?Vy():Vy([[s,e]])}const NC=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),a=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||a>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let gb=NC;function OC(s){gb=s}function MC(){gb=NC}function uu(s,e=s){return gb(s,e)}var o4=Object.freeze({__proto__:null,createTimeRanges:Wr,createTimeRange:Wr,setFormatTime:OC,resetFormatTime:MC,formatTime:uu});function PC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=Wr(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function _s(s){if(s instanceof _s)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:ka(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=_s.defaultMessages[this.code]||"")}_s.prototype.code=0;_s.prototype.message="";_s.prototype.status=null;_s.prototype.metadata=null;_s.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];_s.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."};_s.MEDIA_ERR_CUSTOM=0;_s.prototype.MEDIA_ERR_CUSTOM=0;_s.MEDIA_ERR_ABORTED=1;_s.prototype.MEDIA_ERR_ABORTED=1;_s.MEDIA_ERR_NETWORK=2;_s.prototype.MEDIA_ERR_NETWORK=2;_s.MEDIA_ERR_DECODE=3;_s.prototype.MEDIA_ERR_DECODE=3;_s.MEDIA_ERR_SRC_NOT_SUPPORTED=4;_s.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;_s.MEDIA_ERR_ENCRYPTED=5;_s.prototype.MEDIA_ERR_ENCRYPTED=5;function yh(s){return s!=null&&typeof s.then=="function"}function xa(s){yh(s)&&s.then(null,e=>{})}const dx=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}})})},l4=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=dx(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(dx))},u4=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 hx={textTracksToJson:l4,jsonToTextTracks:u4,trackToJson:dx};const zy="vjs-modal-dialog";class Vc extends Fe{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_=Xt("div",{className:`${zy}-content`},{role:"document"}),this.descEl_=Xt("p",{className:`${zy}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),vl(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`${zy} 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(),TC(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"),r0(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=at.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 fe.HTMLAnchorElement||t instanceof fe.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof fe.HTMLInputElement||t instanceof fe.HTMLSelectElement||t instanceof fe.HTMLTextAreaElement||t instanceof fe.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof fe.HTMLIFrameElement||t instanceof fe.HTMLObjectElement||t instanceof fe.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Vc.prototype.options_={pauseOnOpen:!0,temporary:!0};Fe.registerComponent("ModalDialog",Vc);class cu extends Tr{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})},ho(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){qy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&qy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,qy(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 Ky=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){Ky(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,Ky(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 yb extends cu{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 c4{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(fe.console&&fe.console.groupCollapsed&&fe.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>fi.error(n)),fe.console&&fe.console.groupEnd&&fe.console.groupEnd()),t.flush()},BE=function(s,e){const t={uri:s},i=u0(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),$A(t,os(this,function(r,a,u){if(r)return fi.error(r,a);e.loaded_=!0,typeof fe.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){fi.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return PE(u,e)}):PE(u,e)}))};class jh extends vb{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=Xi(e,{kind:f4[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=ME[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 hp(this.cues_),a=new hp(this.activeCues_);let u=!1;this.timeupdateHandler=os(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){ME[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&BE(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 a;const d=this.tech_.currentTime(),f=[];for(let p=0,y=this.cues.length;p=d&&f.push(v)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let p=0;p{t=mo.LOADED,this.trigger({type:"load",target:this})})}}mo.prototype.allowedEvents_={load:"load"};mo.NONE=0;mo.LOADING=1;mo.LOADED=2;mo.ERROR=3;const Dr={audio:{ListClass:BC,TrackClass:jC,capitalName:"Audio"},video:{ListClass:FC,TrackClass:$C,capitalName:"Video"},text:{ListClass:yb,TrackClass:jh,capitalName:"Text"}};Object.keys(Dr).forEach(function(s){Dr[s].getterName=`${s}Tracks`,Dr[s].privateName=`${s}Tracks_`});const Pc={remoteText:{ListClass:yb,TrackClass:jh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:c4,TrackClass:mo,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Ln=Object.assign({},Dr,Pc);Pc.names=Object.keys(Pc);Dr.names=Object.keys(Dr);Ln.names=[].concat(Pc.names).concat(Dr.names);function p4(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const a=new Ln.text.TrackClass(n);return r.addTrack(a),a}class li extends Fe{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}),Ln.names.forEach(i=>{const n=Ln[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 Ln.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(os(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 Wr(0,0)}bufferedPercent(){return PC(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(Dr.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 _s(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?Wr(0,0):Wr()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){Dr.names.forEach(e=>{const t=Dr[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(!fe.WebVTT)if(at.body.contains(this.el())){if(!this.options_["vtt.js"]&&Ic(oE)&&Object.keys(oE).length>0){this.trigger("vttjsloaded");return}const e=at.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}),fe.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"),a=()=>{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=Lr();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 li.canPlayType(e.type)}static isTech(e){return e.prototype instanceof li||e instanceof li||e===li}static registerTech(e,t){if(li.techs_||(li.techs_={}),!li.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!li.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!li.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=Cs(e),li.techs_[e]=t,li.techs_[gh(e)]=t,e!=="Tech"&&li.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(li.techs_&&li.techs_[e])return li.techs_[e];if(e=Cs(e),fe&&fe.videojs&&fe.videojs[e])return fi.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),fe.videojs[e]}}}Ln.names.forEach(function(s){const e=Ln[s];li.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});li.prototype.featuresVolumeControl=!0;li.prototype.featuresMuteControl=!0;li.prototype.featuresFullscreenResize=!1;li.prototype.featuresPlaybackRate=!1;li.prototype.featuresProgressEvents=!1;li.prototype.featuresSourceset=!1;li.prototype.featuresTimeupdateEvents=!1;li.prototype.featuresNativeTextTracks=!1;li.prototype.featuresVideoFrameCallback=!1;li.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;rWl(e,nu[e.type],t,s),1)}function v4(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function x4(s,e,t){return s.reduceRight(Tb(t),e[t]())}function b4(s,e,t,i){return e[t](s.reduce(Tb(t),i))}function FE(s,e,t,i=null){const n="call"+Cs(t),r=s.reduce(Tb(n),i),a=r===mp,u=a?null:e[t](r);return S4(s,t,u,a),u}const T4={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},_4={setCurrentTime:1,setMuted:1,setVolume:1},UE={play:1,pause:1};function Tb(s){return(e,t)=>e===mp?mp:t[s]?t[s](e):e}function S4(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function E4(s){fp.hasOwnProperty(s.id())&&delete fp[s.id()]}function w4(s,e){const t=fp[s.id()];let i=null;if(t==null)return i=e(s),fp[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 $E=lp?10009:up?461:8,Ku={codes:{play:415,pause:19,ff:417,rw:412,back:$E},names:{415:"play",19:"pause",417:"ff",412:"rw",[$E]:"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}},HE=5;class D4 extends Tr{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(Ku.isEventKey(t,"play")||Ku.isEventKey(t,"pause")||Ku.isEventKey(t,"ff")||Ku.isEventKey(t,"rw")){t.preventDefault();const i=Ku.getEventName(t);this.performMediaAction_(i)}else Ku.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()+HE);break;case"rw":this.userSeek_(this.player_.currentTime()-HE);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(a=>a!==t&&this.isInDirection_(i.boundingClientRect,a.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 a of t){const u=a.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"&&fi.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=Xt(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(Xt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=Xt("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,vl(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)}}Fe.registerComponent("ClickableComponent",c0);class fx extends c0{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 Xt("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(Xt("picture",{className:"vjs-poster",tabIndex:-1},{},Xt("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()?xa(this.player_.play()):this.player_.pause())}}fx.prototype.crossorigin=fx.prototype.crossOrigin;Fe.registerComponent("PosterImage",fx);const kr="#222",GE="#ccc",R4={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 Wy(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 ca(s,e,t){try{s.style[e]=t}catch{return}}function VE(s){return s?`${s}px`:""}class I4 extends Fe{constructor(e,t,i){super(e,t,i);const n=a=>this.updateDisplay(a),r=a=>{this.updateDisplayOverlay(),this.updateDisplay(a)};e.on("loadstart",a=>this.toggleDisplay(a)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",a=>{this.updateDisplayOverlay(),this.preselectTrack(a)}),e.ready(os(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const a=fe.screen.orientation||fe,u=fe.screen.orientation?"change":"orientationchange";a.addEventListener(u,r),e.on("dispose",()=>a.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()||!fe.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,a=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):a=Math.round((t-e/n)/2)),ca(this.el_,"insetInline",VE(r)),ca(this.el_,"insetBlock",VE(a))}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 a=r.displayState;if(t.color&&(a.firstChild.style.color=t.color),t.textOpacity&&ca(a.firstChild,"color",Wy(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(a.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&ca(a.firstChild,"backgroundColor",Wy(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?ca(a,"backgroundColor",Wy(t.windowColor,t.windowOpacity)):a.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?a.firstChild.style.textShadow=`2px 2px 3px ${kr}, 2px 2px 4px ${kr}, 2px 2px 5px ${kr}`:t.edgeStyle==="raised"?a.firstChild.style.textShadow=`1px 1px ${kr}, 2px 2px ${kr}, 3px 3px ${kr}`:t.edgeStyle==="depressed"?a.firstChild.style.textShadow=`1px 1px ${GE}, 0 1px ${GE}, -1px -1px ${kr}, 0 -1px ${kr}`:t.edgeStyle==="uniform"&&(a.firstChild.style.textShadow=`0 0 4px ${kr}, 0 0 4px ${kr}, 0 0 4px ${kr}, 0 0 4px ${kr}`)),t.fontPercent&&t.fontPercent!==1){const u=fe.parseFloat(a.style.fontSize);a.style.fontSize=u*t.fontPercent+"px",a.style.height="auto",a.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?a.firstChild.style.fontVariant="small-caps":a.firstChild.style.fontFamily=R4[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof fe.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){xa(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();yh(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}GC.prototype.controlText_="Play Video";Fe.registerComponent("BigPlayButton",GC);class O4 extends Sn{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)}}Fe.registerComponent("CloseButton",O4);class VC extends Sn{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()?xa(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))}}VC.prototype.controlText_="Play";Fe.registerComponent("PlayToggle",VC);class zc extends Fe{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=Xt("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=Xt("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=uu(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,fi.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_=at.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}zc.prototype.labelText_="Time";zc.prototype.controlText_="Time";Fe.registerComponent("TimeDisplay",zc);class _b extends zc{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)}}_b.prototype.labelText_="Current Time";_b.prototype.controlText_="Current Time";Fe.registerComponent("CurrentTimeDisplay",_b);class Sb extends zc{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)}}Sb.prototype.labelText_="Duration";Sb.prototype.controlText_="Duration";Fe.registerComponent("DurationDisplay",Sb);class M4 extends Fe{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}}Fe.registerComponent("TimeDivider",M4);class Eb extends zc{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(Xt("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)}}Eb.prototype.labelText_="Remaining Time";Eb.prototype.controlText_="Remaining Time";Fe.registerComponent("RemainingTimeDisplay",Eb);class P4 extends Fe{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_=Xt("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(Xt("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(at.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()}}Fe.registerComponent("LiveDisplay",P4);class zC extends Sn{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_=Xt("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()}}zC.prototype.controlText_="Seek to live, currently playing live";Fe.registerComponent("SeekToLive",zC);function $h(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var B4=Object.freeze({__proto__:null,clamp:$h});class wb extends Fe{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"&&!Da&&e.preventDefault(),yC(),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;vC(),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($h(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=n0(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")}}Fe.registerComponent("Slider",wb);const Yy=(s,e)=>$h(s/e*100,0,100).toFixed(2)+"%";class F4 extends Fe{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=Xt("span",{className:"vjs-control-text"}),i=Xt("span",{textContent:this.localize("Loaded")}),n=at.createTextNode(": ");return this.percentageEl_=Xt("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(),a=this.partEls_,u=Yy(r,n);this.percent_!==u&&(this.el_.style.width=u,vl(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(a[c-1]);a.length=i.length})}}Fe.registerComponent("LoadProgressBar",F4);class U4 extends Fe{constructor(e,t){super(e,t),this.update=La(os(this,this.update),Rr)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=Ah(this.el_),r=Oc(this.player_.el()),a=e.width*t;if(!r||!n)return;let u=e.left-r.left+a,c=e.width-a+(r.right-e.right);c||(c=e.width-a,u=a);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){vl(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+uu(c,u)}else r=uu(i,a);this.update(e,t,r),n&&n()})}}Fe.registerComponent("TimeTooltip",U4);class Ab extends Fe{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=La(os(this,this.update),Rr)}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)}}Ab.prototype.options_={children:[]};!Tn&&!Yr&&Ab.prototype.options_.children.push("timeTooltip");Fe.registerComponent("PlayProgressBar",Ab);class qC extends Fe{constructor(e,t){super(e,t),this.update=La(os(this,this.update),Rr)}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`})}}qC.prototype.options_={children:["timeTooltip"]};Fe.registerComponent("MouseTimeDisplay",qC);class d0 extends wb{constructor(e,t){t=Xi(d0.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(Tn||Yr)||e.options_.disableSeekWhileScrubbingOnSTV;(!Tn&&!Yr||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=os(this,this.update),this.update=La(this.update_,Rr),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 at&&"visibilityState"in at&&this.on(at,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){at.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,Rr))}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(at.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}",[uu(i,r),uu(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(Oc(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){Ch(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Ch(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 a=r.seekableStart(),u=r.liveCurrentTime();if(i=a+n*r.liveWindow(),i>=u&&(i=u),i<=a&&(i=a+.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?xa(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 at&&"visibilityState"in at&&this.off(at,"visibilitychange",this.toggleVisibility_),super.dispose()}}d0.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};Fe.registerComponent("SeekBar",d0);class KC extends Fe{constructor(e,t){super(e,t),this.handleMouseMove=La(os(this,this.handleMouseMove),Rr),this.throttledHandleMouseSeek=La(os(this,this.handleMouseSeek),Rr),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(),a=Ah(r);let u=n0(r,e).x;u=$h(u,0,1),n&&n.update(a,u),i&&i.update(a,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&&xa(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"]};Fe.registerComponent("ProgressControl",KC);class WC extends Sn{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(){at.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in fe?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 at.exitPictureInPicture=="function"&&super.show()}}WC.prototype.controlText_="Picture-in-Picture";Fe.registerComponent("PictureInPictureToggle",WC);class YC extends Sn{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),at[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()}}YC.prototype.controlText_="Fullscreen";Fe.registerComponent("FullscreenToggle",YC);const j4=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 $4 extends Fe{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}}Fe.registerComponent("VolumeLevel",$4);class H4 extends Fe{constructor(e,t){super(e,t),this.update=La(os(this,this.update),Rr)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=Oc(this.el_),a=Oc(this.player_.el()),u=e.width*t;if(!a||!r)return;const c=e.left-a.left+u,d=e.width-u+(a.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){vl(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}Fe.registerComponent("VolumeLevelTooltip",H4);class XC extends Fe{constructor(e,t){super(e,t),this.update=La(os(this,this.update),Rr)}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`})}}XC.prototype.options_={children:["volumeLevelTooltip"]};Fe.registerComponent("MouseVolumeLevelDisplay",XC);class h0 extends wb{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){Ch(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=Oc(i),r=this.vertical();let a=n0(i,e);a=r?a.y:a.x,a=$h(a,0,1),t.update(n,a,r)}Ch(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)})}}h0.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!Tn&&!Yr&&h0.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");h0.prototype.playerEvent="volumechange";Fe.registerComponent("VolumeBar",h0);class QC extends Fe{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Ic(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),j4(this,e),this.throttledHandleMouseMove=La(os(this,this.handleMouseMove),Rr),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)}}QC.prototype.options_={children:["volumeBar"]};Fe.registerComponent("VolumeControl",QC);const G4=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 ZC extends Sn{constructor(e,t){super(e,t),G4(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"),Tn&&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),i0(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),su(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}ZC.prototype.controlText_="Mute";Fe.registerComponent("MuteToggle",ZC);class JC extends Fe{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Ic(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"),br(at,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),_n(at,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}JC.prototype.options_={children:["muteToggle","volumeControl"]};Fe.registerComponent("VolumePanel",JC);class ek extends Sn{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]))}}ek.prototype.controlText_="Skip Forward";Fe.registerComponent("SkipForward",ek);class tk extends Sn{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]))}}tk.prototype.controlText_="Skip Backward";Fe.registerComponent("SkipBackward",tk);class ik extends Fe{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 Fe&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof Fe&&(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_=Xt(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_),br(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||at.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())}}Fe.registerComponent("Menu",ik);class Cb extends Fe{constructor(e,t={}){super(e,t),this.menuButton_=new Sn(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=Sn.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(),br(at,"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 ik(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=Xt("li",{className:"vjs-menu-title",textContent:Cs(this.options_.title),tabIndex:-1}),i=new Fe(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},a=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",a),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",a)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof fe.Event!="object")try{u=new fe.Event("change")}catch{}u||(u=at.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&&a.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&&a.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()}}Fe.registerComponent("OffTextTrackMenuItem",sk);class qc extends kb{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Gh){let i;this.label_&&(i=`${this.label_} off`),e.push(new sk(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:a,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${a.kind}-menu-item`),e.push(u)}}return e}}Fe.registerComponent("TextTrackButton",qc);class nk extends Hh{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(Cs(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(Cs(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 Ib(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,rk),e}}Ob.prototype.kinds_=["captions","subtitles"];Ob.prototype.controlText_="Subtitles";Fe.registerComponent("SubsCapsButton",Ob);class ak extends Hh{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=(...a)=>{this.handleTracksChange.apply(this,a)};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(Xt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(Xt("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)}}Mb.prototype.contentElType="button";Fe.registerComponent("PlaybackRateMenuItem",Mb);class lk extends Cb{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_=Xt("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 Mb(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")}}lk.prototype.controlText_="Playback Rate";Fe.registerComponent("PlaybackRateMenuButton",lk);class uk extends Fe{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}Fe.registerComponent("Spacer",uk);class V4 extends uk{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}Fe.registerComponent("CustomControlSpacer",V4);class ck extends Fe{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}ck.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};Fe.registerComponent("ControlBar",ck);class dk extends Vc{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):""}}dk.prototype.options_=Object.assign({},Vc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});Fe.registerComponent("ErrorDisplay",dk);class hk extends Fe{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(),Xt("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${Lr()}`)+"-"+t[1].replace(/\W+/g,""),n=Xt("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}Fe.registerComponent("TextTrackSelect",hk);class ru extends Fe{constructor(e,t={}){super(e,t);const i=Xt("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 a=this.options_.selectConfigs[r],u=a.className,c=a.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${Lr()}`;if(this.options_.type==="colors"){d=Xt("span",{className:u});const y=Xt("label",{id:c,className:"vjs-label",textContent:this.localize(a.label)});y.setAttribute("for",f),d.appendChild(y)}const p=new hk(e,{SelectOptions:a.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 Xt("fieldset",{className:this.options_.className})}}Fe.registerComponent("TextTrackFieldset",ru);class fk extends Fe{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new ru(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 ru(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 a=new ru(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(a)}createEl(){return Xt("div",{className:"vjs-track-settings-colors"})}}Fe.registerComponent("TextTrackSettingsColors",fk);class mk extends Fe{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new ru(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 ru(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 a=new ru(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(a)}createEl(){return Xt("div",{className:"vjs-track-settings-font"})}}Fe.registerComponent("TextTrackSettingsFont",mk);class pk extends Fe{constructor(e,t={}){super(e,t);const i=new Sn(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 Sn(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return Xt("div",{className:"vjs-track-settings-controls"})}}Fe.registerComponent("TrackSettingsControls",pk);const Xy="vjs-text-track-settings",zE=["#000","Black"],qE=["#00F","Blue"],KE=["#0FF","Cyan"],WE=["#0F0","Green"],YE=["#F0F","Magenta"],XE=["#F00","Red"],QE=["#FFF","White"],ZE=["#FF0","Yellow"],Qy=["1","Opaque"],Zy=["0.5","Semi-Transparent"],JE=["0","Transparent"],al={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[zE,QE,XE,WE,qE,ZE,YE,KE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[Qy,Zy,JE],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[QE,zE,XE,WE,qE,ZE,YE,KE],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:[Qy,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:[JE,Zy,Qy],className:"vjs-window-opacity vjs-opacity"}};al.windowColor.options=al.backgroundColor.options;function gk(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function z4(s,e){const t=s.options[s.options.selectedIndex].value;return gk(t,e)}function q4(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()}),dc(al,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 rC(al,(e,t,i)=>{const n=z4(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){dc(al,(t,i)=>{q4(this.$(t.selector),e[i],t.parser)})}setDefaults(){dc(al,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(fe.localStorage.getItem(Xy))}catch(t){fi.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?fe.localStorage.setItem(Xy,JSON.stringify(e)):fe.localStorage.removeItem(Xy)}catch(t){fi.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}Fe.registerComponent("TextTrackSettings",K4);class W4 extends Fe{constructor(e,t){let i=t.ResizeObserver||fe.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=Xi({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||fe.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=kC(()=>{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 a=this.unloadListener_=function(){_n(this,"resize",r),_n(this,"unload",a),a=null};br(this.el_.contentWindow,"unload",a),br(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()}}Fe.registerComponent("ResizeManager",W4);const Y4={trackingThreshold:20,liveTolerance:15};class X4 extends Fe{constructor(e,t){const i=Xi(Y4,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(fe.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 a=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,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_,Rr),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()}}Fe.registerComponent("LiveTracker",X4);class Q4 extends Fe{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:Xt("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${Lr()}`}),description:Xt("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${Lr()}`})},Xt("div",{className:"vjs-title-bar"},{},aC(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],a=this.els[n],u=i[n];r0(a),r&&vl(a,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,a.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}}Fe.registerComponent("TitleBar",Q4);const Z4={initialDisplay:4e3,position:[],takeFocus:!1};class J4 extends Sn{constructor(e,t){t=Xi(Z4,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=Xt("button",{},{type:"button",class:this.buildCSSClass()},Xt("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()}}Fe.registerComponent("TransientButton",J4);const mx=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;iyk([s.el(),fe.HTMLMediaElement.prototype,fe.Element.prototype,eB],"innerHTML"),e2=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=tB(s),n=r=>(...a)=>{const u=r.apply(e,a);return mx(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",Xi(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_)},iB=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?UC(fe.Element.prototype.getAttribute.call(this,"src")):""},set(s){return fe.Element.prototype.setAttribute.call(this,"src",s),s}}),sB=s=>yk([s.el(),fe.HTMLMediaElement.prototype,iB],"src"),nB=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=sB(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",Xi(t,{set:r=>{const a=t.set.call(e,r);return s.triggerSourceset(e.src),a}})),e.setAttribute=(r,a)=>{const u=i.call(e,r,a);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return mx(s)||(s.triggerSourceset(""),e2(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):mx(s)||e2(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class St extends li{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 a=r.length;const u=[];for(;a--;){const c=r[a];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")&&u0(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=Dr[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[Pc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},a=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",a),this.on("dispose",u=>this.off("loadstart",a))}proxyNativeTracks_(){Dr.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),St.disposeMediaElement(e),e=i}else{e=at.createElement("video");const i=this.options_.tag&&rl(this.options_.tag),n=Xi({},i);(!wh||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,pC(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&Nc(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&&t0?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){fi(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Yr&&Da&&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)xa(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 fi.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=Xt("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return fi.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 fi.warn(`No matching source element found with src: ${e}`),!1}reset(){St.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=at.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),fe.performance&&(e.creationTime=fe.performance.now()),e}}Qp(St,"TEST_VID",function(){if(!$c())return;const s=at.createElement("video"),e=at.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});St.isSupported=function(){try{St.TEST_VID.volume=.5}catch{return!1}return!!(St.TEST_VID&&St.TEST_VID.canPlayType)};St.canPlayType=function(s){return St.TEST_VID.canPlayType(s)};St.canPlaySource=function(s,e){return St.canPlayType(s.type)};St.canControlVolume=function(){try{const s=St.TEST_VID.volume;St.TEST_VID.volume=s/2+.1;const e=s!==St.TEST_VID.volume;return e&&Tn?(fe.setTimeout(()=>{St&&St.prototype&&(St.prototype.featuresVolumeControl=s!==St.TEST_VID.volume)}),!1):e}catch{return!1}};St.canMuteVolume=function(){try{const s=St.TEST_VID.muted;return St.TEST_VID.muted=!s,St.TEST_VID.muted?Nc(St.TEST_VID,"muted","muted"):s0(St.TEST_VID,"muted","muted"),s!==St.TEST_VID.muted}catch{return!1}};St.canControlPlaybackRate=function(){if(Yr&&Da&&Zp<58)return!1;try{const s=St.TEST_VID.playbackRate;return St.TEST_VID.playbackRate=s/2+.1,s!==St.TEST_VID.playbackRate}catch{return!1}};St.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(at.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(at.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(at.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(at.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};St.supportsNativeTextTracks=function(){return t0||Tn&&Da};St.supportsNativeVideoTracks=function(){return!!(St.TEST_VID&&St.TEST_VID.videoTracks)};St.supportsNativeAudioTracks=function(){return!!(St.TEST_VID&&St.TEST_VID.audioTracks)};St.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]){Qp(St.prototype,s,()=>St[e](),!0)});St.prototype.featuresVolumeControl=St.canControlVolume();St.prototype.movingMediaElementInDOM=!Tn;St.prototype.featuresFullscreenResize=!0;St.prototype.featuresProgressEvents=!0;St.prototype.featuresTimeupdateEvents=!0;St.prototype.featuresVideoFrameCallback=!!(St.TEST_VID&&St.TEST_VID.requestVideoFrameCallback);St.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{}})()}};St.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){St.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){St.prototype["set"+Cs(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){St.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){St.prototype["set"+Cs(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){St.prototype[s]=function(){return this.el_[s]()}});li.withSourceHandlers(St);St.nativeSourceHandler={};St.nativeSourceHandler.canPlayType=function(s){try{return St.TEST_VID.canPlayType(s)}catch{return""}};St.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return St.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=bb(s.src);return St.nativeSourceHandler.canPlayType(`video/${t}`)}return""};St.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};St.nativeSourceHandler.dispose=function(){};St.registerSourceHandler(St.nativeSourceHandler);li.registerTech("Html5",St);const vk=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],Jy={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},px=["tiny","xsmall","small","medium","large","xlarge","huge"],jm={};px.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;jm[s]=`vjs-layout-${e}`});const rB={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let ys=class ic extends Fe{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${Lr()}`,t=Object.assign(ic.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const a=e.closest("[lang]");a&&(t.language=a.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=a=>this.documentFullscreenChange_(a),this.boundFullWindowOnEscKey_=a=>this.fullWindowOnEscKey(a),this.boundUpdateStyleEl_=a=>this.updateStyleEl_(a),this.boundApplyInitTime_=a=>this.applyInitTime_(a),this.boundUpdateCurrentBreakpoint_=a=>this.updateCurrentBreakpoint_(a),this.boundHandleTechClick_=a=>this.handleTechClick_(a),this.boundHandleTechDoubleClick_=a=>this.handleTechDoubleClick_(a),this.boundHandleTechTouchStart_=a=>this.handleTechTouchStart_(a),this.boundHandleTechTouchMove_=a=>this.handleTechTouchMove_(a),this.boundHandleTechTouchEnd_=a=>this.handleTechTouchEnd_(a),this.boundHandleTechTap_=a=>this.handleTechTap_(a),this.boundUpdatePlayerHeightOnAudioOnlyMode_=a=>this.updatePlayerHeightOnAudioOnlyMode_(a),this.isFullscreen_=!1,this.log=sC(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&&rl(e),this.language(this.options_.language),t.languages){const a={};Object.getOwnPropertyNames(t.languages).forEach(function(u){a[u.toLowerCase()]=t.languages[u]}),this.languages_=a}else this.languages_=ic.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(a=>{if(typeof this[a]!="function")throw new Error(`plugin "${a}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),pb(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(br(at,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=Xi(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(a=>{this[a](t.plugins[a])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new fe.DOMParser().parseFromString(k4,"image/svg+xml");if(u.querySelector("parsererror"))fi.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 D4(this),this.addClass("vjs-spatial-navigation-enabled")),wh&&this.addClass("vjs-touch-enabled"),Tn||this.addClass("vjs-workinghover"),ic.players[this.id_]=this;const r=nx.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",a=>this.listenForUserActivity_(a)),this.on("keydown",a=>this.handleKeyDown(a)),this.on("languagechange",a=>this.handleLanguagechange(a)),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"),_n(at,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),_n(at,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),ic.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),E4(this),Ln.names.forEach(e=>{const t=Ln[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=rl(e);if(n){for(t=this.el_=e,e=this.tag=at.createElement("video");t.children.length;)e.appendChild(t.firstChild);ph(t,"video-js")||su(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",Da&&Jp&&(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 a=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>dC[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),fe.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=AC("vjs-styles-dimensions");const c=pl(".vjs-styles-defaults"),d=pl("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"){fi.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)){fi.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,ho(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),i4(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(fe.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(":"),a=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/a:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*a,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),CC(this.styleEl_,` - .${n} { - width: ${e}px; - height: ${t}px; - } - - .${n}.vjs-fluid:not(.vjs-audio-only-mode) { - padding-top: ${a*100}%; - } - `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=Cs(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(li.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 a={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};Ln.names.forEach(c=>{const d=Ln[c];a[d.getterName]=this[d.privateName]}),Object.assign(a,this.options_[i]),Object.assign(a,this.options_[n]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);const u=li.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(a),this.tech_.ready(os(this,this.handleTechReady_),!0),hx.jsonToTextTracks(this.textTracksJson_||[],this.tech_),vk.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${Cs(c)}_`](d))}),Object.keys(Jy).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${Jy[c]}_`].bind(this),event:d});return}this[`handleTech${Jy[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)&&ax(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Ln.names.forEach(e=>{const t=Ln[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=hx.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&&fi.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":nx}}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 a=this.play();if(yh(a))return a.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),yh(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!yh(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=C4(this,t)),this.cache_.source=Xi({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],a=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 a=this.techGet_("currentSrc");this.lastSource_.tech=a,this.updateSourceCaches_(a)})}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()?xa(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()&&!at.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=at[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 _4)return b4(this.middleware_,this.tech_,e,t);if(e in UE)return FE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw fi(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in T4)return x4(this.middleware_,this.tech_,e);if(e in UE)return FE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(fi(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(fi(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(fi(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=xa){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(t0||Tn);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=a=>{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")||Wr(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=Wr(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=Wr(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 PC(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",a)}function a(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",a),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",a),e.off("fullscreenchange",r)}function r(){n(),t()}function a(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",a);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=at[this.fsApi_.exitFullscreen]();return e&&xa(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=at.documentElement.style.overflow,br(at,"keydown",this.boundFullWindowOnEscKey_),at.documentElement.style.overflow="hidden",su(at.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,_n(at,"keydown",this.boundFullWindowOnEscKey_),at.documentElement.style.overflow=this.docOrigOverflow,i0(at.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&&fe.documentPictureInPicture){const e=at.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(Xt("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),fe.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(SC(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 at&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(fe.documentPictureInPicture&&fe.documentPictureInPicture.window)return fe.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in at)return at.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const a=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?a.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=a=>e.key.toLowerCase()==="f",muteKey:n=a=>e.key.toLowerCase()==="m",playPauseKey:r=a=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=Fe.getComponent("FullscreenToggle");at[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),Fe.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),Fe.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,li.getTech(u)]).filter(([u,c])=>c?c.isSupported():(fi.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(y=>{if(f=d(p,y),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),a=([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(a)):n=i(t,e,a),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=HC(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]),y4(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}v4(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?IC(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();xa(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}),ho(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(ml("beforeerror").forEach(t=>{const i=t(this,e);if(!(ka(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 _s(e),this.addClass("vjs-error"),fi.error(`(CODE:${this.error_.code} ${_s.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),ml("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=os(this,this.reportUserActivity),r=function(p){(p.screenX!==t||p.screenY!==i)&&(t=p.screenX,i=p.screenY,n())},a=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(p){n(),this.clearInterval(e)};this.on("mousedown",a),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!Tn&&!Yr&&(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(),ho(this)&&this.trigger("languagechange"))}languages(){return Xi(ic.prototype.options_.languages,this.languages_)}toJSON(){const e=Xi(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:a||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:pp(n.poster)}]),n}return Xi(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=rl(e),n=i["data-setup"];if(ph(e,"vjs-fill")&&(i.fill=!0),ph(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){fi.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let a=0,u=r.length;atypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};ys.prototype.videoTracks=()=>{};ys.prototype.audioTracks=()=>{};ys.prototype.textTracks=()=>{};ys.prototype.remoteTextTracks=()=>{};ys.prototype.remoteTextTrackEls=()=>{};Ln.names.forEach(function(s){const e=Ln[s];ys.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});ys.prototype.crossorigin=ys.prototype.crossOrigin;ys.players={};const Xd=fe.navigator;ys.prototype.options_={techOrder:li.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};vk.forEach(function(s){ys.prototype[`handleTech${Cs(s)}_`]=function(){return this.trigger(s)}});Fe.registerComponent("Player",ys);const gp="plugin",mc="activePlugins_",ac={},yp=s=>ac.hasOwnProperty(s),$m=s=>yp(s)?ac[s]:void 0,xk=(s,e)=>{s[mc]=s[mc]||{},s[mc][e]=!0},vp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},aB=function(s,e){const t=function(){vp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return xk(this,s),vp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},t2=(s,e)=>(e.prototype.name=s,function(...t){vp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,vp(this,i.getEventHash()),i});class Jn{constructor(e){if(this.constructor===Jn)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),pb(this),delete this.trigger,RC(this,this.constructor.defaultState),xk(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 Gc(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[mc][e]=!1,this.player=this.state=null,t[e]=t2(e,ac[e])}static isBasic(e){const t=typeof e=="string"?$m(e):e;return typeof t=="function"&&!Jn.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(yp(e))fi.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(ys.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 ac[e]=t,e!==gp&&(Jn.isBasic(t)?ys.prototype[e]=aB(e,t):ys.prototype[e]=t2(e,t)),t}static deregisterPlugin(e){if(e===gp)throw new Error("Cannot de-register base plugin.");yp(e)&&(delete ac[e],delete ys.prototype[e])}static getPlugins(e=Object.keys(ac)){let t;return e.forEach(i=>{const n=$m(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=$m(e);return t&&t.VERSION||""}}Jn.getPlugin=$m;Jn.BASE_PLUGIN_NAME=gp;Jn.registerPlugin(gp,Jn);ys.prototype.usingPlugin=function(s){return!!this[mc]&&this[mc][s]===!0};ys.prototype.hasPlugin=function(s){return!!yp(s)};function oB(s,e){let t=!1;return function(...i){return t||fi.warn(s),t=!0,e.apply(this,i)}}function Xr(s,e,t,i){return oB(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var lB={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 bk=s=>s.indexOf("#")===0?s.slice(1):s;function De(s,e,t){let i=De.getPlayer(s);if(i)return e&&fi.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?pl("#"+bk(s)):s;if(!Hc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in n?n.getRootNode()instanceof fe.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!a.contains(n))&&fi.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)),ml("beforesetup").forEach(c=>{const d=c(n,Xi(e));if(!ka(d)||Array.isArray(d)){fi.error("please return an object in beforesetup hooks");return}e=Xi(e,d)});const u=Fe.getComponent("Player");return i=new u(n,e,t),ml("setup").forEach(c=>c(i)),i}De.hooks_=oo;De.hooks=ml;De.hook=HP;De.hookOnce=GP;De.removeHook=iC;if(fe.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&$c()){let s=pl(".vjs-styles-defaults");if(!s){s=AC("vjs-styles-defaults");const e=pl("head");e&&e.insertBefore(s,e.firstChild),CC(s,` - .video-js { - width: 300px; - height: 150px; - } - - .vjs-fluid:not(.vjs-audio-only-mode) { - padding-top: 56.25% - } - `)}}lx(1,De);De.VERSION=nx;De.options=ys.prototype.options_;De.getPlayers=()=>ys.players;De.getPlayer=s=>{const e=ys.players;let t;if(typeof s=="string"){const i=bk(s),n=e[i];if(n)return n;t=pl("#"+i)}else t=s;if(Hc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};De.getAllPlayers=()=>Object.keys(ys.players).map(s=>ys.players[s]).filter(Boolean);De.players=ys.players;De.getComponent=Fe.getComponent;De.registerComponent=(s,e)=>(li.isTech(e)&&fi.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),Fe.registerComponent.call(Fe,s,e));De.getTech=li.getTech;De.registerTech=li.registerTech;De.use=g4;Object.defineProperty(De,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(De.middleware,"TERMINATOR",{value:mp,writeable:!1,enumerable:!0});De.browser=dC;De.obj=qP;De.mergeOptions=Xr(9,"videojs.mergeOptions","videojs.obj.merge",Xi);De.defineLazyProperty=Xr(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Qp);De.bind=Xr(9,"videojs.bind","native Function.prototype.bind",os);De.registerPlugin=Jn.registerPlugin;De.deregisterPlugin=Jn.deregisterPlugin;De.plugin=(s,e)=>(fi.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),Jn.registerPlugin(s,e));De.getPlugins=Jn.getPlugins;De.getPlugin=Jn.getPlugin;De.getPluginVersion=Jn.getPluginVersion;De.addLanguage=function(s,e){return s=(""+s).toLowerCase(),De.options.languages=Xi(De.options.languages,{[s]:e}),De.options.languages[s]};De.log=fi;De.createLogger=sC;De.time=o4;De.createTimeRange=Xr(9,"videojs.createTimeRange","videojs.time.createTimeRanges",Wr);De.createTimeRanges=Xr(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",Wr);De.formatTime=Xr(9,"videojs.formatTime","videojs.time.formatTime",uu);De.setFormatTime=Xr(9,"videojs.setFormatTime","videojs.time.setFormatTime",OC);De.resetFormatTime=Xr(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",MC);De.parseUrl=Xr(9,"videojs.parseUrl","videojs.url.parseUrl",xb);De.isCrossOrigin=Xr(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",u0);De.EventTarget=Tr;De.any=mb;De.on=br;De.one=o0;De.off=_n;De.trigger=Gc;De.xhr=$A;De.TrackList=cu;De.TextTrack=jh;De.TextTrackList=yb;De.AudioTrack=jC;De.AudioTrackList=BC;De.VideoTrack=$C;De.VideoTrackList=FC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{De[s]=function(){return fi.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),EC[s].apply(null,arguments)}});De.computedStyle=Xr(9,"videojs.computedStyle","videojs.dom.computedStyle",Mc);De.dom=EC;De.fn=t4;De.num=B4;De.str=r4;De.url=m4;De.Error=lB;class uB{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 xp extends De.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 uB(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=Tk,i},_k=function(s){return cB(this,De.obj.merge({},s))};De.registerPlugin("qualityLevels",_k);_k.VERSION=Tk;const Yn=Kp,bp=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,Or=s=>De.log.debug?De.log.debug.bind(De,"VHS:",`${s} >`):function(){};function Pi(...s){const e=De.obj||De;return(e.merge||e.mergeOptions).apply(e,s)}function rn(...s){const e=De.time||De;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function dB(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 ba=1/30,Ta=ba*3,Sk=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},vm=function(s,e){return Sk(s,function(t){return t-ba>=e})},hB=function(s){if(s.length<2)return rn();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(", ")},mB=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},tu=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},Bb=(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},gx=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),[]),wk=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},Ak=({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},Ck=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=wk(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},gB=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+=Bb(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},yB=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 fe.Infinity}return kk(s,e,t)},vh=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(a+=f.duration,r){if(a<0)continue}else if(a+ba<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-vh({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(a-=s.targetDuration,a<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dba,y=a===0,v=p&&a+ba>=0;if(!((y||v)&&d!==u.length-1)){if(r){if(a>0)continue}else if(a-ba>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+vh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},Rk=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Fb=function(s){return s.excludeUntil&&s.excludeUntil===1/0},f0=function(s){const e=Rk(s);return!s.disabled&&!e},bB=function(s){return s.disabled},TB=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=>f0(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),i2=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},Vh=s=>{if(!s||!s.playlists||!s.playlists.length)return i2(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;eVA(r))||i2(s,r=>Ub(t,r))))return!1}return!0};var Xn={liveEdgeDelay:Ck,duration:Dk,seekable:vB,getMediaInfoForTime:xB,isEnabled:f0,isDisabled:bB,isExcluded:Rk,isIncompatible:Fb,playlistEnd:Lk,isAes:TB,hasAttribute:Ik,estimateSegmentRequestTime:_B,isLowestEnabledRendition:yx,isAudioOnly:Vh,playlistMatch:Ub,segmentDurationWithParts:Bb};const{log:Nk}=De,pc=(s,e)=>`${s}-${e}`,Ok=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,SB=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const a=new c3;s&&a.on("warn",s),e&&a.on("info",e),i.forEach(d=>a.addParser(d)),n.forEach(d=>a.addTagMapper(d)),a.push(t),a.end();const u=a.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=wk(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}`}),Nk.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},Kc=(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)}})},Mk=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},EB=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];Mk({playlist:t,id:pc(e,t.uri)}),t.resolvedUri=Yn(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||Nk.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},wB=s=>{Kc(s,e=>{e.uri&&(e.resolvedUri=Yn(s.uri,e.uri))})},AB=(s,e)=>{const t=pc(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:fe.location.href,resolvedUri:fe.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},Pk=(s,e,t=Ok)=>{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,a={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)a.error=Ns({},t),a.errorType=De.Error.NetworkRequestFailed;else if(e.aborted)a.errorType=De.Error.NetworkRequestAborted;else if(e.timedout)a.errorType=De.Error.NetworkRequestTimeout;else if(u){const c=i?De.Error.NetworkBodyParserFailed:De.Error.NetworkBadStatus;a.errorType=c,a.status=e.status,a.headers=e.headers}return a},CB=Or("CodecUtils"),Fk=function(s){const e=s.attributes||{};if(e.CODECS)return ga(e.CODECS)},Uk=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},kB=(s,e)=>{if(!Uk(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},kh=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(GA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){CB(`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},n2=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},xh=function(s,e){const t=e.attributes||{},i=kh(Fk(e)||[]);if(Uk(s,e)&&!i.audio&&!kB(s,e)){const n=kh(h3(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:DB}=De,LB=(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||[],a=Ak(e)-1;a>-1&&a!==r.length-1&&(t._HLS_part=a),(a>-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 fe.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},RB=(s,e)=>{if(!s)return e;const t=Pi(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 a;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=Yn(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=Yn(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=Yn(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=Yn(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=Yn(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=Yn(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,vx=(s,e,t=Hk)=>{const i=Pi(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=$k(e);const r=Pi(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a{jk(a,r.resolvedUri)});for(let a=0;a{if(a.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},r2=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:a,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:a,codecs:u})}),{type:e,isLive:t,renditions:i}};let lc=class extends DB{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Or("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 s2,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=Yn(this.main.uri,e.uri);this.llhls&&(t=LB(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:au({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=SB({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:De.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:a}=n.RESOLUTION||{};if(r&&a)return!0;const u=Fk(i)||[];return!!kh(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 a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),Mk({playlist:a,uri:i,id:n});const u=vx(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(xx(this.media(),!!u)),r.parsedPlaylist=r2(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),fe.clearTimeout(this.mediaUpdateTimeout),fe.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new s2,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(fe.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=fe.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_(xx(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 a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),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=bp(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(fe.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&&(fe.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=fe.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&&(fe.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=fe.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=fe.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:au({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=bp(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=r2(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,Pk(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=$k(i),i.segments.forEach(n=>{jk(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||fe.location.href;this.main=AB(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 a=i.playlists[r];if(a.attributes["PATHWAY-ID"]===n){const u=a.resolvedUri,c=a.id;if(t){const d=this.createCloneURI_(a.resolvedUri,e),f=pc(n,d),p=this.createCloneAttributes_(n,a.attributes),y=this.createClonePlaylist_(a,f,e,p);i.playlists[r]=y,i.playlists[f]=y,i.playlists[d]=y}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 a in i.mediaGroups[r])if(a===n){for(const u in i.mediaGroups[r][a])i.mediaGroups[r][a][u].playlists.forEach((d,f)=>{const p=i.playlists[d.id],y=p.id,v=p.resolvedUri;delete i.playlists[y],delete i.playlists[v]});delete i.mediaGroups[r][a]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),a=pc(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,a,e,u);i.playlists[n]=c,i.playlists[a]=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 a in n.mediaGroups[r]){if(a===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][a]){const c=n.mediaGroups[r][a][u];n.mediaGroups[r][t][u]=Ns({},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,y)=>{const v=n.playlists[p.id],b=Ok(r,t,u),_=pc(t,b);if(v&&!n.playlists[_]){const E=this.createClonePlaylist_(v,_,e),L=E.resolvedUri;n.playlists[_]=E,n.playlists[L]=E}d.playlists[y]=this.createClonePlaylist_(p,_,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:r,uri:r,id:t};return e.segments&&(a.segments=[]),n&&(a.attributes=n),Pi(e,a)}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 bx=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)},NB=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},OB=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},Gk=function(){const s=function e(t,i){t=Pi({timeout:45e3},t);const n=e.beforeRequest||De.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||De.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||De.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(De.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=De.Vhs.xhr.original===!0?De.xhr:De.Vhs.xhr,c=NB(r,t);r.delete(n);const d=u(c||t,function(p,y){return OB(a,d,p,y),bx(d,p,y,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},MB=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=fe.BigInt(s.offset)+fe.BigInt(s.length)-fe.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},Tx=function(s){const e={};return s.byterange&&(e.Range=MB(s.byterange)),e},PB=function(s,e){return s.start(e)+"-"+s.end(e)},BB=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},FB=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},Vk=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];qA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},Tp=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},zk=function(s){return s.resolvedUri},qk=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let a=0;aqk(s),jB=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)},GB=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,VB=(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:Xn.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},zB=(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"}},qB=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},KB=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=zB(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=HB(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},Wk=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!KB(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=VB(s,e);if(!u)return a({message:`${s} was not found in the stream`});const c=u.segment,d=qB(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return a({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{Wk({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:a})});return}const f=c.start+d,p=()=>a(null,r.currentTime());r.one("seeked",p),n&&r.pause(),i(f)},tv=(s,e)=>{if(s.readyState===4)return e()},YB=(s,e,t,i)=>{let n=[],r,a=!1;const u=function(p,y,v,b){return y.abort(),a=!0,t(p,y,v,b)},c=function(p,y){if(a)return;if(p)return p.metadata=au({requestType:i,request:y,error:p}),u(p,y,"",n);const v=y.responseText.substring(n&&n.byteLength||0,y.responseText.length);if(n=_3(n,KA(v,!0)),r=r||rh(n),n.length<10||r&&n.lengthu(p,y,"",n));const b=ub(n);return b==="ts"&&n.length<188?tv(y,()=>u(p,y,"",n)):!b&&n.length<376?tv(y,()=>u(p,y,"",n)):u(null,y,b,n)},f=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:y,loaded:v}){return bx(p,null,{statusCode:p.status},c)})}},function(p,y){return bx(f,p,y,c)});return f},{EventTarget:XB}=De,a2=function(s,e){if(!Hk(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}`},ZB=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=bP(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return Pk(r,e,QB),r},JB=(s,e)=>{Kc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},eF=(s,e,t)=>{let i=!0,n=Pi(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=vx(n,r.playlists[0],a2);f&&(n=f,c in n.mediaGroups[a][u]||(n.mediaGroups[a][u][c]=r),n.mediaGroups[a][u][c].playlists[0]=n.playlists[d],i=!1)}}),JB(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},tF=(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,o2=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const a=Yp(r);if(!e[a])break;const u=e[a].sidxInfo;tF(u,r)&&(t[a]=e[a])}}return t},iF=(s,e)=>{let i=o2(s.playlists,e);return Kc(s,(n,r,a,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=Pi(i,o2(c,e))}}),i};class _x extends XB{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_=Or("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&&Yp(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){fe.clearTimeout(this.mediaRequest_),this.mediaRequest_=fe.setTimeout(()=>i(!1),0);return}const r=bp(e.sidx.resolvedUri),a=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:p}=d;let y;try{y=wP(qt(d.response).subarray(8))}catch(v){v.metadata=au({requestType:p,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:y},ab(e,y,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=YB(r,this.vhs_.xhr,(c,d,f,p)=>{if(c)return a(c,d);if(!f||f!=="mp4"){const b=f||"unknown";return a({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:y,length:v}=e.sidx.byterange;if(p.length>=v+y)return a(c,{response:p.subarray(y,y+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:Tx({byterange:e.sidx.byterange})},a)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},fe.clearTimeout(this.minimumUpdatePeriodTimeout_),fe.clearTimeout(this.mediaRequest_),fe.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,fe.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(),fe.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(fe.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,fe.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=fe.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_){fe.clearTimeout(this.mediaRequest_),this.mediaRequest_=fe.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:a}=n;i.metadata=au({requestType:a,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=bp(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=TP(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:Yn(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:a}=n;return this.error.metadata=au({requestType:a,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_(){fe.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=ZB({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:De.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=eF(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:a}=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:!a,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_&&(fe.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_=fe.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_=iF(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=fe.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},xx(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 sn={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 sF=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(A){var k,C,N,U;if(k=x[A],!!k)if(arguments.length===2)for(N=k.length,C=0;C"u")){for(x in J)J.hasOwnProperty(x)&&(J[x]=[x.charCodeAt(0),x.charCodeAt(1),x.charCodeAt(2),x.charCodeAt(3)]);ue=new Uint8Array([105,115,111,109]),q=new Uint8Array([97,118,99,49]),se=new Uint8Array([0,0,0,1]),Y=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]),Q={video:Y,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]),F=new Uint8Array([0,0,0,0,0,0,0,0]),he=new Uint8Array([0,0,0,0,0,0,0,0]),be=he,pe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ce=he,oe=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(x){var A=[],k=0,C,N,U;for(C=1;C>>1,x.samplingfrequencyindex<<7|x.channelcount<<3,6,1,2]))},f=function(){return u(J.ftyp,ue,se,ue,q)},B=function(x){return u(J.hdlr,Q[x])},p=function(x){return u(J.mdat,x)},P=function(x){var A=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,x.duration>>>24&255,x.duration>>>16&255,x.duration>>>8&255,x.duration&255,85,196,0,0]);return x.samplerate&&(A[12]=x.samplerate>>>24&255,A[13]=x.samplerate>>>16&255,A[14]=x.samplerate>>>8&255,A[15]=x.samplerate&255),u(J.mdhd,A)},$=function(x){return u(J.mdia,P(x),B(x.type),v(x))},y=function(x){return u(J.mfhd,new Uint8Array([0,0,0,0,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&255]))},v=function(x){return u(J.minf,x.type==="video"?u(J.vmhd,oe):u(J.smhd,F),c(),H(x))},b=function(x,A){for(var k=[],C=A.length;C--;)k[C]=M(A[C]);return u.apply(null,[J.moof,y(x)].concat(k))},_=function(x){for(var A=x.length,k=[];A--;)k[A]=I(x[A]);return u.apply(null,[J.moov,L(4294967295)].concat(k).concat(E(x)))},E=function(x){for(var A=x.length,k=[];A--;)k[A]=W(x[A]);return u.apply(null,[J.mvex].concat(k))},L=function(x){var A=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&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(J.mvhd,A)},O=function(x){var A=x.samples||[],k=new Uint8Array(4+A.length),C,N;for(N=0;N>>8),U.push(C[le].byteLength&255),U=U.concat(Array.prototype.slice.call(C[le]));for(le=0;le>>8),ne.push(N[le].byteLength&255),ne=ne.concat(Array.prototype.slice.call(N[le]));if(de=[J.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,(k.width&65280)>>8,k.width&255,(k.height&65280)>>8,k.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(J.avcC,new Uint8Array([1,k.profileIdc,k.profileCompatibility,k.levelIdc,255].concat([C.length],U,[N.length],ne))),u(J.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],k.sarRatio){var me=k.sarRatio[0],Ee=k.sarRatio[1];de.push(u(J.pasp,new Uint8Array([(me&4278190080)>>24,(me&16711680)>>16,(me&65280)>>8,me&255,(Ee&4278190080)>>24,(Ee&16711680)>>16,(Ee&65280)>>8,Ee&255])))}return u.apply(null,de)},A=function(k){return u(J.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(k.channelcount&65280)>>8,k.channelcount&255,(k.samplesize&65280)>>8,k.samplesize&255,0,0,0,0,(k.samplerate&65280)>>8,k.samplerate&255,0,0]),d(k))}})(),R=function(x){var A=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,0,(x.duration&4278190080)>>24,(x.duration&16711680)>>16,(x.duration&65280)>>8,x.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,(x.width&65280)>>8,x.width&255,0,0,(x.height&65280)>>8,x.height&255,0,0]);return u(J.tkhd,A)},M=function(x){var A,k,C,N,U,ne,le;return A=u(J.tfhd,new Uint8Array([0,0,0,58,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),ne=Math.floor(x.baseMediaDecodeTime/a),le=Math.floor(x.baseMediaDecodeTime%a),k=u(J.tfdt,new Uint8Array([1,0,0,0,ne>>>24&255,ne>>>16&255,ne>>>8&255,ne&255,le>>>24&255,le>>>16&255,le>>>8&255,le&255])),U=92,x.type==="audio"?(C=K(x,U),u(J.traf,A,k,C)):(N=O(x),C=K(x,N.length+U),u(J.traf,A,k,C,N))},I=function(x){return x.duration=x.duration||4294967295,u(J.trak,R(x),$(x))},W=function(x){var A=new Uint8Array([0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return x.type!=="video"&&(A[A.length-1]=0),u(J.trex,A)},(function(){var x,A,k;k=function(C,N){var U=0,ne=0,le=0,de=0;return C.length&&(C[0].duration!==void 0&&(U=1),C[0].size!==void 0&&(ne=2),C[0].flags!==void 0&&(le=4),C[0].compositionTimeOffset!==void 0&&(de=8)),[0,0,U|ne|le|de,1,(C.length&4278190080)>>>24,(C.length&16711680)>>>16,(C.length&65280)>>>8,C.length&255,(N&4278190080)>>>24,(N&16711680)>>>16,(N&65280)>>>8,N&255]},A=function(C,N){var U,ne,le,de,me,Ee;for(de=C.samples||[],N+=20+16*de.length,le=k(de,N),ne=new Uint8Array(le.length+de.length*16),ne.set(le),U=le.length,Ee=0;Ee>>24,ne[U++]=(me.duration&16711680)>>>16,ne[U++]=(me.duration&65280)>>>8,ne[U++]=me.duration&255,ne[U++]=(me.size&4278190080)>>>24,ne[U++]=(me.size&16711680)>>>16,ne[U++]=(me.size&65280)>>>8,ne[U++]=me.size&255,ne[U++]=me.flags.isLeading<<2|me.flags.dependsOn,ne[U++]=me.flags.isDependedOn<<6|me.flags.hasRedundancy<<4|me.flags.paddingValue<<1|me.flags.isNonSyncSample,ne[U++]=me.flags.degradationPriority&61440,ne[U++]=me.flags.degradationPriority&15,ne[U++]=(me.compositionTimeOffset&4278190080)>>>24,ne[U++]=(me.compositionTimeOffset&16711680)>>>16,ne[U++]=(me.compositionTimeOffset&65280)>>>8,ne[U++]=me.compositionTimeOffset&255;return u(J.trun,ne)},x=function(C,N){var U,ne,le,de,me,Ee;for(de=C.samples||[],N+=20+8*de.length,le=k(de,N),U=new Uint8Array(le.length+de.length*8),U.set(le),ne=le.length,Ee=0;Ee>>24,U[ne++]=(me.duration&16711680)>>>16,U[ne++]=(me.duration&65280)>>>8,U[ne++]=me.duration&255,U[ne++]=(me.size&4278190080)>>>24,U[ne++]=(me.size&16711680)>>>16,U[ne++]=(me.size&65280)>>>8,U[ne++]=me.size&255;return u(J.trun,U)},K=function(C,N){return C.type==="audio"?x(C,N):A(C,N)}})();var Re={ftyp:f,mdat:p,moof:b,moov:_,initSegment:function(x){var A=f(),k=_(x),C;return C=new Uint8Array(A.byteLength+k.byteLength),C.set(A),C.set(k,A.byteLength),C}},Ze=function(x){var A,k,C=[],N=[];for(N.byteLength=0,N.nalCount=0,N.duration=0,C.byteLength=0,A=0;A1&&(A=x.shift(),x.byteLength-=A.byteLength,x.nalCount-=A.nalCount,x[0][0].dts=A.dts,x[0][0].pts=A.pts,x[0][0].duration+=A.duration),x},dt=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},ot=function(x,A){var k=dt();return k.dataOffset=A,k.compositionTimeOffset=x.pts-x.dts,k.duration=x.duration,k.size=4*x.length,k.size+=x.byteLength,x.keyFrame&&(k.flags.dependsOn=2,k.flags.isNonSyncSample=0),k},nt=function(x,A){var k,C,N,U,ne,le=A||0,de=[];for(k=0;kKe.ONE_SECOND_IN_TS/2))){for(me=$t()[x.samplerate],me||(me=A[0].data),Ee=0;Ee=k?x:(A.minSegmentDts=1/0,x.filter(function(C){return C.dts>=k?(A.minSegmentDts=Math.min(A.minSegmentDts,C.dts),A.minSegmentPts=A.minSegmentDts,!0):!1}))},ci=function(x){var A,k,C=[];for(A=0;A=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(x),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(x){this.rows[this.rowIdx]+=x},oi.prototype.backspace=function(){if(!this.isEmpty()){var x=this.rows[this.rowIdx];this.rows[this.rowIdx]=x.substr(0,x.length-1)}};var ti=function(x,A,k){this.serviceNum=x,this.text="",this.currentWindow=new oi(-1),this.windows=[],this.stream=k,typeof A=="string"&&this.createTextDecoder(A)};ti.prototype.init=function(x,A){this.startPts=x;for(var k=0;k<8;k++)this.windows[k]=new oi(k),typeof A=="function"&&(this.windows[k].beforeRowOverflow=A)},ti.prototype.setCurrentWindow=function(x){this.currentWindow=this.windows[x]},ti.prototype.createTextDecoder=function(x){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(x)}catch(A){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+x+" encoding. "+A})}};var Kt=function(x){x=x||{},Kt.prototype.init.call(this);var A=this,k=x.captionServices||{},C={},N;Object.keys(k).forEach(U=>{N=k[U],/^SERVICE/.test(U)&&(C[U]=N.encoding)}),this.serviceEncodings=C,this.current708Packet=null,this.services={},this.push=function(U){U.type===3?(A.new708Packet(),A.add708Bytes(U)):(A.current708Packet===null&&A.new708Packet(),A.add708Bytes(U))}};Kt.prototype=new Oi,Kt.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Kt.prototype.add708Bytes=function(x){var A=x.ccData,k=A>>>8,C=A&255;this.current708Packet.ptsVals.push(x.pts),this.current708Packet.data.push(k),this.current708Packet.data.push(C)},Kt.prototype.push708Packet=function(){var x=this.current708Packet,A=x.data,k=null,C=null,N=0,U=A[N++];for(x.seq=U>>6,x.sizeCode=U&63;N>5,C=U&31,k===7&&C>0&&(U=A[N++],k=U),this.pushServiceBlock(k,N,C),C>0&&(N+=C-1)},Kt.prototype.pushServiceBlock=function(x,A,k){var C,N=A,U=this.current708Packet.data,ne=this.services[x];for(ne||(ne=this.initService(x,N));N("0"+(_t&255).toString(16)).slice(-2)).join("")}if(N?(Pe=[le,de],x++):Pe=[le],A.textDecoder_&&!C)Ee=A.textDecoder_.decode(new Uint8Array(Pe));else if(N){const Ue=ht(Pe);Ee=String.fromCharCode(parseInt(Ue,16))}else Ee=Mi(ne|le);return me.pendingNewLine&&!me.isEmpty()&&me.newLine(this.getPts(x)),me.pendingNewLine=!1,me.addText(Ee),x},Kt.prototype.multiByteCharacter=function(x,A){var k=this.current708Packet.data,C=k[x+1],N=k[x+2];return Li(C)&&Li(N)&&(x=this.handleText(++x,A,{isMultiByte:!0})),x},Kt.prototype.setCurrentWindow=function(x,A){var k=this.current708Packet.data,C=k[x],N=C&7;return A.setCurrentWindow(N),x},Kt.prototype.defineWindow=function(x,A){var k=this.current708Packet.data,C=k[x],N=C&7;A.setCurrentWindow(N);var U=A.currentWindow;return C=k[++x],U.visible=(C&32)>>5,U.rowLock=(C&16)>>4,U.columnLock=(C&8)>>3,U.priority=C&7,C=k[++x],U.relativePositioning=(C&128)>>7,U.anchorVertical=C&127,C=k[++x],U.anchorHorizontal=C,C=k[++x],U.anchorPoint=(C&240)>>4,U.rowCount=C&15,C=k[++x],U.columnCount=C&63,C=k[++x],U.windowStyle=(C&56)>>3,U.penStyle=C&7,U.virtualRowCount=U.rowCount+1,x},Kt.prototype.setWindowAttributes=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.winAttr;return C=k[++x],N.fillOpacity=(C&192)>>6,N.fillRed=(C&48)>>4,N.fillGreen=(C&12)>>2,N.fillBlue=C&3,C=k[++x],N.borderType=(C&192)>>6,N.borderRed=(C&48)>>4,N.borderGreen=(C&12)>>2,N.borderBlue=C&3,C=k[++x],N.borderType+=(C&128)>>5,N.wordWrap=(C&64)>>6,N.printDirection=(C&48)>>4,N.scrollDirection=(C&12)>>2,N.justify=C&3,C=k[++x],N.effectSpeed=(C&240)>>4,N.effectDirection=(C&12)>>2,N.displayEffect=C&3,x},Kt.prototype.flushDisplayed=function(x,A){for(var k=[],C=0;C<8;C++)A.windows[C].visible&&!A.windows[C].isEmpty()&&k.push(A.windows[C].getText());A.endPts=x,A.text=k.join(` - -`),this.pushCaption(A),A.startPts=x},Kt.prototype.pushCaption=function(x){x.text!==""&&(this.trigger("data",{startPts:x.startPts,endPts:x.endPts,text:x.text,stream:"cc708_"+x.serviceNum}),x.text="",x.startPts=x.endPts)},Kt.prototype.displayWindows=function(x,A){var k=this.current708Packet.data,C=k[++x],N=this.getPts(x);this.flushDisplayed(N,A);for(var U=0;U<8;U++)C&1<>4,N.offset=(C&12)>>2,N.penSize=C&3,C=k[++x],N.italics=(C&128)>>7,N.underline=(C&64)>>6,N.edgeType=(C&56)>>3,N.fontStyle=C&7,x},Kt.prototype.setPenColor=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.penColor;return C=k[++x],N.fgOpacity=(C&192)>>6,N.fgRed=(C&48)>>4,N.fgGreen=(C&12)>>2,N.fgBlue=C&3,C=k[++x],N.bgOpacity=(C&192)>>6,N.bgRed=(C&48)>>4,N.bgGreen=(C&12)>>2,N.bgBlue=C&3,C=k[++x],N.edgeRed=(C&48)>>4,N.edgeGreen=(C&12)>>2,N.edgeBlue=C&3,x},Kt.prototype.setPenLocation=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.penLoc;return A.currentWindow.pendingNewLine=!0,C=k[++x],N.row=C&15,C=k[++x],N.column=C&63,x},Kt.prototype.reset=function(x,A){var k=this.getPts(x);return this.flushDisplayed(k,A),this.initService(A.serviceNum,x)};var Gs={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},qi=function(x){return x===null?"":(x=Gs[x]||x,String.fromCharCode(x))},fn=14,tr=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],ss=function(){for(var x=[],A=fn+1;A--;)x.push({text:"",indent:0,offset:0});return x},bi=function(x,A){bi.prototype.init.call(this),this.field_=x||0,this.dataChannel_=A||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(k){var C,N,U,ne,le;if(C=k.ccData&32639,C===this.lastControlCode_){this.lastControlCode_=null;return}if((C&61440)===4096?this.lastControlCode_=C:C!==this.PADDING_&&(this.lastControlCode_=null),U=C>>>8,ne=C&255,C!==this.PADDING_)if(C===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(C===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(k.pts),this.flushDisplayed(k.pts),N=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=N,this.startPts_=k.pts;else if(C===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(k.pts);else if(C===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(k.pts);else if(C===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(k.pts);else if(C===this.CARRIAGE_RETURN_)this.clearFormatting(k.pts),this.flushDisplayed(k.pts),this.shiftRowsUp_(),this.startPts_=k.pts;else if(C===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(C===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(k.pts),this.displayed_=ss();else if(C===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=ss();else if(C===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(k.pts),this.displayed_=ss()),this.mode_="paintOn",this.startPts_=k.pts;else if(this.isSpecialCharacter(U,ne))U=(U&3)<<8,le=qi(U|ne),this[this.mode_](k.pts,le),this.column_++;else if(this.isExtCharacter(U,ne))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),U=(U&3)<<8,le=qi(U|ne),this[this.mode_](k.pts,le),this.column_++;else if(this.isMidRowCode(U,ne))this.clearFormatting(k.pts),this[this.mode_](k.pts," "),this.column_++,(ne&14)===14&&this.addFormatting(k.pts,["i"]),(ne&1)===1&&this.addFormatting(k.pts,["u"]);else if(this.isOffsetControlCode(U,ne)){const me=ne&3;this.nonDisplayed_[this.row_].offset=me,this.column_+=me}else if(this.isPAC(U,ne)){var de=tr.indexOf(C&7968);if(this.mode_==="rollUp"&&(de-this.rollUpRows_+1<0&&(de=this.rollUpRows_-1),this.setRollUp(k.pts,de)),de!==this.row_&&de>=0&&de<=14&&(this.clearFormatting(k.pts),this.row_=de),ne&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(k.pts,["u"]),(C&16)===16){const me=(C&14)>>1;this.column_=me*4,this.nonDisplayed_[this.row_].indent+=me}this.isColorPAC(ne)&&(ne&14)===14&&this.addFormatting(k.pts,["i"])}else this.isNormalChar(U)&&(ne===0&&(ne=null),le=qi(U),le+=qi(ne),this[this.mode_](k.pts,le),this.column_+=le.length)}};bi.prototype=new Oi,bi.prototype.flushDisplayed=function(x){const A=C=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+C+"."})},k=[];this.displayed_.forEach((C,N)=>{if(C&&C.text&&C.text.length){try{C.text=C.text.trim()}catch{A(N)}C.text.length&&k.push({text:C.text,line:N+1,position:10+Math.min(70,C.indent*10)+C.offset*2.5})}else C==null&&A(N)}),k.length&&this.trigger("data",{startPts:this.startPts_,endPts:x,content:k,stream:this.name_})},bi.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=ss(),this.nonDisplayed_=ss(),this.lastControlCode_=null,this.column_=0,this.row_=fn,this.rollUpRows_=2,this.formatting_=[]},bi.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},bi.prototype.isSpecialCharacter=function(x,A){return x===this.EXT_&&A>=48&&A<=63},bi.prototype.isExtCharacter=function(x,A){return(x===this.EXT_+1||x===this.EXT_+2)&&A>=32&&A<=63},bi.prototype.isMidRowCode=function(x,A){return x===this.EXT_&&A>=32&&A<=47},bi.prototype.isOffsetControlCode=function(x,A){return x===this.OFFSET_&&A>=33&&A<=35},bi.prototype.isPAC=function(x,A){return x>=this.BASE_&&x=64&&A<=127},bi.prototype.isColorPAC=function(x){return x>=64&&x<=79||x>=96&&x<=127},bi.prototype.isNormalChar=function(x){return x>=32&&x<=127},bi.prototype.setRollUp=function(x,A){if(this.mode_!=="rollUp"&&(this.row_=fn,this.mode_="rollUp",this.flushDisplayed(x),this.nonDisplayed_=ss(),this.displayed_=ss()),A!==void 0&&A!==this.row_)for(var k=0;k"},"");this[this.mode_](x,k)},bi.prototype.clearFormatting=function(x){if(this.formatting_.length){var A=this.formatting_.reverse().reduce(function(k,C){return k+""},"");this.formatting_=[],this[this.mode_](x,A)}},bi.prototype.popOn=function(x,A){var k=this.nonDisplayed_[this.row_].text;k+=A,this.nonDisplayed_[this.row_].text=k},bi.prototype.rollUp=function(x,A){var k=this.displayed_[this.row_].text;k+=A,this.displayed_[this.row_].text=k},bi.prototype.shiftRowsUp_=function(){var x;for(x=0;xA&&(k=-1);Math.abs(A-x)>ki;)x+=k*zs;return x},ns=function(x){var A,k;ns.prototype.init.call(this),this.type_=x||qs,this.push=function(C){if(C.type==="metadata"){this.trigger("data",C);return}this.type_!==qs&&C.type!==this.type_||(k===void 0&&(k=C.dts),C.dts=ls(C.dts,k),C.pts=ls(C.pts,k),A=C.dts,this.trigger("data",C))},this.flush=function(){k=A,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){k=void 0,A=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};ns.prototype=new Vs;var Di={TimestampRolloverStream:ns,handleRollover:ls},Ms=(x,A,k)=>{if(!x)return-1;for(var C=k;C";x.data[0]===ye.Utf8&&(k=rs(x.data,0,A),!(k<0)&&(x.mimeType=re(x.data,A,k),A=k+1,x.pictureType=x.data[A],A++,C=rs(x.data,0,A),!(C<0)&&(x.description=ae(x.data,A,C),A=C+1,x.mimeType===N?x.url=re(x.data,A,x.data.length):x.pictureData=x.data.subarray(A,x.data.length))))},"T*":function(x){x.data[0]===ye.Utf8&&(x.value=ae(x.data,1,x.data.length).replace(/\0*$/,""),x.values=x.value.split("\0"))},TXXX:function(x){var A;x.data[0]===ye.Utf8&&(A=rs(x.data,0,1),A!==-1&&(x.description=ae(x.data,1,A),x.value=ae(x.data,A+1,x.data.length).replace(/\0*$/,""),x.data=x.value))},"W*":function(x){x.url=re(x.data,0,x.data.length).replace(/\0.*$/,"")},WXXX:function(x){var A;x.data[0]===ye.Utf8&&(A=rs(x.data,0,1),A!==-1&&(x.description=ae(x.data,1,A),x.url=re(x.data,A+1,x.data.length).replace(/\0.*$/,"")))},PRIV:function(x){var A;for(A=0;A>>2;_t*=4,_t+=Ue[7]&3,Ee.timeStamp=_t,le.pts===void 0&&le.dts===void 0&&(le.pts=Ee.timeStamp,le.dts=Ee.timeStamp),this.trigger("timestamp",Ee)}le.frames.push(Ee),de+=10,de+=me}while(de>>4>1&&(ne+=N[ne]+1),U.pid===0)U.type="pat",x(N.subarray(ne),U),this.trigger("data",U);else if(U.pid===this.pmtPid)for(U.type="pmt",x(N.subarray(ne),U),this.trigger("data",U);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([N,ne,U]):this.processPes_(N,ne,U)},this.processPes_=function(N,U,ne){ne.pid===this.programMapTable.video?ne.streamType=Nt.H264_STREAM_TYPE:ne.pid===this.programMapTable.audio?ne.streamType=Nt.ADTS_STREAM_TYPE:ne.streamType=this.programMapTable["timed-metadata"][ne.pid],ne.type="pes",ne.data=N.subarray(U),this.trigger("data",ne)}},Se.prototype=new pt,Se.STREAM_TYPES={h264:27,adts:15},rt=function(){var x=this,A=!1,k={data:[],size:0},C={data:[],size:0},N={data:[],size:0},U,ne=function(de,me){var Ee;const Pe=de[0]<<16|de[1]<<8|de[2];me.data=new Uint8Array,Pe===1&&(me.packetLength=6+(de[4]<<8|de[5]),me.dataAlignmentIndicator=(de[6]&4)!==0,Ee=de[7],Ee&192&&(me.pts=(de[9]&14)<<27|(de[10]&255)<<20|(de[11]&254)<<12|(de[12]&255)<<5|(de[13]&254)>>>3,me.pts*=4,me.pts+=(de[13]&6)>>>1,me.dts=me.pts,Ee&64&&(me.dts=(de[14]&14)<<27|(de[15]&255)<<20|(de[16]&254)<<12|(de[17]&255)<<5|(de[18]&254)>>>3,me.dts*=4,me.dts+=(de[18]&6)>>>1)),me.data=de.subarray(9+de[8]))},le=function(de,me,Ee){var Pe=new Uint8Array(de.size),ht={type:me},Ue=0,_t=0,si=!1,Ds;if(!(!de.data.length||de.size<9)){for(ht.trackId=de.data[0].pid,Ue=0;Ue>5,de=((A[N+6]&3)+1)*1024,me=de*us/Nn[(A[N+2]&60)>>>2],A.byteLength-N>>6&3)+1,channelcount:(A[N+2]&1)<<2|(A[N+3]&192)>>>6,samplerate:Nn[(A[N+2]&60)>>>2],samplingfrequencyindex:(A[N+2]&60)>>>2,samplesize:16,data:A.subarray(N+7+ne,N+U)}),k++,N+=U}typeof Ee=="number"&&(this.skipWarn_(Ee,N),Ee=null),A=A.subarray(N)}},this.flush=function(){k=0,this.trigger("done")},this.reset=function(){A=void 0,this.trigger("reset")},this.endTimeline=function(){A=void 0,this.trigger("endedtimeline")}},Ks.prototype=new vs;var ir=Ks,Pr;Pr=function(x){var A=x.byteLength,k=0,C=0;this.length=function(){return 8*A},this.bitsAvailable=function(){return 8*A+C},this.loadWord=function(){var N=x.byteLength-A,U=new Uint8Array(4),ne=Math.min(4,A);if(ne===0)throw new Error("no bytes available");U.set(x.subarray(N,N+ne)),k=new DataView(U.buffer).getUint32(0),C=ne*8,A-=ne},this.skipBits=function(N){var U;C>N?(k<<=N,C-=N):(N-=C,U=Math.floor(N/8),N-=U*8,A-=U,this.loadWord(),k<<=N,C-=N)},this.readBits=function(N){var U=Math.min(C,N),ne=k>>>32-U;return C-=U,C>0?k<<=U:A>0&&this.loadWord(),U=N-U,U>0?ne<>>N)!==0)return k<<=N,C-=N,N;return this.loadWord(),N+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var N=this.skipLeadingZeros();return this.readBits(N+1)-1},this.readExpGolomb=function(){var N=this.readUnsignedExpGolomb();return 1&N?1+N>>>1:-1*(N>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var fu=Pr,Oa=t,mu=fu,_r,pn,go;pn=function(){var x=0,A,k;pn.prototype.init.call(this),this.push=function(C){var N;k?(N=new Uint8Array(k.byteLength+C.data.byteLength),N.set(k),N.set(C.data,k.byteLength),k=N):k=C.data;for(var U=k.byteLength;x3&&this.trigger("data",k.subarray(x+3)),k=null,x=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},pn.prototype=new Oa,go={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},_r=function(){var x=new pn,A,k,C,N,U,ne,le;_r.prototype.init.call(this),A=this,this.push=function(de){de.type==="video"&&(k=de.trackId,C=de.pts,N=de.dts,x.push(de))},x.on("data",function(de){var me={trackId:k,pts:C,dts:N,data:de,nalUnitTypeCode:de[0]&31};switch(me.nalUnitTypeCode){case 5:me.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:me.nalUnitType="sei_rbsp",me.escapedRBSP=U(de.subarray(1));break;case 7:me.nalUnitType="seq_parameter_set_rbsp",me.escapedRBSP=U(de.subarray(1)),me.config=ne(me.escapedRBSP);break;case 8:me.nalUnitType="pic_parameter_set_rbsp";break;case 9:me.nalUnitType="access_unit_delimiter_rbsp";break}A.trigger("data",me)}),x.on("done",function(){A.trigger("done")}),x.on("partialdone",function(){A.trigger("partialdone")}),x.on("reset",function(){A.trigger("reset")}),x.on("endedtimeline",function(){A.trigger("endedtimeline")}),this.flush=function(){x.flush()},this.partialFlush=function(){x.partialFlush()},this.reset=function(){x.reset()},this.endTimeline=function(){x.endTimeline()},le=function(de,me){var Ee=8,Pe=8,ht,Ue;for(ht=0;ht>4;return k=k>=0?k:0,N?k+20:k+10},Ma=function(x,A){return x.length-A<10||x[A]!==73||x[A+1]!==68||x[A+2]!==51?A:(A+=xl(x,A),Ma(x,A))},hs=function(x){var A=Ma(x,0);return x.length>=A+2&&(x[A]&255)===255&&(x[A+1]&240)===240&&(x[A+1]&22)===16},cs=function(x){return x[0]<<21|x[1]<<14|x[2]<<7|x[3]},On=function(x,A,k){var C,N="";for(C=A;C>5,C=x[A+4]<<3,N=x[A+3]&6144;return N|C|k},Pa=function(x,A){return x[A]===73&&x[A+1]===68&&x[A+2]===51?"timed-metadata":x[A]&!0&&(x[A+1]&240)===240?"audio":null},pu=function(x){for(var A=0;A+5>>2]}return null},bl=function(x){var A,k,C,N;A=10,x[5]&64&&(A+=4,A+=cs(x.subarray(10,14)));do{if(k=cs(x.subarray(A+4,A+8)),k<1)return null;if(N=String.fromCharCode(x[A],x[A+1],x[A+2],x[A+3]),N==="PRIV"){C=x.subarray(A+10,A+k+10);for(var U=0;U>>2;return de*=4,de+=le[7]&3,de}break}}A+=10,A+=k}while(A=3;){if(x[N]===73&&x[N+1]===68&&x[N+2]===51){if(x.length-N<10||(C=gu.parseId3TagSize(x,N),N+C>x.length))break;ne={type:"timed-metadata",data:x.subarray(N,N+C)},this.trigger("data",ne),N+=C;continue}else if((x[N]&255)===255&&(x[N+1]&240)===240){if(x.length-N<7||(C=gu.parseAdtsSize(x,N),N+C>x.length))break;le={type:"audio",data:x.subarray(N,N+C),pts:A,dts:A},this.trigger("data",le),N+=C;continue}N++}U=x.length-N,U>0?x=x.subarray(N):x=new Uint8Array},this.reset=function(){x=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){x=new Uint8Array,this.trigger("endedtimeline")}},Zr.prototype=new Yc;var yu=Zr,zh=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],y0=zh,v0=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],x0=v0,vo=t,Tl=Re,_l=bt,vu=ei,nr=te,Br=ni,Sl=Ft,qh=ir,b0=Qr.H264Stream,T0=yu,_0=Wc.isLikelyAacData,Xc=Ft.ONE_SECOND_IN_TS,Kh=y0,Wh=x0,xu,xo,bu,Ba,S0=function(x,A){A.stream=x,this.trigger("log",A)},Yh=function(x,A){for(var k=Object.keys(A),C=0;C=-1e4&&Ee<=de&&(!Pe||me>Ee)&&(Pe=Ue,me=Ee)));return Pe?Pe.gop:null},this.alignGopsAtStart_=function(le){var de,me,Ee,Pe,ht,Ue,_t,si;for(ht=le.byteLength,Ue=le.nalCount,_t=le.duration,de=me=0;deEe.pts){de++;continue}me++,ht-=Pe.byteLength,Ue-=Pe.nalCount,_t-=Pe.duration}return me===0?le:me===le.length?null:(si=le.slice(me),si.byteLength=ht,si.duration=_t,si.nalCount=Ue,si.pts=si[0].pts,si.dts=si[0].dts,si)},this.alignGopsAtEnd_=function(le){var de,me,Ee,Pe,ht,Ue;for(de=N.length-1,me=le.length-1,ht=null,Ue=!1;de>=0&&me>=0;){if(Ee=N[de],Pe=le[me],Ee.pts===Pe.pts){Ue=!0;break}if(Ee.pts>Pe.pts){de--;continue}de===N.length-1&&(ht=me),me--}if(!Ue&&ht===null)return null;var _t;if(Ue?_t=me:_t=ht,_t===0)return le;var si=le.slice(_t),Ds=si.reduce(function(En,aa){return En.byteLength+=aa.byteLength,En.duration+=aa.duration,En.nalCount+=aa.nalCount,En},{byteLength:0,duration:0,nalCount:0});return si.byteLength=Ds.byteLength,si.duration=Ds.duration,si.nalCount=Ds.nalCount,si.pts=si[0].pts,si.dts=si[0].dts,si},this.alignGopsWith=function(le){N=le}},xu.prototype=new vo,Ba=function(x,A){this.numberOfTracks=0,this.metadataStream=A,x=x||{},typeof x.remux<"u"?this.remuxTracks=!!x.remux:this.remuxTracks=!0,typeof x.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=x.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Ba.prototype.init.call(this),this.push=function(k){if(k.content||k.text)return this.pendingCaptions.push(k);if(k.frames)return this.pendingMetadata.push(k);this.pendingTracks.push(k.track),this.pendingBytes+=k.boxes.byteLength,k.track.type==="video"&&(this.videoTrack=k.track,this.pendingBoxes.push(k.boxes)),k.track.type==="audio"&&(this.audioTrack=k.track,this.pendingBoxes.unshift(k.boxes))}},Ba.prototype=new vo,Ba.prototype.flush=function(x){var A=0,k={captions:[],captionStreams:{},metadata:[],info:{}},C,N,U,ne=0,le;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(ne=this.videoTrack.timelineStartInfo.pts,Wh.forEach(function(de){k.info[de]=this.videoTrack[de]},this)):this.audioTrack&&(ne=this.audioTrack.timelineStartInfo.pts,Kh.forEach(function(de){k.info[de]=this.audioTrack[de]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?k.type=this.pendingTracks[0].type:k.type="combined",this.emittedTracks+=this.pendingTracks.length,U=Tl.initSegment(this.pendingTracks),k.initSegment=new Uint8Array(U.byteLength),k.initSegment.set(U),k.data=new Uint8Array(this.pendingBytes),le=0;le=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Ba.prototype.setRemux=function(x){this.remuxTracks=x},bu=function(x){var A=this,k=!0,C,N;bu.prototype.init.call(this),x=x||{},this.baseMediaDecodeTime=x.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var U={};this.transmuxPipeline_=U,U.type="aac",U.metadataStream=new Br.MetadataStream,U.aacStream=new T0,U.audioTimestampRolloverStream=new Br.TimestampRolloverStream("audio"),U.timedMetadataTimestampRolloverStream=new Br.TimestampRolloverStream("timed-metadata"),U.adtsStream=new qh,U.coalesceStream=new Ba(x,U.metadataStream),U.headOfPipeline=U.aacStream,U.aacStream.pipe(U.audioTimestampRolloverStream).pipe(U.adtsStream),U.aacStream.pipe(U.timedMetadataTimestampRolloverStream).pipe(U.metadataStream).pipe(U.coalesceStream),U.metadataStream.on("timestamp",function(ne){U.aacStream.setTimestamp(ne.timeStamp)}),U.aacStream.on("data",function(ne){ne.type!=="timed-metadata"&&ne.type!=="audio"||U.audioSegmentStream||(N=N||{timelineStartInfo:{baseMediaDecodeTime:A.baseMediaDecodeTime},codec:"adts",type:"audio"},U.coalesceStream.numberOfTracks++,U.audioSegmentStream=new xo(N,x),U.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),U.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),U.adtsStream.pipe(U.audioSegmentStream).pipe(U.coalesceStream),A.trigger("trackinfo",{hasAudio:!!N,hasVideo:!!C}))}),U.coalesceStream.on("data",this.trigger.bind(this,"data")),U.coalesceStream.on("done",this.trigger.bind(this,"done")),Yh(this,U)},this.setupTsPipeline=function(){var U={};this.transmuxPipeline_=U,U.type="ts",U.metadataStream=new Br.MetadataStream,U.packetStream=new Br.TransportPacketStream,U.parseStream=new Br.TransportParseStream,U.elementaryStream=new Br.ElementaryStream,U.timestampRolloverStream=new Br.TimestampRolloverStream,U.adtsStream=new qh,U.h264Stream=new b0,U.captionStream=new Br.CaptionStream(x),U.coalesceStream=new Ba(x,U.metadataStream),U.headOfPipeline=U.packetStream,U.packetStream.pipe(U.parseStream).pipe(U.elementaryStream).pipe(U.timestampRolloverStream),U.timestampRolloverStream.pipe(U.h264Stream),U.timestampRolloverStream.pipe(U.adtsStream),U.timestampRolloverStream.pipe(U.metadataStream).pipe(U.coalesceStream),U.h264Stream.pipe(U.captionStream).pipe(U.coalesceStream),U.elementaryStream.on("data",function(ne){var le;if(ne.type==="metadata"){for(le=ne.tracks.length;le--;)!C&&ne.tracks[le].type==="video"?(C=ne.tracks[le],C.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime):!N&&ne.tracks[le].type==="audio"&&(N=ne.tracks[le],N.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime);C&&!U.videoSegmentStream&&(U.coalesceStream.numberOfTracks++,U.videoSegmentStream=new xu(C,x),U.videoSegmentStream.on("log",A.getLogTrigger_("videoSegmentStream")),U.videoSegmentStream.on("timelineStartInfo",function(de){N&&!x.keepOriginalTimestamps&&(N.timelineStartInfo=de,U.audioSegmentStream.setEarliestDts(de.dts-A.baseMediaDecodeTime))}),U.videoSegmentStream.on("processedGopsInfo",A.trigger.bind(A,"gopInfo")),U.videoSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"videoSegmentTimingInfo")),U.videoSegmentStream.on("baseMediaDecodeTime",function(de){N&&U.audioSegmentStream.setVideoBaseMediaDecodeTime(de)}),U.videoSegmentStream.on("timingInfo",A.trigger.bind(A,"videoTimingInfo")),U.h264Stream.pipe(U.videoSegmentStream).pipe(U.coalesceStream)),N&&!U.audioSegmentStream&&(U.coalesceStream.numberOfTracks++,U.audioSegmentStream=new xo(N,x),U.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),U.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),U.audioSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"audioSegmentTimingInfo")),U.adtsStream.pipe(U.audioSegmentStream).pipe(U.coalesceStream)),A.trigger("trackinfo",{hasAudio:!!N,hasVideo:!!C})}}),U.coalesceStream.on("data",this.trigger.bind(this,"data")),U.coalesceStream.on("id3Frame",function(ne){ne.dispatchType=U.metadataStream.dispatchType,A.trigger("id3Frame",ne)}),U.coalesceStream.on("caption",this.trigger.bind(this,"caption")),U.coalesceStream.on("done",this.trigger.bind(this,"done")),Yh(this,U)},this.setBaseMediaDecodeTime=function(U){var ne=this.transmuxPipeline_;x.keepOriginalTimestamps||(this.baseMediaDecodeTime=U),N&&(N.timelineStartInfo.dts=void 0,N.timelineStartInfo.pts=void 0,nr.clearDtsInfo(N),ne.audioTimestampRolloverStream&&ne.audioTimestampRolloverStream.discontinuity()),C&&(ne.videoSegmentStream&&(ne.videoSegmentStream.gopCache_=[]),C.timelineStartInfo.dts=void 0,C.timelineStartInfo.pts=void 0,nr.clearDtsInfo(C),ne.captionStream.reset()),ne.timestampRolloverStream&&ne.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(U){N&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(U)},this.setRemux=function(U){var ne=this.transmuxPipeline_;x.remux=U,ne&&ne.coalesceStream&&ne.coalesceStream.setRemux(U)},this.alignGopsWith=function(U){C&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(U)},this.getLogTrigger_=function(U){var ne=this;return function(le){le.stream=U,ne.trigger("log",le)}},this.push=function(U){if(k){var ne=_0(U);ne&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!ne&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),k=!1}this.transmuxPipeline_.headOfPipeline.push(U)},this.flush=function(){k=!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()}},bu.prototype=new vo;var E0={Transmuxer:bu},w0=function(x){return x>>>0},A0=function(x){return("00"+x.toString(16)).slice(-2)},bo={toUnsigned:w0,toHexString:A0},El=function(x){var A="";return A+=String.fromCharCode(x[0]),A+=String.fromCharCode(x[1]),A+=String.fromCharCode(x[2]),A+=String.fromCharCode(x[3]),A},Zh=El,Jh=bo.toUnsigned,ef=Zh,Qc=function(x,A){var k=[],C,N,U,ne,le;if(!A.length)return null;for(C=0;C1?C+N:x.byteLength,U===A[0]&&(A.length===1?k.push(x.subarray(C+8,ne)):(le=Qc(x.subarray(C+8,ne),A.slice(1)),le.length&&(k=k.concat(le)))),C=ne;return k},Tu=Qc,tf=bo.toUnsigned,To=r.getUint64,C0=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4))};return A.version===1?A.baseMediaDecodeTime=To(x.subarray(4)):A.baseMediaDecodeTime=tf(x[4]<<24|x[5]<<16|x[6]<<8|x[7]),A},Zc=C0,k0=function(x){var A=new DataView(x.buffer,x.byteOffset,x.byteLength),k={version:x[0],flags:new Uint8Array(x.subarray(1,4)),trackId:A.getUint32(4)},C=k.flags[2]&1,N=k.flags[2]&2,U=k.flags[2]&8,ne=k.flags[2]&16,le=k.flags[2]&32,de=k.flags[0]&65536,me=k.flags[0]&131072,Ee;return Ee=8,C&&(Ee+=4,k.baseDataOffset=A.getUint32(12),Ee+=4),N&&(k.sampleDescriptionIndex=A.getUint32(Ee),Ee+=4),U&&(k.defaultSampleDuration=A.getUint32(Ee),Ee+=4),ne&&(k.defaultSampleSize=A.getUint32(Ee),Ee+=4),le&&(k.defaultSampleFlags=A.getUint32(Ee)),de&&(k.durationIsEmpty=!0),!C&&me&&(k.baseDataOffsetIsMoof=!0),k},Jc=k0,sf=function(x){return{isLeading:(x[0]&12)>>>2,dependsOn:x[0]&3,isDependedOn:(x[1]&192)>>>6,hasRedundancy:(x[1]&48)>>>4,paddingValue:(x[1]&14)>>>1,isNonSyncSample:x[1]&1,degradationPriority:x[2]<<8|x[3]}},wl=sf,_o=wl,D0=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4)),samples:[]},k=new DataView(x.buffer,x.byteOffset,x.byteLength),C=A.flags[2]&1,N=A.flags[2]&4,U=A.flags[1]&1,ne=A.flags[1]&2,le=A.flags[1]&4,de=A.flags[1]&8,me=k.getUint32(4),Ee=8,Pe;for(C&&(A.dataOffset=k.getInt32(Ee),Ee+=4),N&&me&&(Pe={flags:_o(x.subarray(Ee,Ee+4))},Ee+=4,U&&(Pe.duration=k.getUint32(Ee),Ee+=4),ne&&(Pe.size=k.getUint32(Ee),Ee+=4),de&&(A.version===1?Pe.compositionTimeOffset=k.getInt32(Ee):Pe.compositionTimeOffset=k.getUint32(Ee),Ee+=4),A.samples.push(Pe),me--);me--;)Pe={},U&&(Pe.duration=k.getUint32(Ee),Ee+=4),ne&&(Pe.size=k.getUint32(Ee),Ee+=4),le&&(Pe.flags=_o(x.subarray(Ee,Ee+4)),Ee+=4),de&&(A.version===1?Pe.compositionTimeOffset=k.getInt32(Ee):Pe.compositionTimeOffset=k.getUint32(Ee),Ee+=4),A.samples.push(Pe);return A},Al=D0,ed={tfdt:Zc,trun:Al},td={parseTfdt:ed.tfdt,parseTrun:ed.trun},id=function(x){for(var A=0,k=String.fromCharCode(x[A]),C="";k!=="\0";)C+=k,A++,k=String.fromCharCode(x[A]);return C+=k,C},sd={uint8ToCString:id},Cl=sd.uint8ToCString,nf=r.getUint64,rf=function(x){var A=4,k=x[0],C,N,U,ne,le,de,me,Ee;if(k===0){C=Cl(x.subarray(A)),A+=C.length,N=Cl(x.subarray(A)),A+=N.length;var Pe=new DataView(x.buffer);U=Pe.getUint32(A),A+=4,le=Pe.getUint32(A),A+=4,de=Pe.getUint32(A),A+=4,me=Pe.getUint32(A),A+=4}else if(k===1){var Pe=new DataView(x.buffer);U=Pe.getUint32(A),A+=4,ne=nf(x.subarray(A)),A+=8,de=Pe.getUint32(A),A+=4,me=Pe.getUint32(A),A+=4,C=Cl(x.subarray(A)),A+=C.length,N=Cl(x.subarray(A)),A+=N.length}Ee=new Uint8Array(x.subarray(A,x.byteLength));var ht={scheme_id_uri:C,value:N,timescale:U||1,presentation_time:ne,presentation_time_delta:le,event_duration:de,id:me,message_data:Ee};return R0(k,ht)?ht:void 0},L0=function(x,A,k,C){return x||x===0?x/A:C+k/A},R0=function(x,A){var k=A.scheme_id_uri!=="\0",C=x===0&&af(A.presentation_time_delta)&&k,N=x===1&&af(A.presentation_time)&&k;return!(x>1)&&C||N},af=function(x){return x!==void 0||x!==null},I0={parseEmsgBox:rf,scaleTime:L0},kl;typeof window<"u"?kl=window:typeof s<"u"?kl=s:typeof self<"u"?kl=self:kl={};var yn=kl,Jr=bo.toUnsigned,So=bo.toHexString,fs=Tu,Fa=Zh,_u=I0,nd=Jc,N0=Al,Eo=Zc,rd=r.getUint64,wo,Su,ad,ea,Ua,Dl,od,Fr=yn,of=st.parseId3Frames;wo=function(x){var A={},k=fs(x,["moov","trak"]);return k.reduce(function(C,N){var U,ne,le,de,me;return U=fs(N,["tkhd"])[0],!U||(ne=U[0],le=ne===0?12:20,de=Jr(U[le]<<24|U[le+1]<<16|U[le+2]<<8|U[le+3]),me=fs(N,["mdia","mdhd"])[0],!me)?null:(ne=me[0],le=ne===0?12:20,C[de]=Jr(me[le]<<24|me[le+1]<<16|me[le+2]<<8|me[le+3]),C)},A)},Su=function(x,A){var k;k=fs(A,["moof","traf"]);var C=k.reduce(function(N,U){var ne=fs(U,["tfhd"])[0],le=Jr(ne[4]<<24|ne[5]<<16|ne[6]<<8|ne[7]),de=x[le]||9e4,me=fs(U,["tfdt"])[0],Ee=new DataView(me.buffer,me.byteOffset,me.byteLength),Pe;me[0]===1?Pe=rd(me.subarray(4,12)):Pe=Ee.getUint32(4);let ht;return typeof Pe=="bigint"?ht=Pe/Fr.BigInt(de):typeof Pe=="number"&&!isNaN(Pe)&&(ht=Pe/de),ht11?(N.codec+=".",N.codec+=So(Ue[9]),N.codec+=So(Ue[10]),N.codec+=So(Ue[11])):N.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(N.codec)?(Ue=ht.subarray(28),_t=Fa(Ue.subarray(4,8)),_t==="esds"&&Ue.length>20&&Ue[19]!==0?(N.codec+="."+So(Ue[19]),N.codec+="."+So(Ue[20]>>>2&63).replace(/^0/,"")):N.codec="mp4a.40.2"):N.codec=N.codec.toLowerCase())}var si=fs(C,["mdia","mdhd"])[0];si&&(N.timescale=Dl(si)),k.push(N)}),k},od=function(x,A=0){var k=fs(x,["emsg"]);return k.map(C=>{var N=_u.parseEmsgBox(new Uint8Array(C)),U=of(N.message_data);return{cueTime:_u.scaleTime(N.presentation_time,N.timescale,N.presentation_time_delta,A),duration:_u.scaleTime(N.event_duration,N.timescale),frames:U}})};var Ao={findBox:fs,parseType:Fa,timescale:wo,startTime:Su,compositionStartTime:ad,videoTrackIds:ea,tracks:Ua,getTimescaleFromMediaHeader:Dl,getEmsgID3:od};const{parseTrun:lf}=td,{findBox:uf}=Ao;var cf=yn,O0=function(x){var A=uf(x,["moof","traf"]),k=uf(x,["mdat"]),C=[];return k.forEach(function(N,U){var ne=A[U];C.push({mdat:N,traf:ne})}),C},df=function(x,A,k){var C=A,N=k.defaultSampleDuration||0,U=k.defaultSampleSize||0,ne=k.trackId,le=[];return x.forEach(function(de){var me=lf(de),Ee=me.samples;Ee.forEach(function(Pe){Pe.duration===void 0&&(Pe.duration=N),Pe.size===void 0&&(Pe.size=U),Pe.trackId=ne,Pe.dts=C,Pe.compositionTimeOffset===void 0&&(Pe.compositionTimeOffset=0),typeof C=="bigint"?(Pe.pts=C+cf.BigInt(Pe.compositionTimeOffset),C+=cf.BigInt(Pe.duration)):(Pe.pts=C+Pe.compositionTimeOffset,C+=Pe.duration)}),le=le.concat(Ee)}),le},ld={getMdatTrafPairs:O0,parseSamples:df},ud=zi.discardEmulationPreventionBytes,rr=ks.CaptionStream,Co=Tu,Mn=Zc,ko=Jc,{getMdatTrafPairs:cd,parseSamples:Eu}=ld,wu=function(x,A){for(var k=x,C=0;C0?Mn(Ee[0]).baseMediaDecodeTime:0,ht=Co(ne,["trun"]),Ue,_t;A===me&&ht.length>0&&(Ue=Eu(ht,Pe,de),_t=dd(U,Ue,me),k[me]||(k[me]={seiNals:[],logs:[]}),k[me].seiNals=k[me].seiNals.concat(_t.seiNals),k[me].logs=k[me].logs.concat(_t.logs))}),k},hf=function(x,A,k){var C;if(A===null)return null;C=ja(x,A);var N=C[A]||{};return{seiNals:N.seiNals,logs:N.logs,timescale:k}},Au=function(){var x=!1,A,k,C,N,U,ne;this.isInitialized=function(){return x},this.init=function(le){A=new rr,x=!0,ne=le?le.isPartial:!1,A.on("data",function(de){de.startTime=de.startPts/N,de.endTime=de.endPts/N,U.captions.push(de),U.captionStreams[de.stream]=!0}),A.on("log",function(de){U.logs.push(de)})},this.isNewInit=function(le,de){return le&&le.length===0||de&&typeof de=="object"&&Object.keys(de).length===0?!1:C!==le[0]||N!==de[C]},this.parse=function(le,de,me){var Ee;if(this.isInitialized()){if(!de||!me)return null;if(this.isNewInit(de,me))C=de[0],N=me[C];else if(C===null||!N)return k.push(le),null}else return null;for(;k.length>0;){var Pe=k.shift();this.parse(Pe,de,me)}return Ee=hf(le,C,N),Ee&&Ee.logs&&(U.logs=U.logs.concat(Ee.logs)),Ee===null||!Ee.seiNals?U.logs.length?{logs:U.logs,captions:[],captionStreams:[]}:null:(this.pushNals(Ee.seiNals),this.flushStream(),U)},this.pushNals=function(le){if(!this.isInitialized()||!le||le.length===0)return null;le.forEach(function(de){A.push(de)})},this.flushStream=function(){if(!this.isInitialized())return null;ne?A.partialFlush():A.flush()},this.clearParsedCaptions=function(){U.captions=[],U.captionStreams={},U.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;A.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){k=[],C=null,N=null,U?this.clearParsedCaptions():U={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},Do=Au;const{parseTfdt:M0}=td,Ss=Tu,{getTimescaleFromMediaHeader:hd}=Ao,{parseSamples:Ur,getMdatTrafPairs:ff}=ld;var ta=function(){let x=9e4;this.init=function(A){const k=Ss(A,["moov","trak","mdia","mdhd"])[0];k&&(x=hd(k))},this.parseSegment=function(A){const k=[],C=ff(A);let N=0;return C.forEach(function(U){const ne=U.mdat,le=U.traf,de=Ss(le,["tfdt"])[0],me=Ss(le,["tfhd"])[0],Ee=Ss(le,["trun"]);if(de&&(N=M0(de).baseMediaDecodeTime),Ee.length&&me){const Pe=Ur(Ee,N,me);let ht=0;Pe.forEach(function(Ue){const _t="utf-8",si=new TextDecoder(_t),Ds=ne.slice(ht,ht+Ue.size);if(Ss(Ds,["vtte"])[0]){ht+=Ue.size;return}Ss(Ds,["vttc"]).forEach(function(Nl){const as=Ss(Nl,["payl"])[0],$a=Ss(Nl,["sttg"])[0],jr=Ue.pts/x,oa=(Ue.pts+Ue.duration)/x;let Ui,Sr;if(as)try{Ui=si.decode(as)}catch(Js){console.error(Js)}if($a)try{Sr=si.decode($a)}catch(Js){console.error(Js)}Ue.duration&&Ui&&k.push({cueText:Ui,start:jr,end:oa,settings:Sr})}),ht+=Ue.size})}}),k}},Ll=Os,md=function(x){var A=x[1]&31;return A<<=8,A|=x[2],A},Lo=function(x){return!!(x[1]&64)},Rl=function(x){var A=0;return(x[3]&48)>>>4>1&&(A+=x[4]+1),A},Pn=function(x,A){var k=md(x);return k===0?"pat":k===A?"pmt":A?"pes":null},Ro=function(x){var A=Lo(x),k=4+Rl(x);return A&&(k+=x[k]+1),(x[k+10]&31)<<8|x[k+11]},Io=function(x){var A={},k=Lo(x),C=4+Rl(x);if(k&&(C+=x[C]+1),!!(x[C+5]&1)){var N,U,ne;N=(x[C+1]&15)<<8|x[C+2],U=3+N-4,ne=(x[C+10]&15)<<8|x[C+11];for(var le=12+ne;le=x.byteLength)return null;var C=null,N;return N=x[k+7],N&192&&(C={},C.pts=(x[k+9]&14)<<27|(x[k+10]&255)<<20|(x[k+11]&254)<<12|(x[k+12]&255)<<5|(x[k+13]&254)>>>3,C.pts*=4,C.pts+=(x[k+13]&6)>>>1,C.dts=C.pts,N&64&&(C.dts=(x[k+14]&14)<<27|(x[k+15]&255)<<20|(x[k+16]&254)<<12|(x[k+17]&255)<<5|(x[k+18]&254)>>>3,C.dts*=4,C.dts+=(x[k+18]&6)>>>1)),C},vn=function(x){switch(x){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}},Bn=function(x){for(var A=4+Rl(x),k=x.subarray(A),C=0,N=0,U=!1,ne;N3&&(ne=vn(k[N+3]&31),ne==="slice_layer_without_partitioning_rbsp_idr"&&(U=!0)),U},ia={parseType:Pn,parsePat:Ro,parsePmt:Io,parsePayloadUnitStartIndicator:Lo,parsePesType:Cu,parsePesTime:Il,videoPacketContainsKeyFrame:Bn},ar=Os,an=Di.handleRollover,hi={};hi.ts=ia,hi.aac=Wc;var sa=Ft.ONE_SECOND_IN_TS,Ws=188,Fn=71,mf=function(x,A){for(var k=0,C=Ws,N,U;C=0;){if(x[C]===Fn&&(x[N]===Fn||N===x.byteLength)){if(U=x.subarray(C,N),ne=hi.ts.parseType(U,A.pid),ne==="pes"&&(le=hi.ts.parsePesType(U,A.table),de=hi.ts.parsePayloadUnitStartIndicator(U),le==="audio"&&de&&(me=hi.ts.parsePesTime(U),me&&(me.type="audio",k.audio.push(me),Ee=!0))),Ee)break;C-=Ws,N-=Ws;continue}C--,N--}},Zi=function(x,A,k){for(var C=0,N=Ws,U,ne,le,de,me,Ee,Pe,ht,Ue=!1,_t={data:[],size:0};N=0;){if(x[C]===Fn&&x[N]===Fn){if(U=x.subarray(C,N),ne=hi.ts.parseType(U,A.pid),ne==="pes"&&(le=hi.ts.parsePesType(U,A.table),de=hi.ts.parsePayloadUnitStartIndicator(U),le==="video"&&de&&(me=hi.ts.parsePesTime(U),me&&(me.type="video",k.video.push(me),Ue=!0))),Ue)break;C-=Ws,N-=Ws;continue}C--,N--}},Ti=function(x,A){if(x.audio&&x.audio.length){var k=A;(typeof k>"u"||isNaN(k))&&(k=x.audio[0].dts),x.audio.forEach(function(U){U.dts=an(U.dts,k),U.pts=an(U.pts,k),U.dtsTime=U.dts/sa,U.ptsTime=U.pts/sa})}if(x.video&&x.video.length){var C=A;if((typeof C>"u"||isNaN(C))&&(C=x.video[0].dts),x.video.forEach(function(U){U.dts=an(U.dts,C),U.pts=an(U.pts,C),U.dtsTime=U.dts/sa,U.ptsTime=U.pts/sa}),x.firstKeyFrame){var N=x.firstKeyFrame;N.dts=an(N.dts,C),N.pts=an(N.pts,C),N.dtsTime=N.dts/sa,N.ptsTime=N.pts/sa}}},na=function(x){for(var A=!1,k=0,C=null,N=null,U=0,ne=0,le;x.length-ne>=3;){var de=hi.aac.parseType(x,ne);switch(de){case"timed-metadata":if(x.length-ne<10){A=!0;break}if(U=hi.aac.parseId3TagSize(x,ne),U>x.length){A=!0;break}N===null&&(le=x.subarray(ne,ne+U),N=hi.aac.parseAacTimestamp(le)),ne+=U;break;case"audio":if(x.length-ne<7){A=!0;break}if(U=hi.aac.parseAdtsSize(x,ne),U>x.length){A=!0;break}C===null&&(le=x.subarray(ne,ne+U),C=hi.aac.parseSampleRate(le)),k++,ne+=U;break;default:ne++;break}if(A)return null}if(C===null||N===null)return null;var me=sa/C,Ee={audio:[{type:"audio",dts:N,pts:N},{type:"audio",dts:N+k*1024*me,pts:N+k*1024*me}]};return Ee},Un=function(x){var A={pid:null,table:null},k={};mf(x,A);for(var C in A.table)if(A.table.hasOwnProperty(C)){var N=A.table[C];switch(N){case ar.H264_STREAM_TYPE:k.video=[],Zi(x,A,k),k.video.length===0&&delete k.video;break;case ar.ADTS_STREAM_TYPE:k.audio=[],Ps(x,A,k),k.audio.length===0&&delete k.audio;break}}return k},pd=function(x,A){var k=hi.aac.isLikelyAacData(x),C;return k?C=na(x):C=Un(x),!C||!C.audio&&!C.video?null:(Ti(C,A),C)},ra={inspect:pd,parseAudioPes_:Ps};const pf=function(x,A){A.on("data",function(k){const C=k.initSegment;k.initSegment={data:C.buffer,byteOffset:C.byteOffset,byteLength:C.byteLength};const N=k.data;k.data=N.buffer,x.postMessage({action:"data",segment:k,byteOffset:N.byteOffset,byteLength:N.byteLength},[k.data])}),A.on("done",function(k){x.postMessage({action:"done"})}),A.on("gopInfo",function(k){x.postMessage({action:"gopInfo",gopInfo:k})}),A.on("videoSegmentTimingInfo",function(k){const C={start:{decode:Ft.videoTsToSeconds(k.start.dts),presentation:Ft.videoTsToSeconds(k.start.pts)},end:{decode:Ft.videoTsToSeconds(k.end.dts),presentation:Ft.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Ft.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Ft.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:C})}),A.on("audioSegmentTimingInfo",function(k){const C={start:{decode:Ft.videoTsToSeconds(k.start.dts),presentation:Ft.videoTsToSeconds(k.start.pts)},end:{decode:Ft.videoTsToSeconds(k.end.dts),presentation:Ft.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Ft.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Ft.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:C})}),A.on("id3Frame",function(k){x.postMessage({action:"id3Frame",id3Frame:k})}),A.on("caption",function(k){x.postMessage({action:"caption",caption:k})}),A.on("trackinfo",function(k){x.postMessage({action:"trackinfo",trackInfo:k})}),A.on("audioTimingInfo",function(k){x.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Ft.videoTsToSeconds(k.start),end:Ft.videoTsToSeconds(k.end)}})}),A.on("videoTimingInfo",function(k){x.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Ft.videoTsToSeconds(k.start),end:Ft.videoTsToSeconds(k.end)}})}),A.on("log",function(k){x.postMessage({action:"log",log:k})})};class gd{constructor(A,k){this.options=k||{},this.self=A,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new E0.Transmuxer(this.options),pf(this.self,this.transmuxer)}pushMp4Captions(A){this.captionParser||(this.captionParser=new Do,this.captionParser.init());const k=new Uint8Array(A.data,A.byteOffset,A.byteLength),C=this.captionParser.parse(k,A.trackIds,A.timescales);this.self.postMessage({action:"mp4Captions",captions:C&&C.captions||[],logs:C&&C.logs||[],data:k.buffer},[k.buffer])}initMp4WebVttParser(A){this.webVttParser||(this.webVttParser=new ta);const k=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.webVttParser.init(k)}getMp4WebVttText(A){this.webVttParser||(this.webVttParser=new ta);const k=new Uint8Array(A.data,A.byteOffset,A.byteLength),C=this.webVttParser.parseSegment(k);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:C||[],data:k.buffer},[k.buffer])}probeMp4StartTime({timescales:A,data:k}){const C=Ao.startTime(A,k);this.self.postMessage({action:"probeMp4StartTime",startTime:C,data:k},[k.buffer])}probeMp4Tracks({data:A}){const k=Ao.tracks(A);this.self.postMessage({action:"probeMp4Tracks",tracks:k,data:A},[A.buffer])}probeEmsgID3({data:A,offset:k}){const C=Ao.getEmsgID3(A,k);this.self.postMessage({action:"probeEmsgID3",id3Frames:C,emsgData:A},[A.buffer])}probeTs({data:A,baseStartTime:k}){const C=typeof k=="number"&&!isNaN(k)?k*Ft.ONE_SECOND_IN_TS:void 0,N=ra.inspect(A,C);let U=null;N&&(U={hasVideo:N.video&&N.video.length===2||!1,hasAudio:N.audio&&N.audio.length===2||!1},U.hasVideo&&(U.videoStart=N.video[0].ptsTime),U.hasAudio&&(U.audioStart=N.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:U,data:A},[A.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(A){const k=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.transmuxer.push(k)}reset(){this.transmuxer.reset()}setTimestampOffset(A){const k=A.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Ft.secondsToVideoTs(k)))}setAudioAppendStart(A){this.transmuxer.setAudioAppendStart(Math.ceil(Ft.secondsToVideoTs(A.appendStart)))}setRemux(A){this.transmuxer.setRemux(A.remux)}flush(A){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(A){this.transmuxer.alignGopsWith(A.gopsToAlignWith.slice())}}self.onmessage=function(x){if(x.data.action==="init"&&x.data.options){this.messageHandlers=new gd(self,x.data.options);return}this.messageHandlers||(this.messageHandlers=new gd(self)),x.data&&x.data.action&&x.data.action!=="init"&&this.messageHandlers[x.data.action]&&this.messageHandlers[x.data.action](x.data)}}));var aF=Xk(rF);const oF=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:a,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:a,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)},lF=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},uF=(s,e)=>{e.gopInfo=s.data.gopInfo},Jk=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:a,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:p,onId3:y,onCaptions:v,onDone:b,onEndedTimeline:_,onTransmuxerLog:E,isEndOfTimeline:L,segment:I,triggerSegmentEventFn:R}=s,$={buffer:[]};let P=L;const B=H=>{e.currentTransmux===s&&(H.data.action==="data"&&oF(H,$,a),H.data.action==="trackinfo"&&u(H.data.trackInfo),H.data.action==="gopInfo"&&uF(H,$),H.data.action==="audioTimingInfo"&&c(H.data.audioTimingInfo),H.data.action==="videoTimingInfo"&&d(H.data.videoTimingInfo),H.data.action==="videoSegmentTimingInfo"&&f(H.data.videoSegmentTimingInfo),H.data.action==="audioSegmentTimingInfo"&&p(H.data.audioSegmentTimingInfo),H.data.action==="id3Frame"&&y([H.data.id3Frame],H.data.id3Frame.dispatchType),H.data.action==="caption"&&v(H.data.caption),H.data.action==="endedtimeline"&&(P=!1,_()),H.data.action==="log"&&E(H.data.log),H.data.type==="transmuxed"&&(P||(e.onmessage=null,lF({transmuxedData:$,callback:b}),eD(e))))},O=()=>{const H={message:"Received an error message from the transmuxer worker",metadata:{errorType:De.Error.StreamingFailedToTransmuxSegment,segmentInfo:Zl({segment:I})}};b(null,H)};if(e.onmessage=B,e.onerror=O,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 H=t instanceof ArrayBuffer?t:t.buffer,D=t instanceof ArrayBuffer?0:t.byteOffset;R({type:"segmenttransmuxingstart",segment:I}),e.postMessage({action:"push",data:H,byteOffset:D,byteLength:t.byteLength},[H])}L&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},eD=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Jk(s.currentTransmux))},l2=(s,e)=>{s.postMessage({action:e}),eD(s)},tD=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,l2(e,s);return}e.transmuxQueue.push(l2.bind(null,e,s))},cF=s=>{tD("reset",s)},dF=s=>{tD("endTimeline",s)},iD=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Jk(s);return}s.transmuxer.transmuxQueue.push(s)},hF=s=>{const e=new aF;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 iv={reset:cF,endTimeline:dF,transmux:iD,createTransmuxer:hF};const gc=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=Ns({},s,{endAction:null,transmuxer:null,callback:null}),r=a=>{a.data.action===t&&(e.removeEventListener("message",r),a.data.data&&(a.data.data=new Uint8Array(a.data.data,s.byteOffset||0,s.byteLength||a.data.data.byteLength),s.data&&(s.data=a.data.data)),i(a.data))};if(e.addEventListener("message",r),s.data){const a=s.data instanceof ArrayBuffer;n.byteOffset=a?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[a?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},_a={FAILURE:2,TIMEOUT:-101,ABORTED:-102},sD="wvtt",Sx=s=>{s.forEach(e=>{e.abort()})},fF=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),mF=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},jb=(s,e)=>{const{requestType:t}=e,i=au({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:_a.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:_a.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:_a.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:_a.FAILURE,xhr:e,metadata:i}:null},u2=(s,e,t,i)=>(n,r)=>{const a=r.response,u=jb(n,r);if(u)return t(u,s);if(a.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:_a.FAILURE,xhr:r},s);const c=new DataView(a),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let p=0;p{e===sD&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},gF=(s,e,t)=>{e===sD&&gc({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},nD=(s,e)=>{const t=ub(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:_a.FAILURE,metadata:{mediaType:n}})}gc({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"&&pF(s,r.codec))}),e(null))})},yF=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=jb(i,n);if(r)return e(r,s);const a=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=a,e(null,s);s.map.bytes=a,nD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},vF=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const a=jb(n,r);if(a)return e(a,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:sF(r.responseText.substring(s.lastReachedChar||0));return s.stats=fF(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},xF=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,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 R=i.bind(null,s,"video","end"),$=()=>iD({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:P=>{P.type=P.type==="combined"?"video":P.type,f(s,P)},onTrackInfo:P=>{t&&(_&&(P.isMuxed=!0),t(s,P))},onAudioTimingInfo:P=>{E&&typeof P.start<"u"&&(E(P.start),E=null),L&&typeof P.end<"u"&&L(P.end)},onVideoTimingInfo:P=>{I&&typeof P.start<"u"&&(I(P.start),I=null),R&&typeof P.end<"u"&&R(P.end)},onVideoSegmentTimingInfo:P=>{const B={pts:{start:P.start.presentation,end:P.end.presentation},dts:{start:P.start.decode,end:P.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:B}),n(P)},onAudioSegmentTimingInfo:P=>{const B={pts:{start:P.start.pts,end:P.end.pts},dts:{start:P.start.dts,end:P.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:B}),r(P)},onId3:(P,B)=>{a(s,P,B)},onCaptions:P=>{u(s,[P])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:y,onDone:(P,B)=>{p&&(P.type=P.type==="combined"?"video":P.type,v({type:"segmenttransmuxingcomplete",segment:s}),p(B,s,P))},segment:s,triggerSegmentEventFn:v});gc({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:P=>{s.bytes=e=P.data;const B=P.result;B&&(t(s,{hasAudio:B.hasAudio,hasVideo:B.hasVideo,isMuxed:_}),t=null),$()}})},rD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=new Uint8Array(e);if(jP(b)){s.isFmp4=!0;const{tracks:_}=s.map;if(_.text&&(!_.audio||!_.video)){f(s,{data:b,type:"text"}),gF(s,_.text.codec,p);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=(R,$)=>{f(s,{data:b,type:L.hasAudio&&!L.isMuxed?"audio":"video"}),$&&$.length&&a(s,$),R&&R.length&&u(s,R),p(null,s,{})};gc({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:R,startTime:$})=>{e=R.buffer,s.bytes=b=R,L.hasAudio&&!L.isMuxed&&i(s,"audio","start",$),L.hasVideo&&i(s,"video","start",$),gc({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:$,callback:({emsgData:P,id3Frames:B})=>{if(e=P.buffer,s.bytes=b=P,!_.video||!P.byteLength||!s.transmuxer){I(void 0,B);return}gc({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[_.video.id],callback:O=>{e=O.data.buffer,s.bytes=b=O.data,O.logs.forEach(function(H){y(Pi(H,{stream:"mp4CaptionParser"}))}),I(O.captions,B)}})}})}});return}if(!s.transmuxer){p(null,s,{});return}if(typeof s.container>"u"&&(s.container=ub(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),p(null,s,{});return}xF({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})},aD=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},a){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;a(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=Zl({segment:n}),p={message:d,metadata:{error:new Error(d),errorType:De.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(Vk({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},bF=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),aD({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:p},b=>{e.bytes=b,v({type:"segmentdecryptioncomplete",segment:e}),rD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})})},TF=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=0,_=!1;return(E,L)=>{if(!_){if(E)return _=!0,Sx(s),p(E,L);if(b+=1,b===s.length){const I=function(){if(L.encryptedBytes)return bF({decryptionWorker:e,segment:L,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v});rD({segment:L,bytes:L.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})};if(L.endOfAllRequests=Date.now(),L.map&&L.map.encryptedBytes&&!L.map.bytes)return v({type:"segmentdecryptionstart",segment:L}),aD({decryptionWorker:e,id:L.requestId+"-init",encryptedBytes:L.map.encryptedBytes,key:L.map.key,segment:L,doneFn:p},R=>{L.map.bytes=R,v({type:"segmentdecryptioncomplete",segment:L}),nD(L,$=>{if($)return Sx(s),p($,L);I()})});I()}}}},_F=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},SF=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>p=>{if(!p.target.aborted)return s.stats=Pi(s.stats,mF(p)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(p,s)},EF=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:E,triggerSegmentEventFn:L})=>{const I=[],R=TF({activeXhrs:I,decryptionWorker:t,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:E,triggerSegmentEventFn:L});if(i.key&&!i.key.bytes){const H=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&H.push(i.map.key);const D=Pi(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),M=u2(i,H,R,L),W={uri:i.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:W});const K=s(D,M);I.push(K)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const K=Pi(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),J=u2(i,[i.map.key],R,L),ue={uri:i.map.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:ue});const se=s(K,J);I.push(se)}const D=Pi(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:Tx(i.map),requestType:"segment-media-initialization"}),M=yF({segment:i,finishProcessingFn:R,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const W=s(D,M);I.push(W)}const $=Pi(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:Tx(i),requestType:"segment"}),P=vF({segment:i,finishProcessingFn:R,responseType:$.responseType,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const B=s($,P);B.addEventListener("progress",SF({segment:i,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b})),I.push(B);const O={};return I.forEach(H=>{H.addEventListener("loadend",_F({loadendState:O,abortFn:n}))}),()=>Sx(I)},xm=Or("PlaylistSelector"),c2=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||""})},yc=function(s,e){if(!s)return"";const t=fe.getComputedStyle(s);return t?t[e]:""},vc=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})},$b=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||fe.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||fe.Number.MAX_VALUE,t-i},wF=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||fe.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||fe.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let oD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:a,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:a};let d=e.playlists;Xn.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(O=>{let H;const D=O.attributes&&O.attributes.RESOLUTION&&O.attributes.RESOLUTION.width,M=O.attributes&&O.attributes.RESOLUTION&&O.attributes.RESOLUTION.height;return H=O.attributes&&O.attributes.BANDWIDTH,H=H||fe.Number.MAX_VALUE,{bandwidth:H,width:D,height:M,playlist:O}});vc(f,(O,H)=>O.bandwidth-H.bandwidth),f=f.filter(O=>!Xn.isIncompatible(O.playlist));let p=f.filter(O=>Xn.isEnabled(O.playlist));p.length||(p=f.filter(O=>!Xn.isDisabled(O.playlist)));const y=p.filter(O=>O.bandwidth*sn.BANDWIDTH_VARIANCEO.bandwidth===v.bandwidth)[0];if(a===!1){const O=b||p[0]||f[0];if(O&&O.playlist){let H="sortedPlaylistReps";return b&&(H="bandwidthBestRep"),p[0]&&(H="enabledPlaylistReps"),xm(`choosing ${c2(O)} using ${H} with options`,c),O.playlist}return xm("could not choose a playlist with options",c),null}const _=y.filter(O=>O.width&&O.height);vc(_,(O,H)=>O.width-H.width);const E=_.filter(O=>O.width===i&&O.height===n);v=E[E.length-1];const L=E.filter(O=>O.bandwidth===v.bandwidth)[0];let I,R,$;L||(I=_.filter(O=>r==="cover"?O.width>i&&O.height>n:O.width>i||O.height>n),R=I.filter(O=>O.width===I[0].width&&O.height===I[0].height),v=R[R.length-1],$=R.filter(O=>O.bandwidth===v.bandwidth)[0]);let P;if(u.leastPixelDiffSelector){const O=_.map(H=>(H.pixelDiff=Math.abs(H.width-i)+Math.abs(H.height-n),H));vc(O,(H,D)=>H.pixelDiff===D.pixelDiff?D.bandwidth-H.bandwidth:H.pixelDiff-D.pixelDiff),P=O[0]}const B=P||$||L||b||p[0]||f[0];if(B&&B.playlist){let O="sortedPlaylistReps";return P?O="leastPixelDiffRep":$?O="resolutionPlusOneRep":L?O="resolutionBestRep":b?O="bandwidthBestRep":p[0]&&(O="enabledPlaylistReps"),xm(`choosing ${c2(B)} using ${O} with options`,c),B.playlist}return xm("could not choose a playlist with options",c),null};const d2=function(){let s=this.useDevicePixelRatio&&fe.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),oD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(yc(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(yc(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?yc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},AF=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&&fe.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),oD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(yc(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(yc(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?yc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},CF=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:a,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(b=>!Xn.isIncompatible(b));let f=d.filter(Xn.isEnabled);f.length||(f=d.filter(b=>!Xn.isDisabled(b)));const y=f.filter(Xn.hasAttribute.bind(null,"BANDWIDTH")).map(b=>{const E=c.getSyncPoint(b,n,u,t)?1:2,I=Xn.estimateSegmentRequestTime(r,i,b)*E-a;return{playlist:b,rebufferingImpact:I}}),v=y.filter(b=>b.rebufferingImpact<=0);return vc(v,(b,_)=>$b(_.playlist,b.playlist)),v.length?v[0]:(vc(y,(b,_)=>b.rebufferingImpact-_.rebufferingImpact),y[0]||null)},kF=function(){const s=this.playlists.main.playlists.filter(Xn.isEnabled);return vc(s,(t,i)=>$b(t,i)),s.filter(t=>!!xh(this.playlists.main,t).video)[0]||null},DF=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 lD(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const LF=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 a=t,u=t,c=!1;const d=r[i];d&&(a=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:a,language:u},!1).track}}},RF=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=fe.WebKitDataCue||fe.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(a=>{const u=new i(n.startTime+t,n.endTime+t,a.text);u.line=a.line,u.align="left",u.position=a.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},IF=function(s){Object.defineProperties(s.frame,{id:{get(){return De.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return De.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return De.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},NF=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=fe.WebKitDataCue||fe.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const p=f.cueTime+t;typeof p!="number"||fe.isNaN(p)||p<0||!(p<1/0)||!f.frames||!f.frames.length||f.frames.forEach(y=>{const v=new n(p,p,y.value||y.url||y.data||"");v.frame=y,v.value=y,IF(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const a=r.cues,u=[];for(let f=0;f{const y=f[p.startTime]||[];return y.push(p),f[p.startTime]=y,f},{}),d=Object.keys(c).sort((f,p)=>Number(f)-Number(p));d.forEach((f,p)=>{const y=c[f],v=isFinite(i)?i:f,b=Number(d[p+1])||v;y.forEach(_=>{_.endTime=b})})},OF={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"},MF=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),PF=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=fe.WebKitDataCue||fe.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(MF.has(r))continue;const a=new i(n.startTime,n.endTime,"");a.id=n.id,a.type="com.apple.quicktime.HLS",a.value={key:OF[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(a.value.data=new Uint8Array(a.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(a)}n.processDateRange()})},h2=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,De.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},oh=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)},BF=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}},FF=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*eu.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},UF=(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)},jF=(s,e,t,i)=>{const n=Math.ceil((e-i)*eu.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*eu.ONE_SECOND_IN_TS),a=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return a;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),a.splice(c,u-c+1),a},$F=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]},Qd=1,GF=500,f2=s=>typeof s=="number"&&isFinite(s),bm=1/60,VF=(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,zF=(s,e,t)=>{let i=e-sn.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},Wu=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:a,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,p=u.length-1;let y="mediaIndex/partIndex increment";s.getMediaInfoForTime?y=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(y="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(y+=` with independent ${s.independent}`);const v=typeof d=="number",b=s.segment.uri?"segment":"pre-segment",_=v?Ak({preloadSegment:i})-1:0;return`${b} [${r+c}/${r+p}]`+(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 [${y}] playlist [${a}]`},m2=s=>`${s}TimingInfo`,qF=({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},KF=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)},WF=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(Ex({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&KF(s.timelineChangeController_)){if(WF(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},YF=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 a;typeof n=="bigint"||typeof r=="bigint"?a=fe.BigInt(r)-fe.BigInt(n):typeof n=="number"&&typeof r=="number"&&(a=r-n),typeof a<"u"&&a>e&&(e=a)}),typeof e=="bigint"&&es?Math.round(s)>e+ba:!1,XF=(s,e)=>{if(e!=="hls")return null;const t=YF({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=p2({segmentDuration:t,maxDuration:i*2}),r=p2({segmentDuration:t,maxDuration:i}),a=`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:a}:null},Zl=({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 wx extends De.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_=Or(`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_():el(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(Ns({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():el(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(Ns({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():el(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():el(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return iv.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_&&fe.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,fe.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_&&iv.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return rn();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=Tp(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=zk(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: ${ev(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 a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,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-=a,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_&&(fe.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_&&iv.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 a=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,a)),(n||this.loaderType_==="main")&&(this.gopBuffer_=jF(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,a));for(const u in this.inbandTextTracks_)oh(e,t,this.inbandTextTracks_[u]);oh(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&fe.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=fe.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&fe.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=fe.setTimeout(this.monitorBufferTick_.bind(this),GF)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:Zl({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,a=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&a}chooseNextRequest_(){const e=this.buffered_(),t=ev(e)||0,i=Pb(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.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=HF(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const y=a[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=y.end?y.end:t,y.parts&&y.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let y,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:De.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})`),y=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=Xn.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});y=E.segmentIndex,v=E.partIndex,b=E.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,u.mediaIndex=y,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=a[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 y=a[u.mediaIndex-1],v=y.parts&&y.parts.length&&y.parts[y.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=y.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>=a.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:a,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],p=typeof u=="number"&&f.parts[u],y={requestId:"segment-loader-"+Math.random(),uri:p&&p.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:p?u:null,isSyncRequest:a,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},v=typeof c<"u"?c:this.isPendingTimestampOffset_;y.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const b=ev(this.sourceUpdater_.audioBuffered());return typeof b=="number"&&(y.audioAppendStart=b-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(y.gopsToAlignWith=FF(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),y}timestampOffsetForSegment_(e){return qF(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=Xn.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),a=mB(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=a)return;const u=CF({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-a-u.rebufferingImpact;let f=.5;a<=ba&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[a.stream]=r[a.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[a.stream];u.startTime=Math.min(u.startTime,a.startTime+n),u.endTime=Math.max(u.endTime,a.endTime+n),u.captions.push(a)}),Object.keys(r).forEach(a=>{const{startTime:u,endTime:c,captions:d}=r[a],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${a}`),LF(f,this.vhs_.tech_,a),oh(u,c,f[a]),RF({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_()?!Ex({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||Ex({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_()){el(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[m2(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let a;r&&(a=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:a,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=Tp(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(),a=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+tu(r).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+tu(a).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=a.length?a.start(0):0,f=a.length?a.end(a.length-1):0;if(c-u<=Qd&&f-d<=Qd){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${tu(r).join(", ")}, video buffer: ${tu(a).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 y=this.currentTime_()-Qd;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${y}`),this.remove(0,y,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Qd}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=fe.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Qd*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===Bk){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:De.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=DF({bytes:c,segments:u})}const a={segmentInfo:Zl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),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_()){el(this),this.loadQueue_.push(()=>{const t=Ns({},e,{forceTimestampOffset:!0});Ns(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,a=i||n&&r;this.logger_(`Requesting -${lD(e.uri)} -${Wu(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=EF({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:a,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_(`${Wu(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:p})=>{const v={segmentInfo:Zl({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),p&&(v.timingInfo=p),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=zF(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,a={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?a.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(a.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=c}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}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,a=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}a&&e.waitingOnAppends++,u&&e.waitingOnAppends++,a&&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=VF(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:Zl({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=XF(e,this.sourceType_);if(t&&(t.severity==="warn"?De.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 ${Wu(e)}`);return}this.logger_(`Appended ${Wu(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,a=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||a){this.logger_(`bad ${r?"segment":"part"} ${Wu(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())},QF=["video","audio"],Ax=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},ZF=(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(),xc("audio",e),xc("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||Ax(s,e))){if(i.type!==s){if(t=ZF(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,xc(s,e);return}}},cD=(s,e)=>{const t=e[`${s}Buffer`],i=uD(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},ya=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,hr={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(ya(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(a){n.logger_(`Error with code ${a.code} `+(a.code===Bk?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(a)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(ya(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`];ya(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){De.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){De.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(ya(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){De.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=uD(s),n=kc(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(cD(s,e),!!ya(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){De.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=kc(s);if(!ya(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))===r)return;const c={codecsChangeInfo:{from:a,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${a} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=De.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),De.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},fr=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),xc(s,e)},g2=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=dB(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_`])}xc(s,e)};class dD extends De.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>xc("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Or("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=g2("video",this),this.onAudioUpdateEnd_=g2("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){fr({type:"mediaSource",sourceUpdater:this,action:hr.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){fr({type:e,sourceUpdater:this,action:hr.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){De.log.error("removeSourceBuffer is not supported!");return}fr({type:"mediaSource",sourceUpdater:this,action:hr.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!De.browser.IS_FIREFOX&&fe.MediaSource&&fe.MediaSource.prototype&&typeof fe.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return fe.SourceBuffer&&fe.SourceBuffer.prototype&&typeof fe.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){De.log.error("changeType is not supported!");return}fr({type:e,sourceUpdater:this,action:hr.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 a=t;if(fr({type:n,sourceUpdater:this,action:hr.appendBuffer(r,i||{mediaIndex:-1},a),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 ya(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:rn()}videoBuffered(){return ya(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:rn()}buffered(){const e=ya(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=ya(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():fB(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=lo){fr({type:"mediaSource",sourceUpdater:this,action:hr.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=lo){typeof e!="string"&&(e=void 0),fr({type:"mediaSource",sourceUpdater:this,action:hr.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=lo){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}fr({type:"audio",sourceUpdater:this,action:hr.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=lo){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}fr({type:"video",sourceUpdater:this,action:hr.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(Ax("audio",this)||Ax("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(fr({type:"audio",sourceUpdater:this,action:hr.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(fr({type:"video",sourceUpdater:this,action:hr.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&fr({type:"audio",sourceUpdater:this,action:hr.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&fr({type:"video",sourceUpdater:this,action:hr.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),QF.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>cD(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const y2=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),JF=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},v2=new Uint8Array(` - -`.split("").map(s=>s.charCodeAt(0)));class e8 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class t8 extends wx{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 rn();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return rn([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Tp(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=v2.byteLength+e.bytes.byteLength,a=new Uint8Array(r);a.set(e.bytes),a.set(v2,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}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){oh(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===_a.TIMEOUT&&this.handleTimeout_(),e.code===_a.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 a=n.segment;if(a.map&&(a.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof fe.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}a.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:De.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+=a.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new fe.VTTCue(u.startTime,u.endTime,u.text):u)}),BF(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,a=new fe.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];a[d]=isNaN(f)?f:Number(f)}),e.cues.push(a)})}parseVTTCues_(e){let t,i=!1;if(typeof fe.WebVTT!="function")throw new e8;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof fe.TextDecoder=="function"?t=new fe.TextDecoder("utf8"):(t=fe.WebVTT.StringDecoder(),i=!0);const n=new fe.WebVTT.Parser(fe,fe.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=a=>{e.timestampmap=a},n.onparsingerror=a=>{De.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=y2(a)),n.parse(a)}let r=e.bytes;i&&(r=y2(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:a}=e.timestampmap,c=r/eu.ONE_SECOND_IN_TS-a+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*eu.ONE_SECOND_IN_TS;const n=t*eu.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/eu.ONE_SECOND_IN_TS}}const i8=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},s8=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 hD{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=` -`,a=i,u=t;this.start_=a,e.forEach((c,d)=>{const f=this.storage_.get(u),p=a,y=p+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),b=new x2({start:p,end:y,appended:v,segmentIndex:d});c.syncInfo=b;let _=a;const E=(c.parts||[]).map((L,I)=>{const R=_,$=_+L.duration,P=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[I]&&f.partsSyncInfo[I].isAppended),B=new x2({start:R,end:$,appended:P,segmentIndex:d,partIndex:I});return _=$,r+=`Media Sequence: ${u}.${I} | Range: ${R} --> ${$} | Appended: ${P} -`,L.syncInfo=B,B});n.set(u,new n8(b,E)),r+=`${lD(c.resolvedUri)} | Media Sequence: ${u} | Range: ${p} --> ${y} | Appended: ${v} -`,u++,a=y}),this.end_=a,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 a=s.getMediaSequenceSync(r);if(!a||!a.isReliable)return null;const u=a.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,a=null;const u=gx(e);n=n||0;for(let c=0;c{let r=null,a=null;n=n||0;const u=gx(e);for(let c=0;c=v)&&(a=v,r={time:y,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 a=null;for(let u=0;u=p)&&(a=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 a8 extends De.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new hD,i=new b2(t),n=new b2(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=Or("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return sv.find(({name:c})=>c==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,i,n,r);if(!a.length)return null;for(const u of a){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:p}=c;if(f<0)continue;const y=e.segments[f],v=p,b=v+y.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+vh({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const a=[];for(let u=0;ur8){De.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 a=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),u=e.startOfSegment,c=t.end+a.mapping;else if(a)u=t.start+a.mapping,c=t.end+a.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-vh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+vh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[a]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class o8 extends De.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 l8=Qk(Zk(function(){var s=(function(){function _(){this.listeners={}}var E=_.prototype;return E.on=function(I,R){this.listeners[I]||(this.listeners[I]=[]),this.listeners[I].push(R)},E.off=function(I,R){if(!this.listeners[I])return!1;var $=this.listeners[I].indexOf(R);return this.listeners[I]=this.listeners[I].slice(0),this.listeners[I].splice($,1),$>-1},E.trigger=function(I){var R=this.listeners[I];if(R)if(arguments.length===2)for(var $=R.length,P=0;P<$;++P)R[P].call(this,arguments[1]);else for(var B=Array.prototype.slice.call(arguments,1),O=R.length,H=0;H>7)*283)^$]=$;for(P=B=0;!I[P];P^=D||1,B=H[B]||1)for(K=B^B<<1^B<<2^B<<3^B<<4,K=K>>8^K&255^99,I[P]=K,R[K]=P,W=O[M=O[D=O[P]]],ue=W*16843009^M*65537^D*257^P*16843008,J=O[K]*257^K*16843008,$=0;$<4;$++)E[$][P]=J=J<<24^J>>>8,L[$][K]=ue=ue<<24^ue>>>8;for($=0;$<5;$++)E[$]=E[$].slice(0),L[$]=L[$].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,R;const $=this._tables[0][4],P=this._tables[1],B=E.length;let O=1;if(B!==4&&B!==6&&B!==8)throw new Error("Invalid aes key size");const H=E.slice(0),D=[];for(this._key=[H,D],L=B;L<4*B+28;L++)R=H[L-1],(L%B===0||B===8&&L%B===4)&&(R=$[R>>>24]<<24^$[R>>16&255]<<16^$[R>>8&255]<<8^$[R&255],L%B===0&&(R=R<<8^R>>>24^O<<24,O=O<<1^(O>>7)*283)),H[L]=H[L-B]^R;for(I=0;L;I++,L--)R=H[I&3?L:L-4],L<=4||I<4?D[I]=R:D[I]=P[0][$[R>>>24]]^P[1][$[R>>16&255]]^P[2][$[R>>8&255]]^P[3][$[R&255]]}decrypt(E,L,I,R,$,P){const B=this._key[1];let O=E^B[0],H=R^B[1],D=I^B[2],M=L^B[3],W,K,J;const ue=B.length/4-2;let se,q=4;const Y=this._tables[1],ie=Y[0],Q=Y[1],oe=Y[2],F=Y[3],ee=Y[4];for(se=0;se>>24]^Q[H>>16&255]^oe[D>>8&255]^F[M&255]^B[q],K=ie[H>>>24]^Q[D>>16&255]^oe[M>>8&255]^F[O&255]^B[q+1],J=ie[D>>>24]^Q[M>>16&255]^oe[O>>8&255]^F[H&255]^B[q+2],M=ie[M>>>24]^Q[O>>16&255]^oe[H>>8&255]^F[D&255]^B[q+3],q+=4,O=W,H=K,D=J;for(se=0;se<4;se++)$[(3&-se)+P]=ee[O>>>24]<<24^ee[H>>16&255]<<16^ee[D>>8&255]<<8^ee[M&255]^B[q++],W=O,O=H,H=D,D=M,M=W}}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 a=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},u=function(_,E,L){const I=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),R=new n(Array.prototype.slice.call(E)),$=new Uint8Array(_.byteLength),P=new Int32Array($.buffer);let B,O,H,D,M,W,K,J,ue;for(B=L[0],O=L[1],H=L[2],D=L[3],ue=0;ue{const I=_[L];y(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),R=new Uint32Array(E.iv.bytes,E.iv.byteOffset,E.iv.byteLength/4);new c(L,I,R,function($,P){self.postMessage(b({source:E.source,decrypted:P}),[P.buffer])})}}));var u8=Xk(l8);const c8=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},fD=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},Cx=(s,e)=>{e.activePlaylistLoader=s,s.load()},d8=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),a=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(a&&c&&a.id===c.id)&&(n.lastGroup_=a,n.lastTrack_=r,fD(t,n),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),Cx(a.playlistLoader,n)}},h8=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},f8=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,a=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&a&&d.id===a.id)&&(r.lastGroup_=u,r.lastTrack_=a,fD(i,r),!!u)){if(u.isMainPlaylist){if(!a||!d||a.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 ${a.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){Cx(u.playlistLoader,r);return}i.track&&i.track(a),i.resetEverything(),Cx(u.playlistLoader,r)}},_p={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),a=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[a];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}De.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;De.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},T2={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const a=e.media();r.playlist(a,n),(!i.paused()||a.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",_p[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:a}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(a.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",_p[s](s,t))}},m8={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:a},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,p=Vh(f.main);(!a[s]||Object.keys(a[s]).length===0)&&(a[s]={main:{default:{default:!0}}},p&&(a[s].main.default.playlists=f.main.playlists));for(const y in a[s]){u[y]||(u[y]=[]);for(const v in a[s][y]){let b=a[s][y][v],_;if(p?(d(`AUDIO group '${y}' label '${v}' is a main playlist`),b.isMainPlaylist=!0,_=null):i==="vhs-json"&&b.playlists?_=new lc(b.playlists[0],t,r):b.resolvedUri?_=new lc(b.resolvedUri,t,r):b.playlists&&i==="dash"?_=new _x(b.playlists[0],t,r,f):_=null,b=Pi({id:v,playlistLoader:_},b),T2[s](s,b.playlistLoader,e),u[y].push(b),typeof c[v]>"u"){const E=new De.AudioTrack({id:v,kind:c8(b),enabled:!1,language:b.language,default:b.default,label:v});c[v]=E}}}n.on("error",_p[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:a,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const p in u[s]){c[p]||(c[p]=[]);for(const y in u[s][p]){if(!i.options_.useForcedSubtitles&&u[s][p][y].forced)continue;let v=u[s][p][y],b;if(n==="hls")b=new lc(v.resolvedUri,i,a);else if(n==="dash"){if(!v.playlists.filter(E=>E.excludeUntil!==1/0).length)return;b=new _x(v.playlists[0],i,a,f)}else n==="vhs-json"&&(b=new lc(v.playlists?v.playlists[0]:v.resolvedUri,i,a));if(v=Pi({id:y,playlistLoader:b},v),T2[s](s,v.playlistLoader,e),c[p].push(v),typeof d[y]>"u"){const _=t.addRemoteTextTrack({id:y,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:y},!1).track;d[y]=_}}}r.on("error",_p[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const a in i[s]){n[a]||(n[a]=[]);for(const u in i[s][a]){const c=i[s][a][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=Pi(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[a].push(Pi({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}}}}},mD=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let a=null;r.attributes[s]&&(a=n[r.attributes[s]]);const u=Object.keys(n);if(!a)if(s==="AUDIO"&&u.length>1&&Vh(e.main))for(let c=0;c"u"?a:t===null||!a?null:a.filter(c=>c.id===t.id)[0]||null},g8={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}},y8=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},v8=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{m8[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:a}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=p8(d,s),e[d].activeTrack=g8[d](d,s),e[d].onGroupChanged=d8(d,s),e[d].onGroupChanging=h8(d,s),e[d].onTrackChanged=f8(d,s),e[d].getActiveGroup=y8(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?(a.setAudio(!1),r.setAudio(!0)):a.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])},x8=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:lo,activeTrack:lo,getActiveGroup:lo,onGroupChanged:lo,onTrackChanged:lo,lastTrack_:null,logger_:Or(`MediaGroups[${e}]`)}}),s};class _2{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_=Yn(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 b8=class extends De.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new _2,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_=Or("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=Yn(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,a)=>{if(r){if(a.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(a.status===429){const d=a.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:De.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 fe.URL(e),i=new fe.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(fe.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new fe.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_=fe.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){fe.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 _2}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&&(Yn(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const T8=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},_8=10;let tl;const S8=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],E8=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},w8=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:a,bufferBasedABR:u,log:c}){if(!i)return De.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=!!oc(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=Pb(e,t),y=u?sn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:sn.MAX_BUFFER_LOW_WATER_LINE;if(ab)&&p>=n){let _=`${d} as forwardBuffer >= bufferLowWaterLine (${p} >= ${n})`;return u&&(_+=` and next bandwidth > current bandwidth (${v} > ${b})`),c(_),!0}return c(`not ${d} as no switching criteria met`),!1};class A8 extends De.EventTarget{constructor(e){super(),this.fastQualityChange_=T8(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:a,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:p,bufferBasedABR:y,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),tl=a,this.bufferBasedABR=!!y,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_=x8(),_&&fe.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new fe.ManagedMediaSource,this.usingManagedMediaSource_=!0,De.log("Using ManagedMediaSource")):fe.MediaSource&&(this.mediaSource=new fe.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_=rn(),this.hasPlayed_=!1,this.syncController_=new a8(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new u8,this.sourceUpdater_=new dD(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new o8,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:p,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new _x(t,this.vhs_,Pi(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new lc(t,this.vhs_,Pi(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new wx(Pi(L,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new wx(Pi(L,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new t8(Pi(L,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise(($,P)=>{function B(){n.off("vttjserror",O),$()}function O(){n.off("vttjsloaded",B),P()}n.one("vttjsloaded",B),n.one("vttjserror",O),n.addWebVttScript_()})}),e);const I=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new b8(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_())),S8.forEach($=>{this[$+"_"]=E8.bind(this,$)}),this.logger_=Or("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 R=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(R,()=>{const $=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-$,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),a=e&&(e.id||e.uri);if(r&&r!==a){this.logger_(`switch media ${r} -> ${a} from ${t}`);const u={renditionInfo:{id:a,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 a=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);a.length&&this.mediaTypes_[e].activePlaylistLoader.media(a[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=fe.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(fe.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 a=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)a.push.apply(a,c.playlists);else if(c.uri)a.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;yx(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()),v8({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;yx(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(Ns({},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 a in i.AUDIO)for(const u in i.AUDIO[a])i.AUDIO[a][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"}),tl.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(),a=this.tech_.buffered();return w8({buffered:a,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:_8}))});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(Ns({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(Ns({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(Ns({},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=tl.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return n-r<=Ta;const u=a.end(a.length-1);return u-r<=Ta&&n-u<=Ta}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(f0),a=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return De.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){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&&(De.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_:De.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,y=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=p;return this.switchMedia_(c,"exclude",a||y)}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(a=>{const u=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(a=>{const u=this[`${a}SegmentLoader_`];u&&(e===a||e==="all")&&i.push(u)}),i.forEach(a=>t.forEach(u=>{typeof a[u]=="function"&&a[u]()}))}setCurrentTime(e){const t=oc(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:tl.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=tl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return rn([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const a=tl.Playlist.seekable(i,r,tl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),a=t.end(0);return r>n||i>a?e:rn([[Math.max(i,r),Math.min(n,a)]])}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 [${Ek(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=xh(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||m3),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||dE}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||dE,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 a=(d,f)=>d?mh(f,this.usingManagedMediaSource_):By(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!a(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=(ga(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,y=(ga(n[f]||"")[0]||{}).type;p&&y&&p.toLowerCase()!==y.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=xh(this.main,n),a=[];r.audio&&!By(r.audio)&&!mh(r.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${r.audio}`),r.video&&!By(r.video)&&!mh(r.video,this.usingManagedMediaSource_)&&a.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&a.push(`text codec ${r.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=kh(ga(e)),r=n2(n),a=n.video&&ga(n.video)[0]||null,u=n.audio&&ga(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=xh(this.mainPlaylistLoader_.main,d),y=n2(p);if(!(!p.audio&&!p.video)){if(y!==r&&f.push(`codec count "${y}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=p.video&&ga(p.video)[0]||null,b=p.audio&&ga(p.audio)[0]||null;v&&a&&v.type.toLowerCase()!==a.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${a.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)),s8(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=sn.GOAL_BUFFER_LENGTH,i=sn.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,sn.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=sn.BUFFER_LOW_WATER_LINE,i=sn.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,sn.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,sn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return sn.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){h2(this.inbandTextTracks_,"com.apple.streaming",this.tech_),PF({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();h2(this.inbandTextTracks_,e,this.tech_),NF({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(Ns({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),a=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(a.push(c),!r.has(c)))return!0}return!!(!a.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(a=>{const u=i[a],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(a=>{const u=this.mediaTypes_[a];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[a,u]of i.entries())n.get(a)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(a));for(const[a,u]of n.entries()){const c=i.get(a);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(a))}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 a="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===a,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 ${a}`)):(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 ${a}`)),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,De.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:JF(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 C8=(s,e,t)=>i=>{const n=s.main.playlists[e],r=Fb(n),a=f0(n);if(typeof i>"u")return a;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!==a&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class k8{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=xh(n.main(),t),this.playlist=t,this.id=i,this.enabled=C8(e.playlists,t.id,r)}}const D8=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=Vh(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Fb(i)).map((i,n)=>new k8(s,i,i.id)):[]}},S2=["seeking","seeked","pause","playing","error"];class L8 extends De.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_=Or("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),a=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},a[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(p=>{a[`${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(S2,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(S2,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=>{a[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&fe.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&fe.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=fe.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=pB(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const a={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:a}),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:tu(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+Ta>=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(rn([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:Ta)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${Ek(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const a=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=a.audioBuffer?a.audioBuffered():null,d=a.videoBuffer?a.videoBuffered():null,f=this.media(),p=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-ba)*2,y=[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 a=vm(n,t);return a.length>0?(this.logger_(`Stopped at ${t} and seeking to ${a.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)+Ta;const a=!i.endList,u=typeof i.partTargetDuration=="number";return a&&(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:a}}return null}}const R8={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},pD=function(s,e){let t=0,i=0;const n=Pi(R8,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},a=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(Ts,s,{get(){return De.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),sn[s]},set(e){if(De.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){De.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}sn[s]=e}})});const yD="videojs-vhs",vD=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),vD(s,e.playlists)};Ts.canPlaySource=function(){return De.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const F8=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=kh(ga(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=kc(i.video),r=kc(i.audio),a={};for(const u in s)a[u]={},r&&(a[u].audioContentType=r),n&&(a[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(a[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(a[u].url=s[u]);return Pi(s,a)},U8=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,a)=>{const u=i.contentProtection[a];return u&&u.pssh&&(r[a]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),j8=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=U8(n,Object.keys(e)),a=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),a.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},p=>{if(p){f(p);return}d()})}))}),Promise.race([Promise.all(a),Promise.race(u)])},$8=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=F8(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(De.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},xD=()=>{if(!fe.localStorage)return null;const s=fe.localStorage.getItem(yD);if(!s)return null;try{return JSON.parse(s)}catch{return null}},H8=s=>{if(!fe.localStorage)return!1;let e=xD();e=e?Pi(e,s):s;try{fe.localStorage.setItem(yD,JSON.stringify(e))}catch{return!1}return e},G8=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,bD=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},TD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},_D=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},SD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};Ts.supportsNativeHls=(function(){if(!at||!at.createElement)return!1;const s=at.createElement("video");return De.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})();Ts.supportsNativeDash=(function(){return!at||!at.createElement||!De.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(at.createElement("video").canPlayType("application/dash+xml"))})();Ts.supportsTypeNatively=s=>s==="hls"?Ts.supportsNativeHls:s==="dash"?Ts.supportsNativeDash:!1;Ts.isSupported=function(){return De.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Ts.xhr.onRequest=function(s){bD(Ts.xhr,s)};Ts.xhr.onResponse=function(s){TD(Ts.xhr,s)};Ts.xhr.offRequest=function(s){_D(Ts.xhr,s)};Ts.xhr.offResponse=function(s){SD(Ts.xhr,s)};const V8=De.getComponent("Component");class ED extends V8{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Or("VhsHandler"),t.options_&&t.options_.playerId){const n=De.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(at,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=at.fullscreenElement||at.webkitFullscreenElement||at.mozFullScreenElement||at.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_=Pi(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=xD();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=sn.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===sn.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=G8(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Ts,this.options_.sourceType=zA(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new A8(this.options_);const i=Pi({liveRangeSafeTimeDelta:Ta},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new L8(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=De.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),r.error(a)});const n=this.options_.bufferBasedABR?Ts.movingAverageBandwidthSelector(.55):Ts.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Ts.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 a=fe.navigator.connection||fe.navigator.mozConnection||fe.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&a){const c=a.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 a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(r+a))},set(){De.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:()=>tu(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:()=>tu(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&&H8({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{D8(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_=fe.URL.createObjectURL(this.playlistController_.mediaSource),(De.browser.IS_ANY_SAFARI||De.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"),j8({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=$8({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=De.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{B8(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{vD(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":gD,"mux.js":N8,"mpd-parser":O8,"m3u8-parser":M8,"aes-decrypter":P8}}version(){return this.constructor.version()}canChangeType(){return dD.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_&&fe.URL.revokeObjectURL&&(fe.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return WB({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return Wk({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=>{bD(this.xhr,e)},this.xhr.onResponse=e=>{TD(this.xhr,e)},this.xhr.offRequest=e=>{_D(this.xhr,e)},this.xhr.offResponse=e=>{SD(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(Ns({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(Ns({},n))})})}}const Sp={name:"videojs-http-streaming",VERSION:gD,canHandleSource(s,e={}){const t=Pi(De.options,e);return!t.vhs.experimentalUseMMS&&!mh("avc1.4d400d,mp4a.40.2",!1)?!1:Sp.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=Pi(De.options,t);return e.vhs=new ED(s,e,i),e.vhs.xhr=Gk(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=zA(s);if(!t)return"";const i=Sp.getOverrideNative(e);return!Ts.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(De.browser.IS_ANY_SAFARI||De.browser.IS_IOS),{overrideNative:i=t}=e;return i}},z8=()=>mh("avc1.4d400d,mp4a.40.2",!0);z8()&&De.getTech("Html5").registerSourceHandler(Sp,0);De.VhsHandler=ED;De.VhsSourceHandler=Sp;De.Vhs=Ts;De.use||De.registerComponent("Vhs",Ts);De.options.vhs=De.options.vhs||{};(!De.getPlugin||!De.getPlugin("reloadSourceOnError"))&&De.registerPlugin("reloadSourceOnError",I8);const q8="",sc=s=>{const e=s.startsWith("/")?s:`/${s}`;return`${q8}${e}`};async function K8(s,e){const t=await fetch(sc(s),{...e,credentials:"include",headers:{...e?.headers??{},"Content-Type":e?.headers?.["Content-Type"]??"application/json"}});return t.status===401&&(location.pathname.startsWith("/login")||(location.href="/login")),t}const xt=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},W8=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Y8},Y8=Number.MAX_SAFE_INTEGER||9007199254740991;let Pt=(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})({}),Le=(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})({}),G=(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 yi={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},At={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Yu{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 X8{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 Yu(e),this.fast_=new Yu(t),this.defaultTTFB_=n,this.ttfb_=new Yu(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Yu(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Yu(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Yu(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 Q8(s,e,t){return(e=J8(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Qi(){return Qi=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):ol}function w2(s,e,t){return e[s]?e[s].bind(e):t6(s,t)}const Dx=kx();function i6(s,e,t){const i=kx();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=w2(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return kx()}n.forEach(r=>{Dx[r]=w2(r,s)})}else Qi(Dx,i);return i}const Gi=Dx;function gl(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function s6(s){return typeof self<"u"&&s===self.ManagedMediaSource}function wD(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(a=>i.indexOf(a)===-1)}function xr(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,a="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return a}function dn(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(!xt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Is(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,a=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};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 a6 extends CD{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 a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,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 kD(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||kD(t,e)}}function o6(s,e){const t=kD(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const C2=Math.pow(2,32)-1,l6=[].push,DD={video:1,audio:2,id3:3,text:4};function Qs(s){return String.fromCharCode.apply(null,s)}function LD(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function ii(s,e){const t=RD(s,e);return t<0?4294967296+t:t}function k2(s,e){let t=ii(s,e);return t*=Math.pow(2,32),t+=ii(s,e+4),t}function RD(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function u6(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 pi(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=pi(s.subarray(n+8,u),e.slice(1));c.length&&l6.apply(t,c)}n=u}return t}function c6(s){const e=[],t=s[0];let i=8;const n=ii(s,i);i+=4;let r=0,a=0;t===0?(r=ii(s,i),a=ii(s,i+4),i+=8):(r=k2(s,i),a=k2(s,i+8),i+=16),i+=2;let u=s.length+a;const c=LD(s,i);i+=2;for(let d=0;d>>31===1)return Gi.warn("SIDX has hierarchical references (not supported)"),null;const b=ii(s,f);f+=4,e.push({referenceSize:y,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+y-1}}),u+=y,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function ID(s){const e=[],t=pi(s,["moov","trak"]);for(let n=0;n{const r=ii(n,4),a=e[r];a&&(a.default={duration:ii(n,12),flags:ii(n,20)})}),e}function d6(s){const e=s.subarray(8),t=e.subarray(86),i=Qs(e.subarray(4,8));let n=i,r;const a=i==="enca"||i==="encv";if(a){const d=pi(e,[i])[0].subarray(i==="enca"?28:78);pi(d,["sinf"]).forEach(p=>{const y=pi(p,["schm"])[0];if(y){const v=Qs(y.subarray(4,8));if(v==="cbcs"||v==="cenc"){const b=pi(p,["frma"])[0];b&&(n=Qs(b))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=pi(t,["avcC"])[0];c&&c.length>3&&(n+="."+_m(c[1])+_m(c[2])+_m(c[3]),r=Tm(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=pi(e,[i])[0],d=pi(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=av(d,f),f+=2;const p=d[f++];if(p&128&&(f+=2),p&64&&(f+=d[f++]),d[f++]!==4)break;f=av(d,f);const y=d[f++];if(y===64)n+="."+_m(y);else break;if(f+=12,d[f++]!==5)break;f=av(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=pi(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],p=d&31,y=ii(c,2),v=(d&32)>>5?"H":"L",b=c[12],_=c.subarray(6,12);n+="."+f+p,n+="."+h6(y).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=Tm(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Tm(n,t)||n;break}case"vp09":{const c=pi(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],p=c[6]>>4&15;n+="."+ma(d)+"."+ma(f)+"."+ma(p)}break}case"av01":{const c=pi(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,p=c[2]>>>7?"H":"M",y=(c[2]&64)>>6,v=(c[2]&32)>>5,b=d===2&&y?v?12:10:y?10:8,_=(c[2]&16)>>4,E=(c[2]&8)>>3,L=(c[2]&4)>>2,I=c[2]&3;n+="."+d+"."+ma(f)+p+"."+ma(b)+"."+_+"."+E+L+I+"."+ma(1)+"."+ma(1)+"."+ma(1)+"."+0,r=Tm("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function Tm(s,e){const t=pi(e,["dvvC"]),i=t.length?t[0]:pi(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+ma(n)+"."+ma(r)}}function h6(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function av(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(a=>a!==0)||(Gi.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${dn(r)} -> ${dn(t)}`),i.set(t,8))})}function m6(s){const e=[];return ND(s,t=>e.push(t.subarray(8,24))),e}function ND(s,e){pi(s,["moov","trak"]).forEach(i=>{const n=pi(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let a=pi(r,["enca"]);const u=a.length>0;u||(a=pi(r,["encv"])),a.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);pi(d,["sinf"]).forEach(p=>{const y=OD(p);y&&e(y,u)})})})}function OD(s){const e=pi(s,["schm"])[0];if(e){const t=Qs(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=pi(s,["schi","tenc"])[0];if(i)return i}}}function p6(s,e,t){const i={},n=pi(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,a=0;const u=pi(s,["sidx"]);for(let c=0;cp+y.info.duration||0,0);a=Math.max(a,f+d.earliestPresentationTime/d.timescale)}}a&&xt(a)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=a*i[c].timescale-i[c].start)})}return i}function g6(s){const e={valid:null,remainder:null},t=pi(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 Ir(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function D2(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return pi(i,["moof"]).map(c=>{const d=c.byteOffset-8;pi(c,["traf"]).map(p=>{const y=pi(p,["tfdt"]).map(v=>{const b=v[0];let _=ii(v,4);return b===1&&(_*=Math.pow(2,32),_+=ii(v,8)),_/n})[0];return y!==void 0&&(s=y),pi(p,["tfhd"]).map(v=>{const b=ii(v,4),_=ii(v,0)&16777215,E=(_&1)!==0,L=(_&2)!==0,I=(_&8)!==0;let R=0;const $=(_&16)!==0;let P=0;const B=(_&32)!==0;let O=8;b===r&&(E&&(O+=8),L&&(O+=4),I&&(R=ii(v,O),O+=4),$&&(P=ii(v,O),O+=4),B&&(O+=4),e.type==="video"&&(a=m0(e.codec)),pi(p,["trun"]).map(H=>{const D=H[0],M=ii(H,0)&16777215,W=(M&1)!==0;let K=0;const J=(M&4)!==0,ue=(M&256)!==0;let se=0;const q=(M&512)!==0;let Y=0;const ie=(M&1024)!==0,Q=(M&2048)!==0;let oe=0;const F=ii(H,4);let ee=8;W&&(K=ii(H,ee),ee+=4),J&&(ee+=4);let he=K+d;for(let be=0;be>1&63;return t===39||t===40}else return(e&31)===6}function Vb(s,e,t,i){const n=MD(s);let r=0;r+=e;let a=0,u=0,c=0;for(;r=n.length)break;c=n[r++],a+=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){Gi.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(n[f++]===181){const y=LD(n,f);if(f+=2,y===49){const v=ii(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,R=new Uint8Array(I);if(L){R[0]=_;for(let $=1;$16){const p=[];for(let b=0;b<16;b++){const _=n[f++].toString(16);p.push(_.length==1?"0"+_:_),(b===3||b===5||b===7||b===9)&&p.push("-")}const y=u-16,v=new Uint8Array(y);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 a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),x6([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t)}function T6(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 a=s.buffer,u=dn(new Uint8Array(a,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const y=s.getUint32(28);if(!y||i<32+y*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),Bc={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 zb(s,e){const t=Bc[e];return!!t&&!!t[s.slice(0,4)]}function Dh(s,e,t=!0){return!s.split(",").some(i=>!qb(i,e,t))}function qb(s,e,t=!0){var i;const n=gl(t);return(i=n?.isTypeSupported(Lh(s,e)))!=null?i:!1}function Lh(s,e){return`${e}/mp4;codecs=${s}`}function L2(s){if(s){const e=s.substring(0,4);return Bc.video[e]}return 2}function Ep(s){const e=PD();return s.split(",").reduce((t,i)=>{const r=e&&m0(i)?9:Bc.video[i];return r?(r*2+t)/(t?3:2):(Bc.audio[i]+t)/(t?2:1)},0)}const ov={};function S6(s,e=!0){if(ov[s])return ov[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;nS6(t.toLowerCase(),e))}function w6(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)&&(R2(s,"audio")||R2(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 R2(s,e){return zb(s,e)&&qb(s,e)}function A6(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 C6(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 I2(s){const e=gl(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 Lx(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const k6={supported:!0,powerEfficient:!0,smooth:!0},D6={supported:!1,smooth:!1,powerEfficient:!1},BD={supported:!0,configurations:[],decodingInfoResults:[k6]};function FD(s,e){return{supported:!1,configurations:e,decodingInfoResults:[D6],error:s}}function L6(s,e,t,i,n,r){const a=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((y,v)=>{if(v){const b=e.groups[v];if(!b)throw new Error(`Audio track group ${v} not found`);Object.keys(b.channels).forEach(_=>{y[_]=(y[_]||0)+b.channels[_]})}return y},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(y=>m0(y))||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&&xt(f)&&Object.keys(p).some(y=>parseInt(y)>f)}function UD(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(BD);const r=[],a=R6(s),u=a.length,c=I6(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const p={type:"media-source"};if(u&&(p.video=a[f%u]),d){p.audio=c[f%d];const y=p.audio.bitrate;p.video&&y&&(p.video.bitrate-=y)}r.push(p)}if(n){const f=navigator.userAgent;if(n.split(",").some(p=>m0(p))&&PD())return Promise.resolve(FD(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const p=O6(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 R6(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=jD(s),n=s.width||640,r=s.height||480,a=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:Lh(C6(c),"video"),width:n,height:r,bitrate:i,framerate:a};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function I6(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=jD(s);return n&&s.audioGroups?s.audioGroups.reduce((a,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 y=parseFloat(p.channels||"");n.forEach(v=>{const b={contentType:Lh(v,"audio"),bitrate:t?N6(v,r):r};y&&(b.channels=""+y),f.push(b)})}return f},a):a},[]):[]}function N6(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 jD(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function O6(s){let e="";const{audio:t,video:i}=s;if(i){const n=Lx(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=Lx(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const Rx=["NONE","TYPE-0","TYPE-1",null];function M6(s){return Rx.indexOf(s)>-1}const Ap=["SDR","PQ","HLG"];function P6(s){return!!s&&Ap.indexOf(s)>-1}var Gm={No:"",Yes:"YES",v2:"v2"};function N2(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 M2(this._audioGroups,e)}hasSubtitleGroup(e){return M2(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 M2(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function B6(){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||Ap.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&B6(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const U6=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}},is=(s,e)=>JSON.stringify(s,U6(e));function j6(s,e,t,i,n){const r=Object.keys(s),a=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=a&&parseInt(a)===2;let f=!1,p=!1,y=1/0,v=1/0,b=1/0,_=1/0,E=0,L=[];const{preferHDR:I,allowedVideoRanges:R}=F6(e,n);for(let H=r.length;H--;){const D=s[r[H]];f||(f=D.channels[2]>0),y=Math.min(y,D.minHeight),v=Math.min(v,D.minFramerate),b=Math.min(b,D.minBitrate),R.filter(W=>D.videoRanges[W]>0).length>0&&(p=!0)}y=xt(y)?y:0,v=xt(v)?v:0;const $=Math.max(1080,y),P=Math.max(30,v);b=xt(b)?b:t,t=Math.max(b,t),p||(e=void 0);const B=r.length>1;return{codecSet:r.reduce((H,D)=>{const M=s[D];if(D===H)return H;if(L=p?R.filter(W=>M.videoRanges[W]>0):[],B){if(M.minBitrate>t)return da(D,`min bitrate of ${M.minBitrate} > current estimate of ${t}`),H;if(!M.hasDefaultAudio)return da(D,"no renditions with default or auto-select sound found"),H;if(u&&D.indexOf(u.substring(0,4))%5!==0)return da(D,`audio codec preference "${u}" not found`),H;if(a&&!d){if(!M.channels[a])return da(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(M.channels)})`),H}else if((!u||d)&&f&&M.channels[2]===0)return da(D,"no renditions with stereo sound found"),H;if(M.minHeight>$)return da(D,`min resolution of ${M.minHeight} > maximum of ${$}`),H;if(M.minFramerate>P)return da(D,`min framerate of ${M.minFramerate} > maximum of ${P}`),H;if(!L.some(W=>M.videoRanges[W]>0))return da(D,`no variants with VIDEO-RANGE of ${is(L)} found`),H;if(c&&D.indexOf(c.substring(0,4))%5!==0)return da(D,`video codec preference "${c}" not found`),H;if(M.maxScore=Ep(H)||M.fragmentError>s[H].fragmentError)?H:(_=M.minIndex,E=M.maxScore,D)},void 0),videoRanges:L,preferHDR:I,minFramerate:v,minBitrate:b,minIndex:_}}function da(s,e){Gi.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function $D(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 $6(s,e,t,i){return s.slice(t,i+1).reduce((n,r,a)=>{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:a,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,a),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(y=>{c.channels[y]=(c.channels[y]||0)+p.channels[y]}))}),n},{})}function P2(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 Sa(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 Yl(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 V6(s,e,t,i,n){const r=e[i],u=e.reduce((y,v,b)=>{const _=v.uri;return(y[_]||(y[_]=[])).push(b),y},{})[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,y=>{if(y.videoRange!==c||y.frameRate!==d||y.codecSet.substring(0,4)!==f)return!1;const v=y.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Sa(s,b,n)>-1});return p>-1?p:B2(e,i,y=>{const v=y.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Sa(s,b,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:a}=this,{autoLevelEnabled:u,media:c}=a;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,p=r?r.duration:n.duration,y=d-f.loading.start,v=a.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=a.mainForwardBufferInfo;if(!L&&I===null)return;const R=this.bwEstimator.getEstimateTTFB(),$=Math.abs(c.playbackRate);if(y<=Math.max(R,1e3*(p/($*2))))return;const P=I?I.len/$:0,B=f.loading.first?f.loading.first-f.loading.start:-1,O=f.loaded&&B>-1,H=this.getBwEstimate(),D=a.levels,M=D[b],W=Math.max(f.loaded,Math.round(p*(n.bitrate||M.averageBitrate)/8));let K=O?y-B:y;K<1&&O&&(K=Math.min(y,f.loaded*8/H));const J=O?f.loaded*1e3/K:0,ue=R/1e3,se=J?(W-f.loaded)/J:W*8/H+ue;if(se<=P)return;const q=J?J*8:H,Y=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,ie=this.hls.config.abrBandWidthUpFactor;let Q=Number.POSITIVE_INFINITY,oe;for(oe=b-1;oe>v;oe--){const be=D[oe].maxBitrate,pe=!D[oe].details||Y;if(Q=this.getTimeToLoadFrag(ue,q,p*be,pe),Q=se||Q>p*10)return;O?this.bwEstimator.sample(y-Math.min(R,B),f.loaded):this.bwEstimator.sampleTTFB(y);const F=D[oe].maxBitrate;this.getBwEstimate()*ie>F&&this.resetEstimator(F);const ee=this.findBestLevel(F,v,oe,0,P,1,1);ee>-1&&(oe=ee),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: ${P.toFixed(3)} s - Estimated load time for current fragment: ${se.toFixed(3)} s - Estimated load time for down switch fragment: ${Q.toFixed(3)} s - TTFB estimate: ${B|0} ms - Current BW estimate: ${xt(H)?H|0:"Unknown"} bps - New BW estimate: ${this.getBwEstimate()|0} bps - Switching to level ${oe} @ ${F|0} bps`),a.nextLoadLevel=a.nextAutoLevel=oe,this.clearTimer();const he=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===oe&&oe>0){const be=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${oe>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,oe>v){let pe=this.findBestLevel(this.hls.levels[v].bitrate,v,oe,0,be,1,1);pe===-1&&(pe=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=pe,this.resetEstimator(this.hls.levels[pe].bitrate)}}};E||se>Q*2?he():this.timer=self.setInterval(he,Q*1e3),a.trigger(G.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 X8(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(G.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 Le.BUFFER_ADD_CODEC_ERROR:case Le.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Le.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const a=performance.now(),u=r?r.stats:i.stats,c=a-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,a=n?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;xt(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===At.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,a=this.hls.levels[t.level],u=(a.loaded?a.loaded.bytes:0)+n.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:u,duration:c},a.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(G.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 a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==At.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 a=this.hls.firstLevel,u=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} 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 a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[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:a}=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 E=this.findBestLevel(c,a,n,d,0,f,p);if(E>=0)return this.rebufferNotice=-1,E}let y=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const E=this.bitrateTestDelay;E&&(y=(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*y)} ms`),f=p=1)}const v=this.findBestLevel(c,a,n,d,y,f,p);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[a],_=i.loadLevelObj;return _&&b?.bitrate<_.bitrate?a: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,a,u){var c;const d=n+r,f=this.lastLoadedFragLevel,p=f===-1?this.hls.firstLevel:f,{fragCurrent:y,partCurrent:v}=this,{levels:b,allAudioTracks:_,loadLevel:E,config:L}=this.hls;if(b.length===1)return 0;const I=b[p],R=!!((c=this.hls.latestLevelDetails)!=null&&c.live),$=E===-1||f===-1;let P,B="SDR",O=I?.frameRate||0;const{audioPreference:H,videoPreference:D}=L,M=this.audioTracksByGroup||(this.audioTracksByGroup=$D(_));let W=-1;if($){if(this.firstSelection!==-1)return this.firstSelection;const q=this.codecTiers||(this.codecTiers=$6(b,M,t,i)),Y=j6(q,B,e,H,D),{codecSet:ie,videoRanges:Q,minFramerate:oe,minBitrate:F,minIndex:ee,preferHDR:he}=Y;W=ee,P=ie,B=he?Q[Q.length-1]:Q[0],O=oe,e=Math.max(e,F),this.log(`picked start tier ${is(Y)}`)}else P=I?.codecSet,B=I?.videoRange;const K=v?v.duration:y?y.duration:0,J=this.bwEstimator.getEstimateTTFB()/1e3,ue=[];for(let q=i;q>=t;q--){var se;const Y=b[q],ie=q>p;if(!Y)continue;if(L.useMediaCapabilities&&!Y.supportedResult&&!Y.supportedPromise){const pe=navigator.mediaCapabilities;typeof pe?.decodingInfo=="function"&&L6(Y,M,B,O,e,H)?(Y.supportedPromise=UD(Y,M,pe,this.supportedCache),Y.supportedPromise.then(Ce=>{if(!this.hls)return;Y.supportedResult=Ce;const Re=this.hls.levels,Ze=Re.indexOf(Y);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${Ze} ${is(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(Ge=>Ge.smooth===!1||Ge.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ze} not smooth or powerEfficient: ${is(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ze} ${is(Ce)}`),Ze>-1&&Re.length>1&&(this.log(`Removing unsupported level ${Ze}`),this.hls.removeLevel(Ze),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):Y.supportedResult=BD}if((P&&Y.codecSet!==P||B&&Y.videoRange!==B||ie&&O>Y.frameRate||!ie&&O>0&&Ope.smooth===!1))&&(!$||q!==W)){ue.push(q);continue}const Q=Y.details,oe=(v?Q?.partTarget:Q?.averagetargetduration)||K;let F;ie?F=u*e:F=a*e;const ee=K&&n>=K*2&&r===0?Y.averageBitrate:Y.maxBitrate,he=this.getTimeToLoadFrag(J,F,ee*oe,Q===void 0);if(F>=ee&&(q===f||Y.loadError===0&&Y.fragmentError===0)&&(he<=J||!xt(he)||R&&!this.bitrateTestDelay||he${q} adjustedbw(${Math.round(F)})-bitrate=${Math.round(F-ee)} ttfb:${J.toFixed(1)} avgDuration:${oe.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${he.toFixed(1)} firstSelection:${$} codecSet:${Y.codecSet} videoRange:${Y.videoRange} hls.loadLevel:${E}`)),$&&(this.firstSelection=q),q}}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 HD={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 a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function q6(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!xt(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)&&F2(t,i,r)===0||K6(r,s,Math.min(n,i))))return r;const a=HD.search(e,F2.bind(null,t,i));return a&&(a!==s||!r)?a:r}function K6(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 F2(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 W6(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function GD(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 HD.search(i,a=>a.cce?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function kp(s){switch(s.details){case Le.FRAG_LOAD_TIMEOUT:case Le.KEY_LOAD_TIMEOUT:case Le.LEVEL_LOAD_TIMEOUT:case Le.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function VD(s){return s.details.startsWith("key")}function zD(s){return VD(s)&&!!s.frag&&!s.frag.decryptdata}function U2(s,e){const t=kp(e);return s.default[`${t?"timeout":"error"}Retry`]}function Kb(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function j2(s){return Hi(Hi({},s),{errorRetry:null,timeoutRetry:null})}function Dp(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function Ix(s){return s===0&&navigator.onLine===!1}var un={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},pr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class X6 extends Mr{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(G.ERROR,this.onError,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(G.ERROR,this.onError,this),e.off(G.ERROR,this.onErrorOut,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===At.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(a=>n.indexOf(a.groupId)>=0).some(a=>{var u;return(u=a.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 Le.FRAG_LOAD_ERROR:case Le.FRAG_LOAD_TIMEOUT:case Le.KEY_LOAD_ERROR:case Le.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case Le.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=bc();return}case Le.FRAG_GAP:case Le.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=un.SendAlternateToPenaltyBox;return}case Le.LEVEL_EMPTY_ERROR:case Le.LEVEL_PARSING_ERROR:{var a;const c=t.parent===At.MAIN?t.level:n.loadLevel;t.details===Le.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case Le.LEVEL_LOAD_ERROR:case Le.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case Le.AUDIO_TRACK_LOAD_ERROR:case Le.AUDIO_TRACK_LOAD_TIMEOUT:case Le.SUBTITLE_LOAD_ERROR:case Le.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===yi.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===yi.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=un.SendAlternateToPenaltyBox,t.errorAction.flags=pr.MoveAllAlternatesMatchingHost;return}}return;case Le.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:un.SendAlternateToPenaltyBox,flags:pr.MoveAllAlternatesMatchingHDCP};return;case Le.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Le.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Le.KEY_SYSTEM_NO_SESSION:t.errorAction={action:un.SendAlternateToPenaltyBox,flags:pr.MoveAllAlternatesMatchingKey};return;case Le.BUFFER_ADD_CODEC_ERROR:case Le.REMUX_ALLOC_ERROR:case Le.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case Le.INTERNAL_EXCEPTION:case Le.BUFFER_APPENDING_ERROR:case Le.BUFFER_FULL_ERROR:case Le.LEVEL_SWITCH_ERROR:case Le.BUFFER_STALLED_ERROR:case Le.BUFFER_SEEK_OVER_HOLE:case Le.BUFFER_NUDGE_ON_STALL:t.errorAction=bc();return}t.type===Pt.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=bc())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=U2(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Dp(n,r,kp(e),e.response))return{action:un.RetryRequest,flags:pr.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:a}=t.config,u=U2(VD(e)?a:r,e),c=t.levels.reduce((f,p)=>f+p.fragmentError,0);if(n&&(e.details!==Le.FRAG_GAP&&n.fragmentError++,!zD(e)&&Dp(u,c,kp(e),e.response)))return{action:un.RetryRequest,flags:pr.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,a;const d=e.details;n.loadError++,d===Le.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:p,loadLevel:y,minAutoLevel:v,maxAutoLevel:b}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const _=(r=e.frag)==null?void 0:r.type,L=(_===At.AUDIO&&d===Le.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===Le.BUFFER_ADD_CODEC_ERROR||d===Le.BUFFER_APPEND_ERROR))&&p.some(({audioCodec:B})=>n.audioCodec!==B),R=e.sourceBufferName==="video"&&(d===Le.BUFFER_ADD_CODEC_ERROR||d===Le.BUFFER_APPEND_ERROR)&&p.some(({codecSet:B,audioCodec:O})=>n.codecSet!==B&&n.audioCodec===O),{type:$,groupId:P}=(a=e.context)!=null?a:{};for(let B=p.length;B--;){const O=(B+y)%p.length;if(O!==y&&O>=v&&O<=b&&p[O].loadError===0){var u,c;const H=p[O];if(d===Le.FRAG_GAP&&_===At.MAIN&&e.frag){const D=p[O].details;if(D){const M=du(e.frag,D.fragments,e.frag.start);if(M!=null&&M.gap)continue}}else{if($===yi.AUDIO_TRACK&&H.hasAudioGroup(P)||$===yi.SUBTITLE_TRACK&&H.hasSubtitleGroup(P))continue;if(_===At.AUDIO&&(u=n.audioGroups)!=null&&u.some(D=>H.hasAudioGroup(D))||_===At.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(D=>H.hasSubtitleGroup(D))||L&&n.audioCodec===H.audioCodec||R&&n.codecSet===H.codecSet||!L&&n.codecSet!==H.codecSet)continue}f=O;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:un.SendAlternateToPenaltyBox,flags:pr.None,nextAutoLevel:f}}return{action:un.SendAlternateToPenaltyBox,flags:pr.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case un.DoNothing:break;case un.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==Le.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 pr.None:this.switchLevel(e,r);break;case pr.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=Rx[Rx.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case pr.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let y=f;y--;)if(this.variantHasKey(d[y],c)){var a,u;this.log(`Banned key found in level ${y} (${d[y].bitrate}bps) or audio group "${(a=d[y].audioGroups)==null?void 0:a.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${dn(c.keyId||[])}`),d[y].fragmentError++,d[y].loadError++,this.log(`Removing level ${y} with key error (${e.error})`),this.hls.removeLevel(y)}const p=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||a>=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=Xu(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=a||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),Sm(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]=$2(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Xu(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},a=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||a;for(let f=0;f=p&&c<=y){r.time.push({startPTS:Math.max(a,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(ap){const v=Math.max(a,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<=p)break}return r}getPartialFragment(e){let t=null,i,n,r,a=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&Sm(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=f.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Sm(t))}getState(e){const t=Xu(e),i=this.fragments[t];return i?i.buffered?Sm(i)?Zs.PARTIAL:Zs.OK:Zs.APPENDING:Zs.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a=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=Xu(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:a}=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[a];this.detectEvictedFragments(a,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Xu(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(a=>{const u=this.fragments[a];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=Xu(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=$2(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 Sm(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 Xu(s){return`${s.type}_${s.level}_${s.sn}`}function $2(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var yl={cbc:0,ctr:1};class Z6{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 yl.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case yl.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 J6(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class eU{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],a=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],p=c[2],y=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],R=v[I],$=v[R];let P=v[L]*257^L*16843008;n[b]=P<<24|P>>>8,r[b]=P<<16|P>>>16,a[b]=P<<8|P>>>24,u[b]=P,P=$*16843009^R*65537^I*257^b*16843008,d[L]=P<<24|P>>>8,f[L]=P<<16|P>>>16,p[L]=P<<8|P>>>24,y[L]=P,b?(b=I^v[v[v[$^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):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:a,remainderData:u}=this;if(n!==yl.cbc||t.byteLength!==16)return Gi.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=Ir(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 eU),d.expandKey(t);const f=a;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 tU(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Z6(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Gi.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 a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%sU;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Gi.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const H2=Math.pow(2,17);class nU{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 no({type:Pt.NETWORK_ERROR,details:Le.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,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){c(V2(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new a(n),f=G2(e);e.loader=d;const p=j2(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:H2};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 no({type:Pt.NETWORK_ERROR,details:Le.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Hi({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 no({type:Pt.NETWORK_ERROR,details:Le.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:b}))},onTimeout:(b,_,E)=>{this.resetLoader(e,d),c(new no({type:Pt.NETWORK_ERROR,details:Le.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:E,stats:b}))}};t&&(v.onProgress=(b,_,E,L)=>t({frag:e,part:null,payload:E,networkDetails:L})),d.load(f,y,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(V2(e,t));return}const d=this.loader=r?new r(n):new a(n),f=G2(e,t);e.loader=d;const p=j2(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:H2};t.stats=d.stats,d.load(f,y,{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 no({type:Pt.NETWORK_ERROR,details:Le.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Hi({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 no({type:Pt.NETWORK_ERROR,details:Le.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:v}))},onTimeout:(v,b,_)=>{this.resetLoader(e,d),c(new no({type:Pt.NETWORK_ERROR,details:Le.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${y.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),p=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+p}else i.total=Math.max(i.loaded,i.total);const a=i.loading,u=n.loading;a.start?a.first+=u.first-u.start:(a.start=u.start,a.first=u.first),a.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function G2(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(xt(n)&&xt(r)){var a;let u=n,c=r;if(s.sn==="initSegment"&&rU((a=s.decryptdata)==null?void 0:a.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 V2(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Pt.MEDIA_ERROR,details:Le.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new no(i)}function rU(s){return s==="AES-128"||s==="AES-256"}class no extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class qD extends Mr{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 Yb{constructor(e,t,i,n=0,r=-1,a=!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=Em(),this.buffering={audio:Em(),video:Em(),audiovideo:Em()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=a}}function Em(){return{start:0,executeStart:0,executeEnd:0,end:0}}const z2={length:0,start:()=>0,end:()=>0};class ri{static isBuffered(e,t){if(e){const i=ri.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=ri.getBuffered(e);return ri.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 y=r[p-1].end;e[f].start-yy&&(r[p-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let a=0,u,c=t,d=t;for(let f=0;f=p&&t<=y&&(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 K2(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.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 aU(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 oU=/^(\d+)x(\d+)$/,W2=/(.+?)=(".*?"|.*?)(?:,|$)/g;class xs{constructor(e,t){typeof e=="string"&&(e=xs.parseAttrList(e,t)),Qi(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=oU.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(W2.lastIndex=0;(i=W2.exec(e))!==null;){const a=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(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=Nx(t,u);else if(!d&&!c)switch(a){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":Gi.warn(`${e}: attribute ${a} is missing quotes`)}n[a]=u}return n}}const lU="com.apple.hls.interstitial";function uU(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function cU(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class WD{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 a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){Gi.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Qi(new xs({}),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"]);xt(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?(Gi.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(xt(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===lU}get isValid(){return!!this.id&&!this._badValueForSameId&&xt(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 dU=10;class hU{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?xt(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||dU}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 Lp(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function Y2(s,e){return!s&&!e?!0:!s||!e?!1:Lp(s,e)}function Tc(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Xb(s){switch(s){case"AES-128":case"AES-256":return yl.cbc;case"AES-256-CTR":return yl.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Qb(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Ox(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function fU(s){const e=Ox(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function YD(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function XD(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",a=n[1];r?(i.splice(-1,1),t=Qb(a)):t=fU(a)}}return t}const Rp=typeof self<"u"?self:void 0;var bs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},hn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Vm(s){switch(s){case hn.FAIRPLAY:return bs.FAIRPLAY;case hn.PLAYREADY:return bs.PLAYREADY;case hn.WIDEVINE:return bs.WIDEVINE;case hn.CLEARKEY:return bs.CLEARKEY}}function lv(s){switch(s){case bs.FAIRPLAY:return hn.FAIRPLAY;case bs.PLAYREADY:return hn.PLAYREADY;case bs.WIDEVINE:return hn.WIDEVINE;case bs.CLEARKEY:return hn.CLEARKEY}}function lh(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[bs.FAIRPLAY,bs.WIDEVINE,bs.PLAYREADY,bs.CLEARKEY].filter(n=>!!e[n]):[];return!i[bs.WIDEVINE]&&t&&i.push(bs.WIDEVINE),i}const QD=(function(s){return Rp!=null&&(s=Rp.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function mU(s,e,t,i){let n;switch(s){case bs.FAIRPLAY:n=["cenc","sinf"];break;case bs.WIDEVINE:case bs.PLAYREADY:n=["cenc"];break;case bs.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return pU(n,e,t,i)}function pU(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 gU(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function ZD(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),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const u=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(u){const c=Qb(u).subarray(0,16);return YD(c),c}}return null}let Qu={};class fl{static clearKeyUriToKeyIdMap(){Qu={}}static setKeyIdForUri(e,t){Qu[e]=t}static addKeyIdForUri(e){const t=Object.keys(Qu).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Qu[e]=i,i}constructor(e,t,i,n=[1],r=null,a){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&&!Tc(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(AD(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Lp(e.keyFormatVersions,this.keyFormatVersions)&&Y2(e.iv,this.iv)&&Y2(e.keyId,this.keyId)}isSupported(){if(this.method){if(Tc(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case hn.FAIRPLAY:case hn.WIDEVINE:case hn.PLAYREADY:case hn.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(Tc(this.method)){let r=this.iv;return r||(typeof e!="number"&&(Gi.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=vU(e)),new fl(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Qu[this.uri];if(r&&!Lp(this.keyId,r)&&fl.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=XD(this.uri);if(i)switch(this.keyFormat){case hn.WIDEVINE:if(this.pssh=i,!this.keyId){const r=T6(i.buffer);if(r.length){var n;const a=r[0];this.keyId=(n=a.kids)!=null&&n.length?a.kids[0]:null}}this.keyId||(this.keyId=X2(t));break;case hn.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=b6(r,null,i),this.keyId=ZD(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=yU(t),r||(r=X2(t),r||(r=Qu[this.uri])),r&&(this.keyId=r,fl.setKeyIdForUri(this.uri,r))}return this}}function yU(s){const e=s?.[hn.WIDEVINE];return e?e.keyId:null}function X2(s){const e=s?.[hn.PLAYREADY];if(e){const t=XD(e.uri);if(t)return ZD(t)}return null}function vU(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const Q2=/#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,Z2=/#EXT-X-MEDIA:(.*)/g,xU=/^#EXT(?:INF|-X-TARGETDURATION):/m,uv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),bU=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 Ea{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(Z2.lastIndex=0;(n=Z2.exec(e))!==null;){const d=new xs(n[1],i),f=d.TYPE;if(f){const p=u[f],y=r[f]||[];r[f]=y;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?Ea.resolve(d.URI,t):""};if(b&&(I.assocLang=b),_&&(I.channels=_),E&&(I.characteristics=E),L&&(I.instreamId=L),p!=null&&p.length){const R=Ea.findGroup(p,I.groupId)||p[0];iw(I,R,"audioCodec"),iw(I,R,"textCodec")}y.push(I)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){var u;const c={url:t},d=new hU(t),f=d.fragments,p=[];let y=null,v=0,b=0,_=0,E=0,L=0,I=null,R=new rv(n,c),$,P,B,O=-1,H=!1,D=null,M;if(uv.lastIndex=0,d.m3u8=e,d.hasVariableRefs=q2(e),((u=uv.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;($=uv.exec(e))!==null;){H&&(H=!1,R=new rv(n,c),R.playlistOffset=_,R.setStart(_),R.sn=v,R.cc=E,L&&(R.bitrate=L),R.level=i,y&&(R.initSegment=y,y.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime,y.rawProgramDateTime=null),D&&(R.setByteRange(D),D=null)));const ue=$[1];if(ue){R.duration=parseFloat(ue);const se=(" "+$[2]).slice(1);R.title=se||null,R.tagList.push(se?["INF",ue,se]:["INF",ue])}else if($[3]){if(xt(R.duration)){R.playlistOffset=_,R.setStart(_),B&&nw(R,B,d),R.sn=v,R.level=i,R.cc=E,f.push(R);const se=(" "+$[3]).slice(1);R.relurl=Nx(d,se),Mx(R,I,p),I=R,_+=R.duration,v++,b=0,H=!0}}else{if($=$[0].match(bU),!$){Gi.warn("No matches on slow regex match for level playlist!");continue}for(P=1;P<$.length&&$[P]===void 0;P++);const se=(" "+$[P]).slice(1),q=(" "+$[P+1]).slice(1),Y=$[P+2]?(" "+$[P+2]).slice(1):null;switch(se){case"BYTERANGE":I?R.setByteRange(q,I):R.setByteRange(q);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=q,R.tagList.push(["PROGRAM-DATE-TIME",q]),O===-1&&(O=f.length);break;case"PLAYLIST-TYPE":d.type&&eo(d,se,$),d.type=q.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?eo(d,se,$):f.length>0&&rw(d,se,$),v=d.startSN=parseInt(q);break;case"SKIP":{d.skippedSegments&&eo(d,se,$);const ie=new xs(q,d),Q=ie.decimalInteger("SKIPPED-SEGMENTS");if(xt(Q)){d.skippedSegments+=Q;for(let F=Q;F--;)f.push(null);v+=Q}const oe=ie.enumeratedString("RECENTLY-REMOVED-DATERANGES");oe&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(oe.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&eo(d,se,$),d.targetduration=Math.max(parseInt(q),1);break;case"VERSION":d.version!==null&&eo(d,se,$),d.version=parseInt(q);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||eo(d,se,$),d.live=!1;break;case"#":(q||Y)&&R.tagList.push(Y?[q,Y]:[q]);break;case"DISCONTINUITY":E++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([se]);break;case"BITRATE":R.tagList.push([se,q]),L=parseInt(q)*1e3,xt(L)?R.bitrate=L:L=0;break;case"DATERANGE":{const ie=new xs(q,d),Q=new WD(ie,d.dateRanges[ie.ID],d.dateRangeTagCount);d.dateRangeTagCount++,Q.isValid||d.skippedSegments?d.dateRanges[Q.id]=Q:Gi.warn(`Ignoring invalid DATERANGE tag: "${q}"`),R.tagList.push(["EXT-X-DATERANGE",q]);break}case"DEFINE":{{const ie=new xs(q,d);"IMPORT"in ie?aU(d,ie,a):K2(d,ie,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?eo(d,se,$):f.length>0&&rw(d,se,$),d.startCC=E=parseInt(q);break;case"KEY":{const ie=J2(q,t,d);if(ie.isSupported()){if(ie.method==="NONE"){B=void 0;break}B||(B={});const Q=B[ie.keyFormat];Q!=null&&Q.matches(ie)||(Q&&(B=Qi({},B)),B[ie.keyFormat]=ie)}else Gi.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${q}"`);break}case"START":d.startTimeOffset=ew(q);break;case"MAP":{const ie=new xs(q,d);if(R.duration){const Q=new rv(n,c);sw(Q,ie,i,B),y=Q,R.initSegment=y,y.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime)}else{const Q=R.byteRangeEndOffset;if(Q){const oe=R.byteRangeStartOffset;D=`${Q-oe}@${oe}`}else D=null;sw(R,ie,i,B),y=R,H=!0}y.cc=E;break}case"SERVER-CONTROL":{M&&eo(d,se,$),M=new xs(q),d.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),d.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&eo(d,se,$);const ie=new xs(q);d.partTarget=ie.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ie=d.partList;ie||(ie=d.partList=[]);const Q=b>0?ie[ie.length-1]:void 0,oe=b++,F=new xs(q,d),ee=new a6(F,R,c,oe,Q);ie.push(ee),R.duration+=ee.duration;break}case"PRELOAD-HINT":{const ie=new xs(q,d);d.preloadHint=ie;break}case"RENDITION-REPORT":{const ie=new xs(q,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ie);break}default:Gi.warn(`line parsed but not handled: ${$}`);break}}}I&&!I.relurl?(f.pop(),_-=I.duration,d.partList&&(d.fragmentHint=I)):d.partList&&(Mx(R,I,p),R.cc=E,d.fragmentHint=R,B&&nw(R,B,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const W=f.length,K=f[0],J=f[W-1];if(_+=d.skippedSegments*d.targetduration,_>0&&W&&J){d.averagetargetduration=_/W;const ue=J.sn;d.endSN=ue!=="initSegment"?ue:0,d.live||(J.endList=!0),O>0&&(_U(f,O),K&&p.unshift(K))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,p.length&&d.dateRangeTagCount&&K&&JD(p,d),d.endCC=E,d}}function JD(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 a;if(((a=s[f])==null?void 0:a.sn)=u||i===0){var a;const c=(((a=t[i+1])==null?void 0:a.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 y=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=y;v>d;v--){const b=f[v].programDateTime;if(e>=b&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>zb(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 iw(s,e,t){const i=e[t];i&&(s[t]=i)}function _U(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 Mx(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function sw(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 nw(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 eo(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function rw(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function cv(s,e){const t=e.startPTS;if(xt(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 eL(s,e,t,i,n,r,a){i-t<=0&&(a.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(xt(f)){const L=Math.abs(f-t);s&&L>s.totalduration?a.warn(`media timestamps and playlist times differ by ${L}s for level ${e.level} ${s.url}`):xt(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,p),i=Math.max(i,p),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const y=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--)cv(E[b],E[b-1]);for(b=_;b=0;f--){const p=n[f].initSegment;if(p){i=p;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;AU(s,e,(f,p,y,v)=>{if((!e.startCC||e.skippedSegments)&&p.cc!==f.cc){const b=f.cc-p.cc;for(let _=y;_{var p;f&&(!f.initSegment||f.initSegment.relurl===((p=i)==null?void 0:p.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=EU(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?eL(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):tL(s,e),a.length&&(e.totalduration=e.edge-a[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 EU(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=Qi({},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 WD(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${is(i[c].attr)}"`)}),r):i}function wU(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],u=e[n+i];a&&u&&a.index===u.index&&a.fragment.sn===u.fragment.sn?t(a,u):i--}}}function AU(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,a=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[a+d];let p=u[d];if(i&&!p&&f&&(p=e.fragments[d]=f),f&&p){t(f,p,d,u);const y=f.relurl,v=p.relurl;if(y&&CU(y,v)){e.playlistParsingError=aw(`media sequence mismatch ${p.sn}:`,s,e,f,p);return}else if(f.cc!==p.cc){e.playlistParsingError=aw(`discontinuity sequence mismatch (${f.cc}!=${p.cc})`,s,e,f,p);return}}}}function aw(s,e,t,i,n){return new Error(`${s} ${n.url} -Playlist starting @${e.startSN} -${e.m3u8} - -Playlist starting @${t.startSN} -${t.m3u8}`)}function tL(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let a=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 CU(s,e){return s!==e&&e?lw(s)!==lw(e):!1}function lw(s){return s.replace(/\?[^?]*$/,"")}function bh(s,e){for(let i=0,n=s.length;is.startCC)}function uw(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function aL(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:a,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,p=c?c.currentTime:0,y=ri.bufferInfo(d||c,p,a.maxBufferHole),v=!y.len;if(this.log(`Media seeking to ${xt(p)?p.toFixed(3):p}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===Ve.ENDED)this.resetLoadingState();else if(u){const b=a.maxFragLookUpTolerance,_=u.start-b,E=u.start+u.duration+b;if(v||Ey.end){const L=p>E;(p<_||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(p,1/0,this.playlistType,!0);const b=this.lastCurrentTime;if(p>b&&(this.lastCurrentTime=p),!this.loadingParts){const _=Math.max(y.end,p),E=this.shouldLoadParts(this.getLevelDetails(),_);E&&(this.log(`LL-Part loading ON after seeking to ${p.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=E)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${p} for seek without enough to start`),this.nextLoadPosition=p,v&&(this.startPosition=p)),v&&this.state===Ve.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 nU(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Wb(e.config)}registerListeners(){const{hls:e}=this;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Ve.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=Ve.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=ri.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>n&&a{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state,u=r.frag;if(this.fragContextChanged(u)){(a===Ve.FRAG_LOADING||!this.fragCurrent&&a===Ve.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=Ve.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(G.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===Ve.STOPPED||this.state===Ve.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Zs.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,a?a.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)===Zs.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(G.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:a}=i,u=r.decryptdata;if(a&&a.byteLength>0&&u!=null&&u.key&&u.iv&&Tc(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),u.key.buffer,u.iv.buffer,Xb(u.method)).catch(d=>{throw n.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(G.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===Ve.STOPPED||this.state===Ve.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!==Ve.STOPPED&&(this.state=Ve.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 a=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(u.message),!a||a.mediaKeys?!1:(this.hls.trigger(G.ERROR,{type:Pt.KEY_SYSTEM_ERROR,details:Le.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?LU.toString(ri.getBuffered(i)):"(detached)"})`),Is(e)){var n;if(e.type!==At.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(u=>!!a[u])){this.state=Ve.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=Ve.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),u=new Yb(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Ve.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(y=>{if(!this.fragContextChanged(y.frag))return this.hls.trigger(G.KEY_LOADED,y),this.state===Ve.KEY_LOADING&&(this.state=Ve.IDLE),y}),this.hls.trigger(G.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,a.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Is(e)&&(!c||e.sn!==c.sn)){const y=this.shouldLoadParts(t.details,e.end);y!==this.loadingParts&&(this.log(`LL-Part loading ${y?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=y)}if(i=Math.max(e.start,i||0),this.loadingParts&&Is(e)){const y=a.partList;if(y&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const v=this.getNextPart(y,e,i);if(v>-1){const b=y[v];e=this.fragCurrent=b.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${b.index} (${v}/${y.length-1}) of ${this.fragInfo(e,!1,b)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=b.start+b.duration,this.state=Ve.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(G.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(y,i))return Promise.resolve(null)}}if(Is(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=a.partList)==null?void 0:d.filter(y=>y.loaded).map(y=>`[${y.start}-${y.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} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),xt(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ve.FRAG_LOADING;const f=this.config.progressive&&e.type!==At.SUBTITLE;let p;return f&&u?p=u.then(y=>!y||this.fragContextChanged(y.frag)?null:this.fragmentLoader.load(e,n)).catch(y=>this.handleFragLoadError(y)):p=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([y])=>(!f&&n&&n(y),y)).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(G.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,a)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=p=>{this.fragmentLoader.loadPart(e,p,n).then(y=>{c[p.index]=y;const v=y.part;this.hls.trigger(G.FRAG_LOADED,y);const b=ow(i.details,e.sn,p.index+1)||nL(d,e.sn,p.index+1);if(b)f(b);else return r({frag:e,part:v,partsLoaded:c})}).catch(a)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Le.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Pt.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(G.ERROR,t)}else this.hls.trigger(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Ve.PARSING){!this.fragCurrent&&this.state!==Ve.STOPPED&&this.state!==Ve.ERROR&&(this.state=Ve.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a);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===At.SUBTITLE)return!1;const a=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){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:a}=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=a>-1?ow(c,r,a):null,f=d?d.fragment:sL(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!==Ve.PARSING)return;const{data1:a,data2:u}=e;let c=a;if(u&&(c=Ir(a,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(G.BUFFER_APPENDING,p),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ri.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=ri.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-u>a&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!xt(n))return null;const a=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,a)}getFwdBufferInfoAtPos(e,t,i,n){const r=ri.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const u=Math.max(Math.min(r.nextStart,a.end)-t,n);return ri.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=At.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,a=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const p=r.initialLiveManifestSize;if(n=a?y:v)||c.start:e;this.log(`Setting startPosition to ${b} to match start frag at live edge. mainStart: ${y} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=b}}else e<=a&&(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===Zs.OK||i===Zs.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.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=a.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,a}get primaryPrefetch(){if(cw(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(cw(this.config)&&e.type!==At.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const a=n.event;if(a){if(a.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 a=r.length;a--;){const u=r[a].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,a=!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=q6(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=GD(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:a,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&&(a=a.concat(c),u=c.sn);let y;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;y=du(r,a,e,_)}else y=a[a.length-1];if(y){const b=y.sn-i.startSN,_=this.fragmentTracker.getState(y);if((_===Zs.OK||_===Zs.PARTIAL&&y.gap)&&(r=y),r&&y.sn===r.sn&&(!p||f[0].fragment.sn>y.sn||!i.live)&&y.level===r.level){const L=a[b+1];y.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&&Is(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!==Ve.FRAG_LOADING_WAITING_RETRY)&&(this.state=Ve.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 a=t.details===Le.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=Ve.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:p}=u,y=!!p,v=y&&c===un.RetryRequest,b=y&&!u.resolved&&d===pr.MoveAllAlternatesMatchingHost,_=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&b&&Is(n)&&!n.endList&&_&&!zD(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||b)&&f=t||i&&!Ix(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ve.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Ve.PARSING||this.state===Ve.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 a=!r;return a&&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(),a}return!1}resetFragmentErrors(e){e===At.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ve.STOPPED&&(this.state=Ve.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=ri.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Ve.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ve.STOPPED&&(this.state=Ve.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 y=n?0:eL(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(G.LEVEL_PTS_UPDATED,{details:r,level:i,drift:y,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(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.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=Ve.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(G.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===At.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 cw(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class lL{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=RU(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function RU(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],a=r>>2&15;if(a>12){const v=new Error(`invalid ADTS sampling index:${a}`);s.emit(G.ERROR,G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.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[a];let p=a;(u===5||u===29)&&(p-=3);const y=[u<<3|(p&14)>>1,(p&1)<<7|c<<3];return Gi.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${a})`),{config:y,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function cL(s,e){return s[e]===255&&(s[e+1]&246)===240}function dL(s,e){return s[e+1]&1?7:9}function tT(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function UU(s,e){return e+5=s.length)return!1;const i=tT(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Np(s,n)}return!1}function hL(s,e,t,i,n){if(!s.samplerate){const r=FU(e,t,i,n);if(!r)return;Qi(s,r)}}function fL(s){return 1024*9e4/s}function HU(s,e){const t=dL(s,e);if(e+t<=s.length){const i=tT(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function mL(s,e,t,i,n){const r=fL(s.samplerate),a=i+n*r,u=HU(e,t);let c;if(u){const{frameLength:p,headerLength:y}=u,v=y+p,b=Math.max(0,t+v-e.length);b?(c=new Uint8Array(v-y),c.set(e.subarray(t+y,e.length),0)):c=e.subarray(t+y,t+v);const _={unit:c,pts:a};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:a},length:d,missing:-1}}function GU(s,e){return eT(s,e)&&p0(s,e+6)+10<=s.length-e}function VU(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function hv(s,e=0,t=1/0){return zU(s,e,t,Uint8Array)}function zU(s,e,t,i){const n=qU(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=KU(s)?s.byteOffset:0,u=(a+s.byteLength)/r,c=(a+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 qU(s){return s instanceof ArrayBuffer?s:s.buffer}function KU(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function WU(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=xr(hv(s.data,1,i)),r=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;const u=xr(hv(s.data,3+i,a));let c;return n==="-->"?c=xr(hv(s.data,4+i+a)):c=VU(s.data.subarray(4+i+a)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function YU(s){if(s.size<2)return;const e=xr(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function XU(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=xr(s.data.subarray(t),!0);t+=i.length+1;const n=xr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=xr(s.data.subarray(1));return{key:s.type,info:"",data:e}}function QU(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=xr(s.data.subarray(t),!0);t+=i.length+1;const n=xr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=xr(s.data);return{key:s.type,info:"",data:e}}function ZU(s){return s.type==="PRIV"?YU(s):s.type[0]==="W"?QU(s):s.type==="APIC"?WU(s):XU(s)}function JU(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=p0(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const wm=10,ej=10;function pL(s){let e=0;const t=[];for(;eT(s,e);){const i=p0(s,e+6);s[e+5]>>6&1&&(e+=wm),e+=wm;const n=e+i;for(;e+ej0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:yr.audioId3,duration:Number.POSITIVE_INFINITY});n{if(xt(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Am=null;const sj=[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],nj=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rj=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],aj=[0,1,1,4];function yL(s,e,t,i,n){if(t+24>e.length)return;const r=vL(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*a,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 vL(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 a=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=sj[c*14+n-1]*1e3,p=nj[(t===3?0:t===2?1:2)*3+r],y=u===3?1:2,v=rj[t][i],b=aj[i],_=v*8*b,E=Math.floor(v*d/p+a)*b;if(Am===null){const R=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Am=R?parseInt(R[1]):0}return Am&&Am<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:p,channelCount:y,frameLength:E,samplesPerFrame:_}}}function nT(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function xL(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[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 y=0;p===2?y+=2:(p&1&&p!==1&&(y+=2),p&4&&(y+=2));const v=(e[t+6]<<8|e[t+7])>>12-y&1,_=[2,1,2,3,3,4,4,5][p]+v,E=e[t+5]>>3,L=e[t+5]&7,I=new Uint8Array([r<<6|E<<1|L>>2,(L&3)<<6|p<<3|v<<2|c>>4,c<<4&224]),R=1536/u*9e4,$=i+n*R,P=e.subarray(t,t+f);return s.config=I,s.channelCount=_,s.samplerate=u,s.samples.push({unit:P,pts:$}),f}class cj extends sT{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=Nh(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&iT(t)!==void 0&&TL(e,i)<=16)return!1;for(let n=e.length;i{const a=v6(r);if(dj.test(a.schemeIdUri)){const u=hw(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:yr.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=hw(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:u,pts:u,type:yr.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 hw(s,e){return xt(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class fj{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Wb(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,yl.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),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).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(a,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 a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}class SL{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 a=r,u=[];let c=0,d,f,p,y=-1,v=0;for(r===-1&&(y=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const b={data:t.subarray(y,f),type:v};u.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(a&&c<=4-a&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-a)),f>0&&(b.data=Ir(b.data,t.subarray(0,f)),b.state=0))}c=0&&r>=0){const b={data:t.subarray(y,n),type:v,state:r};u.push(b)}if(u.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=Ir(b.data,t))}return e.naluState=r,u}}class Th{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&&Gi.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 mj extends SL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,u,c=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=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 E=d.data;if(c&&E.length>4){const L=this.readSliceType(E);(L===2||L===4||L===7||L===9)&&(_=!0)}if(_){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=_;break}case 5:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{u=!0,Vb(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 R=0;R<3;R++){let $=L[R].toString(16);$.length<2&&($="0"+$),I+=$}e.codec=I}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(p=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Th(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let a=0;a{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:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:u=!0,Vb(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Qi(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),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.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,(p=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,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 Th(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 Th(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(),a=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),b=t.readUByte(),_=t.readUByte(),E=t.readUByte(),L=t.readUByte(),I=[],R=[];for(let je=0;je0)for(let je=i;je<8;je++)t.readBits(2);for(let je=0;je1&&t.readEG();for(let ut=0;ut0&&ge<16?(ee=Je[ge-1],he=Ye[ge-1]):ge===255&&(ee=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(),Re=t.readBoolean(),Re&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(pe=t.readBits(32),Ce=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Ye=t.readBoolean(),Qe=t.readBoolean();let mt=!1;(Ye||Qe)&&(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 ct=0;ct<=i;ct++){be=t.readBoolean();const et=be||t.readBoolean();let Gt=!1;et?t.readEG():Gt=t.readBoolean();const Jt=Gt?1:t.readUEG()+1;if(Ye)for(let It=0;It>je&1)<<31-je)>>>0;let ft=nt.toString(16);return a===1&&ft==="2"&&(ft="6"),{codecString:`hvc1.${dt}${a}.${ft}.${r?"H":"L"}${L}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[p,y,v,b,_,E],general_level_idc:L,bit_depth:K+8,bit_depth_luma_minus8:K,bit_depth_chroma_minus8:J,min_spatial_segmentation_idc:F,chroma_format_idc:$,frame_rate:{fixed:be,fps:Ce/pe}},width:Ge,height:it,pixelRatio:[ee,he]}}readPPS(e){const t=new Th(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 a=1;return r&&n?a=0:r?a=3:n&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const tn=188;class ll{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=ll.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(tn*5,t-tn)+1,n=0;for(;n1&&(a===0&&u>2||c+tn>i))return a}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=ll.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=ll.createTrack("audio",n),this._id3Track=ll.createTrack("id3"),this._txtTrack=ll.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 a=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=a.pid,p=a.pesData,y=u.pid,v=c.pid,b=u.pesData,_=c.pesData,E=null,L=this.pmtParsed,I=this._pmtId,R=e.length;if(this.remainderData&&(e=Ir(this.remainderData,e),R=e.length,this.remainderData=null),R>4;let W;if(M>1){if(W=O+5+e[O+4],W===O+tn)continue}else W=O+4;switch(D){case f:H&&(p&&(r=Zu(p,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,r,!1)),p={data:[],size:0}),p&&(p.data.push(e.subarray(W,O+tn)),p.size+=O+tn-W);break;case y:if(H){if(b&&(r=Zu(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(W,O+tn)),b.size+=O+tn-W);break;case v:H&&(_&&(r=Zu(_,this.logger))&&this.parseID3PES(c,r),_={data:[],size:0}),_&&(_.data.push(e.subarray(W,O+tn)),_.size+=O+tn-W);break;case 0:H&&(W+=e[W]+1),I=this._pmtId=gj(e,W);break;case I:{H&&(W+=e[W]+1);const K=yj(e,W,this.typeSupported,i,this.observer,this.logger);f=K.videoPid,f>0&&(a.pid=f,a.segmentCodec=K.segmentVideoCodec),y=K.audioPid,y>0&&(u.pid=y,u.segmentCodec=K.segmentAudioCodec),v=K.id3Pid,v>0&&(c.pid=v),E!==null&&!L&&(this.logger.warn(`MPEG-TS PMT found at ${O} after unknown PID '${E}'. Backtracking to sync byte @${$} to parse all TS packets.`),E=null,O=$-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=D;break}}else P++;P>0&&Fx(this.observer,new Error(`Found ${P} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=p,u.pesData=b,c.pesData=_;const B={audioTrack:u,videoTrack:a,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(B),B}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,a=i.pesData,u=t.pesData,c=n.pesData;let d;if(a&&(d=Zu(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=a,u&&(d=Zu(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=Zu(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 fj(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new mj:e==="hevc"&&(this.videoParser=new pj))}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,y=n.sample.unit.byteLength;if(p===-1)r=Ir(n.sample.unit,r);else{const v=y-p;n.sample.unit.set(r.subarray(0,p),v),e.samples.push(n.sample),i=n.missing}}let a,u;for(a=i,u=r.length;a0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Qi({},t,{type:this._videoTrack?yr.emsg:yr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bx(s,e){return((s[e+1]&31)<<8)+s[e+2]}function gj(s,e){return(s[e+10]&31)<<8|s[e+11]}function yj(s,e,t,i,n,r){const a={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 y=e+5,v=p;for(;v>2;){s[y]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=f,a.segmentAudioCodec="ac3"));const _=s[y+1]+2;y+=_,v-=_}}break;case 194:case 135:return Fx(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=f,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=p+5}return a}function Fx(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(G.ERROR,G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function fv(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Zu(s,e){let t=0,i,n,r,a,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Ir(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&&(a=(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,a-u>60*9e4&&(e.warn(`${Math.round((a-u)/9e4)}s delta between PTS and DTS, align them`),a=u)):u=a),r=i[8];let p=r+9;if(s.size<=p)return null;s.size-=p;const y=new Uint8Array(s.size);for(let v=0,b=c.length;v_){p-=_;continue}else i=i.subarray(p),_-=p,p=0;y.set(i,t),t+=_}return n&&(n-=r+3),{data:y,pts:a,dts:u,len:n}}return null}class vj{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 il=Math.pow(2,32)-1;class ke{static init(){ke.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 ke.types)ke.types.hasOwnProperty(e)&&(ke.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]);ke.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]);ke.STTS=ke.STSC=ke.STCO=r,ke.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ke.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ke.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ke.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);ke.FTYP=ke.box(ke.types.ftyp,a,c,a,u),ke.DINF=ke.box(ke.types.dinf,ke.box(ke.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.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 ke.box(ke.types.mdia,ke.mdhd(e.timescale||0,e.duration||0),ke.hdlr(e.type),ke.minf(e))}static mfhd(e){return ke.box(ke.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"?ke.box(ke.types.minf,ke.box(ke.types.smhd,ke.SMHD),ke.DINF,ke.stbl(e)):ke.box(ke.types.minf,ke.box(ke.types.vmhd,ke.VMHD),ke.DINF,ke.stbl(e))}static moof(e,t,i){return ke.box(ke.types.moof,ke.mfhd(e),ke.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=ke.trak(e[t]);return ke.box.apply(null,[ke.types.moov,ke.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(ke.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=ke.trex(e[t]);return ke.box.apply(null,[ke.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(il+1)),n=Math.floor(t%(il+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 ke.box(ke.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(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const u=ke.box(ke.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 ke.box(ke.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,ke.box(ke.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ke.box(ke.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 ke.box(ke.types.mp4a,ke.audioStsd(e),ke.box(ke.types.esds,ke.esds(e)))}static mp3(e){return ke.box(ke.types[".mp3"],ke.audioStsd(e))}static ac3(e){return ke.box(ke.types["ac-3"],ke.audioStsd(e),ke.box(ke.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return ke.box(ke.types.stsd,ke.STSD,ke.mp4a(e));if(t==="ac3"&&e.config)return ke.box(ke.types.stsd,ke.STSD,ke.ac3(e));if(t==="mp3"&&e.codec==="mp3")return ke.box(ke.types.stsd,ke.STSD,ke.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return ke.box(ke.types.stsd,ke.STSD,ke.avc1(e));if(t==="hevc"&&e.vps)return ke.box(ke.types.stsd,ke.STSD,ke.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,a=Math.floor(i/(il+1)),u=Math.floor(i%(il+1));return ke.box(ke.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,a>>24,a>>16&255,a>>8&255,a&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=ke.sdtp(e),n=e.id,r=Math.floor(t/(il+1)),a=Math.floor(t%(il+1));return ke.box(ke.types.traf,ke.box(ke.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),ke.box(ke.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),ke.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,ke.box(ke.types.trak,ke.tkhd(e),ke.mdia(e))}static trex(e){const t=e.id;return ke.box(ke.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,a=new Uint8Array(r);let u,c,d,f,p,y;for(t+=8+r,a.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,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*u);return ke.box(ke.types.trun,a)}static initSegment(e){ke.types||ke.init();const t=ke.moov(e);return Ir(ke.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 a=r.length;for(let b=0;b>8,i[b][_].length&255]),a),a+=2,u.set(i[b][_],a),a+=i[b][_].length}const d=ke.box(ke.types.hvcC,u),f=e.width,p=e.height,y=e.pixelRatio[0],v=e.pixelRatio[1];return ke.box(ke.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,ke.box(ke.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ke.box(ke.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,v>>24,v>>16&255,v>>8&255,v&255])))}}ke.types=void 0;ke.HDLR_TYPES=void 0;ke.STTS=void 0;ke.STSC=void 0;ke.STCO=void 0;ke.STSZ=void 0;ke.VMHD=void 0;ke.SMHD=void 0;ke.STSD=void 0;ke.FTYP=void 0;ke.DINF=void 0;const EL=9e4;function rT(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function xj(s,e,t=1,i=!1){return rT(s,e,1/t,i)}function Zd(s,e=!1){return rT(s,1e3,1/EL,e)}function bj(s,e=1){return rT(s,EL,1/e)}function fw(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const Tj=10*1e3,_j=1024,Sj=1152,Ej=1536;let Ju=null,mv=null;function mw(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 zm extends Mr{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,Ju===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ju=a?parseInt(a[1]):0}if(mv===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);mv=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&&fw(t)} > ${e&&fw(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,a)=>{let u=a.pts,c=u-r;return c<-4294967296&&(t=!0,u=gr(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,a,u,c){let d,f,p,y,v,b,_=r,E=r;const L=e.pid>-1,I=t.pid>-1,R=t.samples.length,$=e.samples.length>0,P=u&&R>0||R>1;if((!L||$)&&(!I||P)||this.ISGenerated||u){if(this.ISGenerated){var O,H,D,M;const ue=this.videoTrackConfig;(ue&&(t.width!==ue.width||t.height!==ue.height||((O=t.pixelRatio)==null?void 0:O[0])!==((H=ue.pixelRatio)==null?void 0:H[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((M=ue.pixelRatio)==null?void 0:M[1]))||!ue&&P||this.nextAudioTs===null&&$)&&this.resetInitSegment()}this.ISGenerated||(p=this.generateIS(e,t,r,a));const W=this.isVideoContiguous;let K=-1,J;if(P&&(K=wj(t.samples),!W&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,K>0){this.warn(`Dropped ${K} out of ${R} video samples due to a missing keyframe`);const ue=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(K),t.dropped+=K,E+=(t.samples[0].pts-ue)/t.inputTimeScale,J=E}else K===-1&&(this.warn(`No keyframe found out of ${R} video samples`),b=!1);if(this.ISGenerated){if($&&P){const ue=this.getVideoStartPts(t.samples),q=(gr(e.samples[0].pts,ue)-ue)/t.inputTimeScale;_+=Math.max(0,q),E+=Math.max(0,-q)}if($){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),p=this.generateIS(e,t,r,a)),f=this.remuxAudio(e,_,this.isAudioContiguous,a,I||P||c===At.AUDIO?E:void 0),P){const ue=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),p=this.generateIS(e,t,r,a)),d=this.remuxVideo(t,E,W,ue)}}else P&&(d=this.remuxVideo(t,E,W,0));d&&(d.firstKeyFrame=K,d.independent=K!==-1,d.firstKeyFramePTS=J)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=wL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(y=AL(n,r,this._initPTS))),{audio:f,video:d,initSegment:p,independent:b,text:y,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let a=gr(e,r);if(a0?F-1:F].dts&&(I=!0)}I&&a.sort(function(F,ee){const he=F.dts-ee.dts,be=F.pts-ee.pts;return he||be}),b=a[0].dts,_=a[a.length-1].dts;const $=_-b,P=$?Math.round($/(c-1)):v||e.inputTimeScale/30;if(i){const F=b-R,ee=F>P,he=F<-1;if((ee||he)&&(ee?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zd(F,!0)} ms (${F}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Zd(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!he||R>=a[0].pts||Ju)){b=R;const be=a[0].pts-F;if(ee)a[0].dts=b,a[0].pts=be;else{let pe=!0;for(let Ce=0;Cebe&&pe);Ce++){const Re=a[Ce].pts;if(a[Ce].dts-=F,a[Ce].pts-=F,Ce0?ee.dts-a[F-1].dts:P;if(pe=F>0?ee.pts-a[F-1].pts:P,Re.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ge=Math.floor(Re.maxBufferHole*r),it=(n?E+n*r:this.nextAudioTs+f)-ee.pts;it>Ge?(v=it-Ze,v<0?v=Ze:K=!0,this.log(`It is approximately ${it/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=Ze}else v=Ze}const Ce=Math.round(ee.pts-ee.dts);J=Math.min(J,v),se=Math.max(se,v),ue=Math.min(ue,pe),q=Math.max(q,pe),u.push(mw(ee.key,v,be,Ce))}if(u.length){if(Ju){if(Ju<70){const F=u[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(mv&&q-ue0&&(n&&Math.abs(R-(L+I))<9e3||Math.abs(gr(_[0].pts,R)-(L+I))<20*f),_.forEach(function(q){q.pts=gr(q.pts,R)}),!i||L<0){const q=_.length;if(_=_.filter(Y=>Y.pts>=0),q!==_.length&&this.warn(`Removed ${_.length-q} of ${q} samples (initPTS ${I} / ${a})`),!_.length)return;r===0?L=0:n&&!b?L=Math.max(0,R-I):L=_[0].pts-I}if(e.segmentCodec==="aac"){const q=this.config.maxAudioFramesDrift;for(let Y=0,ie=L+I;Y<_.length;Y++){const Q=_[Y],oe=Q.pts,F=oe-ie,ee=Math.abs(1e3*F/a);if(F<=-q*f&&b)Y===0&&(this.warn(`Audio frame @ ${(oe/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*F/a)} ms.`),this.nextAudioTs=L=oe-I,ie=oe);else if(F>=q*f&&ee0){O+=E;try{B=new Uint8Array(O)}catch(ee){this.observer.emit(G.ERROR,G.ERROR,{type:Pt.MUX_ERROR,details:Le.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:O,reason:`fail allocating audio mdat ${O}`});return}y||(new DataView(B.buffer).setUint32(0,O),B.set(ke.types.mdat,4))}else return;B.set(Q,E);const F=Q.byteLength;E+=F,v.push(mw(!0,d,F,0)),P=oe}const D=v.length;if(!D)return;const M=v[v.length-1];L=P-I,this.nextAudioTs=L+c*M.duration;const W=y?new Uint8Array(0):ke.moof(e.sequenceNumber++,$/c,Qi({},e,{samples:v}));e.samples=[];const K=($-I)/a,J=this.nextAudioTs/a,se={data1:W,data2:B,startPTS:K,endPTS:J,startDTS:K,endDTS:J,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,se}}function gr(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function wj(s){for(let e=0;ea.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class Aj extends Mr{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:a}=this.initData=ID(e);if(t)f6(e,t);else{const c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=pw(r,es.AUDIO,this)),a&&(n=pw(a,es.VIDEO,this));const u={};r&&a?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?u.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,a){var u,c;let{initPTS:d,lastEndTime:f}=this;const p={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};xt(f)||(f=this.lastEndTime=r||0);const y=t.samples;if(!y.length)return p;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let b=this.initData;if((u=b)!=null&&u.length||(this.generateInitSegment(y),b=this.initData),!((c=b)!=null&&c.length))return this.warn("Failed to generate initSegment."),p;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const _=p6(y,b,this),E=b.audio?_[b.audio.id]:null,L=b.video?_[b.video.id]:null,I=Cm(L,1/0),R=Cm(E,1/0),$=Cm(L,0,!0),P=Cm(E,0,!0);let B=r,O=0;const H=E&&(!L||!d&&R0?this.lastEndTime=W:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K=!!b.audio,J=!!b.video;let ue="";K&&(ue+="audio"),J&&(ue+="video");const se=(b.audio?b.audio.encrypted:!1)||(b.video?b.video.encrypted:!1),q={data1:y,startPTS:M,startDTS:M,endPTS:W,endDTS:W,type:ue,hasAudio:K,hasVideo:J,nb:1,dropped:0,encrypted:se};p.audio=K&&!J?q:void 0,p.video=J?q:void 0;const Y=L?.sampleCount;if(Y){const ie=L.keyFrameIndex,Q=ie!==-1;q.nb=Y,q.dropped=ie===0||this.isVideoContiguous?0:Q?ie:Y,q.independent=Q,q.firstKeyFrame=ie,Q&&L.keyFrameStart&&(q.firstKeyFramePTS=(L.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(p.independent=Q),this.isVideoContiguous||(this.isVideoContiguous=Q),q.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ie}/${Y} dropped: ${q.dropped} start: ${q.firstKeyFramePTS||"NA"}`)}return p.initSegment=v,p.id3=wL(i,r,d,d),n.samples.length&&(p.text=AL(n,r,d)),p}}function Cm(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function Cj(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 pw(s,e,t){const i=s.codec;return i&&i.length>4?i:e===es.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?wp(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 ro;try{ro=self.performance.now.bind(self.performance)}catch{ro=Date.now}const qm=[{demux:hj,remux:Aj},{demux:ll,remux:zm},{demux:lj,remux:zm},{demux:cj,remux:zm}];qm.splice(2,0,{demux:uj,remux:zm});class gw{constructor(e,t,i,n,r,a){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=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=ro();let a=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:p,accurateTimeOffset:y,timeOffset:v,initSegmentChange:b}=n||u,{audioCodec:_,videoCodec:E,defaultInitPts:L,duration:I,initSegmentData:R}=c,$=kj(a,t);if($&&Tc($.method)){const H=this.getDecrypter(),D=Xb($.method);if(H.isSync()){let M=H.softwareDecrypt(a,$.key.buffer,$.iv.buffer,D);if(i.part>-1){const K=H.flush();M=K&&K.buffer}if(!M)return r.executeEnd=ro(),pv(i);a=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=H.webCryptoDecrypt(a,$.key.buffer,$.iv.buffer,D).then(M=>{const W=this.push(M,null,i);return this.decryptionPromise=null,W}),this.decryptionPromise}const P=this.needsProbing(f,p);if(P){const H=this.configureTransmuxer(a);if(H)return this.logger.warn(`[transmuxer] ${H.message}`),this.observer.emit(G.ERROR,G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.FRAG_PARSING_ERROR,fatal:!1,error:H,reason:H.message}),r.executeEnd=ro(),pv(i)}(f||p||b||P)&&this.resetInitSegment(R,_,E,I,t),(f||b||P)&&this.resetInitialTimestamp(L),d||this.resetContiguity();const B=this.transmux(a,$,v,y,i);this.asyncResult=Oh(B);const O=this.currentTransmuxState;return O.contiguous=!0,O.discontinuity=!1,O.trackSwitch=!1,r.executeEnd=ro(),B}flush(e){const t=e.transmuxing;t.executeStart=ro();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:u}=n;if(i){const p=i.flush();p&&a.push(this.push(p.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=ro();const p=[pv(e)];return this.asyncResult?Promise.resolve(p):p}const f=c.flush(u);return Oh(f)?(this.asyncResult=!0,f.then(p=>(this.flushRemux(a,p,e),a))):(this.flushRemux(a,f,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,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===At.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,a,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=ro()}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:a,remuxer:u}=this;!a||!u||(a.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 a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let p=0,y=qm.length;p0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const pv=s=>({remuxResult:{},chunkMeta:s});function Oh(s){return"then"in s&&s.then instanceof Function}class Dj{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 Lj{constructor(e,t,i,n,r,a){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=a}}let yw=0;class CL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=yw++,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 y=(p=this.workerContext)==null?void 0:p.objectURL;y&&self.URL.revokeObjectURL(y);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(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.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 a=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===G.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new Jb,this.observer.on(G.FRAG_DECRYPTED,a),this.observer.on(G.ERROR,a);const u=I2(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||OU()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=PU(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=MU());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:is(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new gw(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new gw(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=yw++;const t=this.hls.config,i=I2(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:is(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),BU(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,a,u,c,d,f){var p,y;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:b}=this,_=a?a.start:r.start,E=r.decryptdata,L=this.frag,I=!(L&&r.cc===L.cc),R=!(L&&d.level===L.level),$=L?d.sn-L.sn:-1,P=this.part?d.part-this.part.index:-1,B=$===0&&d.id>1&&d.id===L?.stats.chunkCount,O=!R&&($===1||$===0&&(P===1||B&&P<=0)),H=self.performance.now();(R||$||r.stats.parsing.start===0)&&(r.stats.parsing.start=H),a&&(P||!O)&&(a.stats.parsing.start=H);const D=!(L&&((p=r.initSegment)==null?void 0:p.url)===((y=L.initSegment)==null?void 0:y.url)),M=new Lj(I,O,c,R,_,D);if(!O||I||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===At.MAIN?"level":"track"}: ${d.level} id: ${d.id} - discontinuity: ${I} - trackSwitch: ${R} - contiguous: ${O} - accurateTimeOffset: ${c} - timeOffset: ${_} - initSegmentChange: ${D}`);const W=new Dj(i,n,t,u,f);this.configureTransmuxer(W)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:M},e instanceof ArrayBuffer?[e]:[]);else if(b){const W=b.push(e,E,d,M);Oh(W)?W.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(W)}}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);Oh(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(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.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 vw=100;class Rj extends Zb{constructor(e,t,i){super(e,t,i,"audio-stream-controller",At.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(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(G.BUFFER_RESET,this.onBufferReset,this),e.on(G.BUFFER_CREATED,this.onBufferCreated,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(G.BUFFER_RESET,this.onBufferReset,this),e.off(G.BUFFER_CREATED,this.onBufferCreated,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){if(i===At.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:a},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===Ve.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===Ve.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,a=this.getLevelDetails(),u=this.getLoadPosition(),c=GD(a,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===Ve.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Ve.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(vw),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Ve.IDLE):this.state=Ve.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Ve.IDLE:this.doTickIdle();break;case Ve.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=Ve.WAITING_INIT_PTS}break}case Ve.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Ve.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Ve.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Ve.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,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=Ve.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,es.AUDIO,At.AUDIO));const f=this.getFwdBufferInfo(d,At.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(G.BUFFER_EOS,{type:"audio"}),this.state=Ve.ENDED;return}const p=f.len,y=t.maxBufferLength,v=c.fragments,b=v[0].start,_=this.getLoadPosition(),E=this.flushing?_:f.end;if(this.switchingTrack&&n){const R=_;c.PTSKnown&&Rb||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=b+.05)}if(p>=y&&!this.switchingTrack&&EI.end){const $=this.fragmentTracker.getFragAtPos(E,At.MAIN);$&&$.end>I.end&&(I=$,this.mainFragLoading={frag:$,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 Rh(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!==Ve.STOPPED&&(this.setInterval(vw),this.state=Ve.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(G.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:a,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==Ve.STOPPED&&(this.state=Ve.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[a];let p=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var y;p=this.alignPlaylists(r,f.details,(y=this.levelLastLoaded)==null?void 0:y.details)}r.alignedSliding||(oL(r,d),r.alignedSliding||Ip(r,d),p=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,p),this.hls.trigger(G.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===Ve.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=Ve.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:a,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=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let y=this.transmuxer;y||(y=this.transmuxer=new CL(this.hls,At.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 Yb(i.level,i.sn,i.stats.chunkCount,r.byteLength,E,L);y.push(r,b,p,"",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 lL,complete:!1};_.push(new Uint8Array(r)),this.state!==Ve.STOPPED&&(this.state=Ve.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===At.MAIN&&Is(t.frag)&&(this.mainFragLoading=t,this.state===Ve.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==At.AUDIO){!this.audioOnly&&i.type===At.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(Is(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(G.AUDIO_TRACK_SWITCHED,Hi({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Ve.ERROR;return}switch(t.details){case Le.FRAG_GAP:case Le.FRAG_PARSING_ERROR:case Le.FRAG_DECRYPT_ERROR:case Le.FRAG_LOAD_ERROR:case Le.FRAG_LOAD_TIMEOUT:case Le.KEY_LOAD_ERROR:case Le.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(At.AUDIO,t);break;case Le.AUDIO_TRACK_LOAD_ERROR:case Le.AUDIO_TRACK_LOAD_TIMEOUT:case Le.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ve.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===yi.AUDIO_TRACK&&(this.state=Ve.IDLE);break;case Le.BUFFER_ADD_CODEC_ERROR:case Le.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case Le.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Le.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==es.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==es.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Ve.ENDED&&(this.state=Ve.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,At.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,u=this.getCurrentContext(a);if(!u){this.resetWhenMissingContext(a);return}const{frag:c,part:d,level:f}=u,{details:p}=f,{audio:y,text:v,id3:b,initSegment:_}=r;if(this.fragContextChanged(c)||!p){this.fragmentTracker.removeFragment(c);return}if(this.state=Ve.PARSING,this.switchingTrack&&y&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const E=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(f,_.tracks,E,a),n.trigger(G.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:_.tracks})}if(y){const{startPTS:E,endPTS:L,startDTS:I,endDTS:R}=y;d&&(d.elementaryStreams[es.AUDIO]={startPTS:E,endPTS:L,startDTS:I,endDTS:R}),c.setElementaryStreamInfo(es.AUDIO,E,L,I,R),this.bufferFragmentData(y,c,d,a)}if(b!=null&&(t=b.samples)!=null&&t.length){const E=Qi({id:i,frag:c,details:p},b);n.trigger(G.FRAG_PARSING_METADATA,E)}if(v){const E=Qi({id:i,frag:c,details:p},v);n.trigger(G.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,i,n){if(this.state!==Ve.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=At.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(G.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(G.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Zs.NOT_LOADED||n===Zs.PARTIAL){var r;if(!Is(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=Ve.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ip(t.details,a)}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:a,channels:u}=this.bufferedTrack;ou({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:u},e,Yl)||(Cp(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(G.AUDIO_TRACK_SWITCHED,Hi({},e))}}class aT extends Mr{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 a=0;a=0&&f>t.partTarget&&(c+=1)}const d=i&&N2(i);return new O2(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,a=self.performance.now(),u=r.loading.first?Math.max(0,a-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){SU(i,n,this);const I=n.playlistParsingError;if(I){this.warn(I);const R=this.hls;if(!R.config.ignorePlaylistParsingErrors){var d;const{networkDetails:$}=t;R.trigger(G.ERROR,{type:Pt.NETWORK_ERROR,details:Le.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:$,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const p=this.hls.mainForwardBufferInfo,y=p?p.end-p.len:0,v=(n.edge-y)*1e3,b=iL(n,v);if(n.requestScheduled+b0){if(D>n.targetduration*3)this.log(`Playlist last advanced ${H.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,L=void 0;else if(i!=null&&i.tuneInGoal&&D-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${M} with playlist age: ${n.age}`),M=0;else{const W=Math.floor(M/n.targetduration);if(E+=W,L!==void 0){const K=Math.round(M%n.targetduration/n.partTarget);L+=K}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${H.toFixed(2)}s goal: ${M} skip sn ${W} to part ${L}`)}n.tuneInGoal=M}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,E,L),I||!O){n.requestScheduled=a,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(),a=n.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const u=a-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=N2(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Gm.No),new O2(i,n,r)}checkRetry(e){const t=e.details,i=kp(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===un.RetryRequest||!n.resolved&&r===un.SendAlternateToPenaltyBox);if(c){var d;if(a>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=Kb(u,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function kL(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function Ux(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class Ij extends aT{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(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(G.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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.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(y=>!i||i.indexOf(y.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(y=>y.default)&&(this.selectDefaultTrack=!1),u.forEach((y,v)=>{y.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const y=Sa(c,u,Yl);if(y>-1)r=u[y];else{const v=Sa(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(G.AUDIO_TRACKS_UPDATED,f);const p=this.trackId;if(d!==-1&&p===-1)this.setAudioTrack(d);else if(u.length&&p===-1){var a;const y=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${u.length}`);this.warn(y.message),this.hls.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:y})}}}onError(e,t){t.fatal||!t.context||t.context.type===yi.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&&ou(e,n,Yl))return n;const r=Sa(e,this.tracksInGroup,Yl);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const u=V6(e,t.levels,i,a,Yl);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const a=Sa(e,i);if(a>-1)return i[a]}}}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(G.AUDIO_TRACK_SWITCHING,Hi({},n)),r))return;const a=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(a)}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 a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.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 xw=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,DL="HlsJsTrackRemovedError";class Oj extends Error{constructor(e){super(e),this.name=DL}}class Mj extends Mr{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(G.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=s6(gl(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(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.BUFFER_RESET,this.onBufferReset,this),e.on(G.BUFFER_APPENDING,this.onBufferAppending,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.BUFFER_EOS,this.onBufferEos,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.FRAG_PARSED,this.onFragParsed,this),e.on(G.FRAG_CHANGED,this.onFragChanged,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.BUFFER_RESET,this.onBufferReset,this),e.off(G.BUFFER_APPENDING,this.onBufferAppending,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_EOS,this.onBufferEos,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.FRAG_PARSED,this.onFragParsed,this),e.off(G.FRAG_CHANGED,this.onFragChanged,this),e.off(G.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 a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?Qi(i,n.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=Qi({},this.tracks[a]),this.removeBuffer(a)),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=gl(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&a instanceof c,bw(i),Pj(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,a=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&a){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: ${is(i,(c,d)=>c==="initSegment"?void 0:d)}; -transfer tracks: ${is(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!wD(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(G.MEDIA_DETACHING,{}),this.onMediaAttaching(G.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 y=this.fragmentTracker,v=f.id;if(y.hasFragments(v)||y.hasParts(v)){const E=ri.getBuffered(p);y.detectEvictedFragments(d,E,v,null,!0)}const b=gv(d),_=[d,p];this.sourceBuffers[b]=_,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:a}=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||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&bw(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(G.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[gv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Nj(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 a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(a||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const p=t[c],{id:y,codec:v,levelCodec:b,container:_,metadata:E,supplemental:L}=p;let I=n[c];const R=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],$=R!=null&&R.buffer?R:I,P=$?.pendingCodec||$?.codec,B=$?.levelCodec;I||(I=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:L,container:_,levelCodec:b,metadata:E,id:y});const O=Hm(P,B),H=O?.replace(xw,"$1");let D=Hm(v,b);const M=(f=D)==null?void 0:f.replace(xw,"$1");D&&O&&H!==M&&(c.slice(0,5)==="audio"&&(D=wp(D,this.appendSource)),this.log(`switching codec ${P} to ${D}`),D!==(I.pendingCodec||I.codec)&&(I.pendingCodec=D),I.container=_,this.appendChangeType(c,_,D))}),(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 a=this.tracks[e];if(a){const u=a.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};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,At.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&ri.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,At.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:a,frag:e},this.append(a,"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:a,frag:u,part:c,chunkMeta:d,offset:f}=t,p=d.buffering[r],{sn:y,cc:v}=u,b=self.performance.now();p.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 R=i.video,$=R?.buffer;if($&&y!=="initSegment"){const O=c||u,H=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(R.ending||R.ended)){const M=O.start+O.duration*.05,W=$.buffered,K=this.currentOp("video");!W.length&&!K?this.blockAudio(O):!K&&!ri.isBuffered($,M)&&this.lastVideoAppendEndM||D{var O;p.executeStart=self.performance.now();const H=(O=this.tracks[r])==null?void 0:O.buffer;H&&(I?this.updateTimestampOffset(H,P,.1,r,y,v):f!==void 0&&xt(f)&&this.updateTimestampOffset(H,f,1e-6,r,y,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const O=self.performance.now();p.executeEnd=p.end=O,_.first===0&&(_.first=O),E&&E.first===0&&(E.first=O);const H={};this.sourceBuffers.forEach(([D,M])=>{D&&(H[D]=ri.getBuffered(M))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(G.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:H})},onError:O=>{var H;const D={type:Pt.MEDIA_ERROR,parent:u.type,details:Le.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:O,err:O,fatal:!1},M=(H=this.media)==null?void 0:H.error;if(O.code===DOMException.QUOTA_EXCEEDED_ERR||O.name=="QuotaExceededError"||"quota"in O)D.details=Le.BUFFER_FULL_ERROR;else if(O.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!M)D.errorAction=bc(!0);else if(O.name===DL&&this.sourceBufferCount===0)D.errorAction=bc(!0);else{const W=++this.appendErrors[r];this.warn(`Failed ${W}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${M||"no media error"})`),(W>=this.hls.config.appendErrorMaxRetry||M)&&(D.fatal=!0)}this.hls.trigger(G.ERROR,D)}};this.log(`queuing "${r}" append sn: ${y}${c?" p: "+c.index:""} of ${u.type===At.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append(B,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(G.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(([a])=>{a&&this.append(this.getFlushOp(a,n,r),a)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[es.AUDIOVIDEO]?r.push("audiovideo"):(a[es.AUDIO]&&r.push("audio"),a[es.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(G.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(([a])=>{if(a){const u=this.tracks[a];(!t.type||t.type===a)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${a} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var u;return a&&!((u=this.tracks[a])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(G.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(G.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===Le.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;xt(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,a=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(xt(u)&&u>=0){const d=Math.max(u,a),f=Math.floor(r/a)*a-d;this.flushBackBuffer(r,a,f)}const c=n.frontBufferFlushThreshold;if(xt(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,a),p=Math.floor(r/a)*a+f;this.flushFrontBuffer(r,a,p)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=ri.getBuffered(r);if(u.length>0&&i>u.start(0)){var a;this.hls.trigger(G.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger(G.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(G.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const a=ri.getBuffered(r),u=a.length;if(u<2)return;const c=a.start(u-1),d=a.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(G.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 xt(r)?{duration:r}:null;const a=this.media.duration,u=xt(i.duration)?i.duration:0;return n>u&&n>a||!xt(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(xt(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}) ${is(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(G.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(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.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 a=r,u=e[a];if(this.isPending(u)){const c=this.getTrackCodec(u,a),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${is(u)}`);try{const f=i.addSourceBuffer(d),p=gv(a),y=[a,f];t[p]=y,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:a,mimeType:d,parent:u.id});return}this.trackSourceBuffer(a,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Dh(i,"video")&&(n=w6(n,i));const r=Hm(n,e.levelCodec);return r?t.slice(0,5)==="audio"?wp(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,a)=>{const u=a.removedRanges;u!=null&&u.length&&this.hls.trigger(G.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(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,a){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,a=this.tracks[e],u=a?.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=xt(n.duration)?n.duration:1/0,d=xt(r.duration)?r.duration:1/0,f=Math.max(0,t),p=Math.min(i,c,d);p>f&&(!a.ending||a.ended)?(a.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 Oj(`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(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(a=>{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 a=i.bind(this,e);n.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}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 bw(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Pj(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function gv(s){return s==="audio"?1:0}class oT{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(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.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&&xt(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,oT.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 a=Math.max(t,i);for(let u=0;u=a||c.height>=a)&&n(c,e[u+1])){r=u;break}}return r}}const Bj={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Kn=Bj,Fj={HLS:"h"},Uj=Fj;class Ra{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Ra?i:new Ra(i))),this.value=e,this.params=t}}const jj="Dict";function $j(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 Hj(s,e,t,i){return new Error(`failed to ${s} "${$j(e)}" as ${t}`,{cause:i})}function Ia(s,e,t){return Hj("serialize",s,e,t)}class LL{constructor(e){this.description=e}}const Tw="Bare Item",Gj="Boolean";function Vj(s){if(typeof s!="boolean")throw Ia(s,Gj);return s?"?1":"?0"}function zj(s){return btoa(String.fromCharCode(...s))}const qj="Byte Sequence";function Kj(s){if(ArrayBuffer.isView(s)===!1)throw Ia(s,qj);return`:${zj(s)}:`}const Wj="Integer";function Yj(s){return s<-999999999999999||99999999999999912)throw Ia(s,Qj);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Jj="String",e7=/[\x00-\x1f\x7f]+/;function t7(s){if(e7.test(s))throw Ia(s,Jj);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function i7(s){return s.description||s.toString().slice(7,-1)}const s7="Token";function _w(s){const e=i7(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ia(e,s7);return e}function jx(s){switch(typeof s){case"number":if(!xt(s))throw Ia(s,Tw);return Number.isInteger(s)?RL(s):Zj(s);case"string":return t7(s);case"symbol":return _w(s);case"boolean":return Vj(s);case"object":if(s instanceof Date)return Xj(s);if(s instanceof Uint8Array)return Kj(s);if(s instanceof LL)return _w(s);default:throw Ia(s,Tw)}}const n7="Key";function $x(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Ia(s,n7);return s}function lT(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${$x(e)}`:`;${$x(e)}=${jx(t)}`).join("")}function NL(s){return s instanceof Ra?`${jx(s.value)}${lT(s.params)}`:jx(s)}function r7(s){return`(${s.value.map(NL).join(" ")})${lT(s.params)}`}function a7(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Ia(s,jj);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Ra||(r=new Ra(r));let a=$x(n);return r.value===!0?a+=lT(r.params):(a+="=",Array.isArray(r.value)?a+=r7(r):a+=NL(r)),a}).join(`,${i}`)}function OL(s,e){return a7(s,e)}const ha="CMCD-Object",As="CMCD-Request",Vl="CMCD-Session",sl="CMCD-Status",o7={br:ha,ab:ha,d:ha,ot:ha,tb:ha,tpb:ha,lb:ha,tab:ha,lab:ha,url:ha,pb:As,bl:As,tbl:As,dl:As,ltc:As,mtp:As,nor:As,nrr:As,rc:As,sn:As,sta:As,su:As,ttfb:As,ttfbb:As,ttlb:As,cmsdd:As,cmsds:As,smrt:As,df:As,cs:As,ts:As,cid:Vl,pr:Vl,sf:Vl,sid:Vl,st:Vl,v:Vl,msd:Vl,bs:sl,bsd:sl,cdn:sl,rtp:sl,bg:sl,pt:sl,ec:sl,e:sl},l7={REQUEST:As};function u7(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 c7(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?u7(e):{};return i.reduce((r,a)=>{var u;const c=o7[a]||n[a]||l7.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[a]=s[a],r},t)}function d7(s){return["ot","sf","st","e","sta"].includes(s)}function h7(s){return typeof s=="number"?xt(s):s!=null&&s!==""&&s!==!1}const ML="event";function f7(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 Km=s=>Math.round(s),Hx=(s,e)=>Array.isArray(s)?s.map(t=>Hx(t,e)):s instanceof Ra&&typeof s.value=="string"?new Ra(Hx(s.value,e),s.params):(e.baseUrl&&(s=f7(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),km=s=>Km(s/100)*100,m7=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Ra&&typeof s.value=="string"?t=new Ra([s]):typeof s=="string"&&(t=[s])),Hx(t,e)},p7={br:Km,d:Km,bl:km,dl:km,mtp:km,nor:m7,rtp:km,tb:Km},PL="request",BL="response",uT=["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"],g7=["e"],y7=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function g0(s){return y7.test(s)}function v7(s){return uT.includes(s)||g7.includes(s)||g0(s)}const FL=["d","dl","nor","ot","rtp","su"];function x7(s){return uT.includes(s)||FL.includes(s)||g0(s)}const b7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function T7(s){return uT.includes(s)||FL.includes(s)||b7.includes(s)||g0(s)}const _7=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function S7(s){return _7.includes(s)||g0(s)}const E7={[BL]:T7,[ML]:v7,[PL]:x7};function UL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||PL,r=i===1?S7:E7[n];let a=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(a=a.filter(u));const c=n===BL||n===ML;c&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const d=Qi({},p7,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return a.sort().forEach(p=>{let y=s[p];const v=d[p];if(typeof v=="function"&&(y=v(y,f)),p==="v"){if(i===1)return;y=i}p=="pr"&&y===1||(c&&p==="ts"&&!xt(y)&&(y=Date.now()),h7(y)&&(d7(p)&&typeof y=="string"&&(y=new LL(y)),t[p]=y))}),t}function w7(s,e={}){const t={};if(!s)return t;const i=UL(s,e),n=c7(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[a,u])=>{const c=OL(u,{whitespace:!1});return c&&(r[a]=c),r},t)}function A7(s,e,t){return Qi(s,w7(e,t))}const C7="CMCD";function k7(s,e={}){return s?OL(UL(s,e),{whitespace:!1}):""}function D7(s,e={}){if(!s)return"";const t=k7(s,e);return encodeURIComponent(t)}function L7(s,e={}){if(!s)return"";const t=D7(s,e);return`${C7}=${t}`}const Sw=/CMCD=[^&#]+/;function R7(s,e,t){const i=L7(e,t);if(!i)return s;if(Sw.test(s))return s.replace(Sw,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class I7{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:Kn.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:a}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(a||r).duration*1e3,ot:c};(c===Kn.VIDEO||c===Kn.AUDIO||c==Kn.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=a?this.getNextPart(a):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(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHED,this.onMediaDetached,this),e.on(G.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHED,this.onMediaDetached,this),e.off(G.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:Uj.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Qi(t,this.createData());const i=t.ot===Kn.INIT||t.ot===Kn.VIDEO||t.ot===Kn.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((a,u)=>(n.includes(u)&&(a[u]=t[u]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),A7(e.headers,t,r)):e.url=R7(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:a}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===a)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Kn.TIMED_TEXT;if(e.sn==="initSegment")return Kn.INIT;if(t==="audio")return Kn.AUDIO;if(t==="main")return this.hls.audioTracks.length?Kn.VIDEO:Kn.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Kn.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===Kn.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ri.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,a,u){t(r),this.loader.load(r,a,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,a,u){t(r),this.loader.load(r,a,u)}}}}const N7=3e5;class O7 extends Mr{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(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.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===un.SendAlternateToPenaltyBox&&i.flags===pr.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?a=this.getPathwayForGroupId(u,d,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),t.details===Le.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: ${a} levels: ${n&&n.length} priorities: ${is(r)} penalized: ${is(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]>N7&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,rL(t),this.hls.trigger(G.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:a,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===a))return;const d=this.getLevelsForPathway(u).map(f=>{const p=new xs(f.attrs);p["PATHWAY-ID"]=a;const y=p.AUDIO&&`${p.AUDIO}_clone_${a}`,v=p.SUBTITLES&&`${p.SUBTITLES}_clone_${a}`;y&&(i[p.AUDIO]=y,p.AUDIO=y),v&&(n[p.SUBTITLES]=v,p.SUBTITLES=v);const b=jL(f.uri,p["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new Rh({attrs:p,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||y.url),E&&this.clonePathways(E);const I={steeringManifest:b,url:n.toString()};this.hls.trigger(G.STEERING_MANIFEST_LOADED,I),L&&this.updatePathwayPriority(L)},onError:(f,p,y,v)=>{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 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 ${p.url} rate limited`);return}this.scheduleRefresh(this.uri||p.url,b)},onTimeout:(f,p,y)=>{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 Ew(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const u=Qi({},a);return u.details=void 0,u.attrs=new xs(u.attrs),u.url=u.attrs.URI=jL(a.url,a.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 jL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let u;e&&(u=a?.[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 _c extends Mr{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=_c.CDMCleanupPromise?[_c.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 a=Object.keys(this.keySystemAccessPromises);a.length||(a=lh(this.config));const u=a.map(lv).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(a=>{const u=Vm(a);if(i!=="sinf"||u!==bs.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const v=Qs(new Uint8Array(n)),b=Qb(JSON.parse(v).sinf),_=OD(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=dn(c),{keyIdToKeySessionPromise:f,mediaKeySessions:p}=this;let y=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(b,i,n,"encrypted-event-key-match")),y.catch(L=>this.handleError(L));break}}y||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${p.length}.`))}).catch(a=>this.handleError(a))}},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(G.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(G.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(G.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(G.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(G.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(G.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(G.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===bs.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=(a,u,c)=>!!a&&c.indexOf(a)===u,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(p=>a({keySystem:f,mediaKeys:p})).catch(p=>{d.length?c(d):p instanceof mr?u(p):u(new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.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 QD===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=mU(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],u=(n=a)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${is(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=a=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(y=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(y,e,v):y)));return p.catch(y=>{this.error(`Failed to create media-keys for "${e}"}: ${y}`)}),p})}return u.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${dn(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=Dm(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 ${dn(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})=>lv(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=lv(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=lh(this.config),i=e.map(Vm).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 a.catch(u=>{if(u instanceof mr){const c=Hi({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new mr(c,u.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof mr){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${dn(i.keyId||[])})`:""}`),this.hls.trigger(G.ERROR,e.data)}else this.error(e.message),this.hls.trigger(G.ERROR,{type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Dm(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Vm(e.keyFormat),r=n?[n]:lh(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=lh(this.config)),e.length===0)throw new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${is({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,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));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 a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const b=a.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=Dm(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 Jb,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===bs.FAIRPLAY&&this.updateKeySession(e,Ox("acknowledged")).then(()=>this.removeSession(e)).catch(I=>this.handleError(I)):this.warn(`unhandled media key message type "${E}"`)},p=(b,_)=>{_.keyStatus=b;let E;b.startsWith("usable")?d.emit("resolved"):b==="internal-error"||b==="output-restricted"||b==="output-downscaled"?E=ww(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))},y=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const E=this.getKeyStatuses(e);if(!Object.keys(E).some($=>E[$]!=="status-pending"))return;if(E[u]==="expired"){this.log(`Expired key ${is(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let I=E[u];if(I)p(I,e);else{var R;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(R=e.keyStatusTimeouts)[u]||(R[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const P=this.getKeyStatus(e.decryptdata);if(P&&P!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${P} from other session.`),p(P,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} (${is(E)}).`)}};In(e.mediaKeysSession,"message",f),In(e.mediaKeysSession,"keystatuseschange",y);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 mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.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===bs.PLAYREADY&&r.length===16){const u=dn(r);t[u]=i,YD(r)}const a=dn(r);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=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((a,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:(y,v,b,_)=>{a(y.data)},onError:(y,v,b,_)=>{u(new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:Hi({url:c.url,data:void 0},y)},`"${e}" certificate request failed (${r}). Status: ${y.code} (${y.text})`))},onTimeout:(y,v,b)=>{u(new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(y,v,b)=>{u(new Error("aborted"))}};n.load(c,f,p)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.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,y=r.length;p in key message");return Ox(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(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||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 a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);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,a,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 mr({type:Pt.KEY_SYSTEM_ERROR,details:Le.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:a,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${a}). 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,a,e,t).then(({xhr:c,licenseChallenge:d})=>{e.keySystem==bs.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,In(i,"encrypted",this.onMediaEncrypted),In(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Qn(e,"encrypted",this.onMediaEncrypted),Qn(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,fl.clearKeyUriToKeyIdMap();const r=n.length;_c.CDMCleanupPromise=Promise.all(n.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).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: ${dn(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:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));const{drmSystemOptions:u}=this.config;return(gU(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(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.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(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}_c.CDMCleanupPromise=void 0;function Dm(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return dn(s.keyId)}function M7(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 mr 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 ww(s,e){const t=s==="output-restricted",i=t?Le.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Le.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new mr({type:Pt.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class P7{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(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(G.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(G.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,a=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*a/r,d=this.hls;if(d.trigger(G.FPS_DROP,{currentDropped:a,currentDecoded:u,totalDroppedFrames:i}),c>0&&a>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(G.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 $L(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 HL(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){Gi.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){Gi.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function uc(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 Gx(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=F7(s.cues,e,t);for(let a=0;as[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,a=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function Wm(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=Wm(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(G.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(G.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;Wm(i.textTracks).forEach(a=>{uc(a)})}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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.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(a=>n?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(f=>f.default)&&(this.selectDefaultTrack=!1),a.forEach((f,p)=>{f.id=p});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=Sa(u,a);if(f>-1)r=a[f];else{const p=Sa(u,this.tracks);r=this.tracks[p]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(G.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=Sa(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),a=e.details,u=a?.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&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(G.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Wm(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Ux(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||!xt(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(G.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:a,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(G.SUBTITLE_TRACK_SWITCH,{id:a,groupId:u,name:c,type:d,url:f});const p=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(p)}}function j7(){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 _h(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Sc=.025;let Op=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function $7(s,e,t){return`${s.identifier}-${t+1}-${_h(e)}`}class H7{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 yv(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=yv(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=xt(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 yv(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 G7(this)}}function yv(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function nc(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class V7{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(G.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const a=()=>{this.hasDetails=!0};r.once(G.LEVEL_LOADED,a),r.once(G.AUDIO_TRACK_LOADED,a),r.once(G.SUBTITLE_TRACK_LOADED,a),r.on(G.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(G.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(G.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=GL(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=ri.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=ri.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: ${nc(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Aw=.033;class z7 extends Mr{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)):[];a.length&&a.sort((d,f)=>{const p=d.cue.pre,y=d.cue.post,v=f.cue.pre,b=f.cue.post;if(p&&!v)return-1;if(v&&!p||y&&!b)return 1;if(b&&!y)return-1;if(!p&&!v&&!y&&!b){const _=d.startTime,E=f.startTime;if(_!==E)return _-E}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=a,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,a=this.parseSchedule(n,e);(i||t.length||r?.length!==a.length||a.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=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let a=0;a!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,p)=>{const y=f.cue.pre,v=f.cue.post,b=e[p-1]||null,_=f.appendInPlace,E=v?r:f.startOffset,L=f.duration,I=f.timelineOccupancy===Op.Range?L:0,R=f.resumptionOffset,$=b?.startTime===E,P=E+f.cumulativeDuration;let B=_?P+L:E+R;if(y||!v&&E<=0){const H=d;d+=I,f.timelineStart=P;const D=a;a+=L,i.push({event:f,start:P,end:B,playout:{start:D,end:a},integrated:{start:H,end:d}})}else if(E<=r){if(!$){const M=E-c;if(M>Aw){const W=c,K=d;d+=M;const J=a;a+=M;const ue={previousEvent:e[p-1]||null,nextEvent:f,start:W,end:W+M,playout:{start:J,end:a},integrated:{start:K,end:d}};i.push(ue)}else M>0&&b&&(b.cumulativeDuration+=M,i[i.length-1].end=E)}v&&(B=P),f.timelineStart=P;const H=d;d+=I;const D=a;a+=L,i.push({event:f,start:P,end:B,playout:{start:D,end:a},integrated:{start:H,end:d}})}else return;const O=f.resumeTime;v||O>r?c=r:c=O}),c{const d=u.cue.pre,f=u.cue.post,p=d?0:f?n:u.startTime;this.updateAssetDurations(u),a===p?u.cumulativeDuration=r:(r=0,a=p),!f&&u.snapOptions.in&&(u.resumeAnchor=du(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+1Sc?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(a=>{const u=t[a].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`),!1;const d=du(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=a==="audio"?.175:0;return Math.abs(d.start-i){const E=y.data,L=E?.ASSETS;if(!Array.isArray(L)){const I=this.assignAssetListError(e,Le.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),b.url,v,_);this.hls.trigger(G.ERROR,I);return}e.assetListResponse=E,this.hls.trigger(G.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:_})},onError:(y,v,b,_)=>{const E=this.assignAssetListError(e,Le.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${y.code} ${y.text} (${v.url})`),v.url,_,b);this.hls.trigger(G.ERROR,E)},onTimeout:(y,v,b)=>{const _=this.assignAssetListError(e,Le.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,y,b);this.hls.trigger(G.ERROR,_)}};return u.load(c,f,p),this.hls.trigger(G.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,a){return e.error=i,{type:Pt.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:a,stats:r}}}function Cw(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Lm(s,e){return`[${s}] Advancing timeline position to ${e}`}class K7 extends Mr{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 a=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),a&&i=u.end){var c;const v=this.findItemIndex(u);let b=this.schedule.findItemIndexAtTime(i);if(b===-1&&(b=v+(a?-1:1),this.log(`seeked ${a?"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),!a&&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,p=d.duration||0;if(a&&i=f+p){var y;(y=u.event)!=null&&y.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 a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const a=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(_=>Gr(_))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let y=null,v=null;a&&(y=this.updateItem(a,this.timelinePos),this.itemsMatch(a,y)?this.playingItem=y: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)>Sc&&this.warn(`${I} ("${_.assetId}" ${_.timelineOffset}->${E})`)}}}),p||n){if(this.hls.trigger(G.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(a)&&f.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(y,a),b&&v!==y&&this.trimInPlace(v,b),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new q7(e),this.schedule=new z7(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(G.MEDIA_ENDED,this.onMediaEnded,this),e.on(G.ERROR,this.onError,this),e.on(G.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(G.MEDIA_ENDED,this.onMediaEnded,this),e.off(G.ERROR,this.onError,this),e.off(G.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){Qn(e,"play",this.onPlay),Qn(e,"pause",this.onPause),Qn(e,"seeking",this.onSeeking),Qn(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;In(i,"seeking",this.onSeeking),In(i,"timeupdate",this.onTimeupdate),In(i,"play",this.onPlay),In(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,y,v,b,_)=>{if(p){let E=p[y].start;const L=p.event;if(L){if(y==="playout"||L.timelineOccupancy!==Op.Point){const I=i(v);I?.interstitial===L&&(E+=I.assetItem.startOffset+I[_])}}else{const I=b==="bufferedPos"?a():e[b];E+=I-p.start}return E}return 0},r=(p,y)=>{var v;if(p!==0&&y!=="primary"&&(v=e.schedule)!=null&&v.length){var b;const _=e.schedule.findItemIndexAtTime(p),E=(b=e.schedule.items)==null?void 0:b[_];if(E){const L=E[y].start-E.start;return p+L}}return p},a=()=>{const p=e.bufferedPos;return p===Number.MAX_VALUE?u("primary"):Math.max(p,0)},u=p=>{var y,v;return(y=e.primaryDetails)!=null&&y.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[p])||0},c=(p,y)=>{var v,b;const _=e.effectivePlayingItem;if(_!=null&&(v=_.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${p} "${y}"`);const E=e.effectivePlayingItem,L=e.schedule.findItemIndexAtTime(p,y),I=(b=e.schedule.items)==null?void 0:b[L],R=e.getBufferingPlayer(),$=R?.interstitial,P=$?.appendInPlace,B=E&&e.itemsMatch(E,I);if(E&&(P||B)){const O=i(e.playingAsset),H=O?.media||e.primaryMedia;if(H){const D=y==="primary"?H.currentTime:n(E,y,e.playingAsset,"timelinePos","currentTime"),M=p-D,W=(P?D:H.currentTime)+M;if(W>=0&&(!O||P||W<=O.duration)){H.currentTime=W;return}}}if(I){let O=p;if(y!=="primary"){const D=I[y].start,M=p-D;O=I.start+M}const H=!e.isInterstitial(I);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(H||I.event.appendInPlace)){const D=e.media||(P?R?.media:null);D&&(D.currentTime=O)}else if(E){const D=e.findItemIndex(E);if(L>D){const W=e.schedule.findJumpRestrictedIndex(D+1,L);if(W>D){e.setSchedulePosition(W);return}}let M=0;if(H)e.timelinePos=O,e.checkBuffer();else{const W=I.event.assetList,K=p-(I[y]||I).start;for(let J=W.length;J--;){const ue=W[J];if(ue.duration&&K>=ue.startOffset&&K{const p=e.effectivePlayingItem;if(e.isInterstitial(p))return p;const y=t();return e.isInterstitial(y)?y:null},f={get bufferedEnd(){const p=t(),y=e.bufferingItem;if(y&&y===p){var v;return n(y,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-y.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const p=d(),y=e.effectivePlayingItem;return y&&y===p?n(y,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-y.playout.start:0},set currentTime(p){const y=d(),v=e.effectivePlayingItem;v&&v===y&&c(p+v.playout.start,"playout")},get duration(){const p=d();return p?p.playout.end-p.playout.start:0},get assetPlayers(){var p;const y=(p=d())==null?void 0:p.event.assetList;return y?y.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var p;const y=(p=d())==null?void 0:p.event;return y&&e.effectivePlayingAsset?y.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 a()},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,y=p?.event;if(y&&!y.restrictions.skip){const v=e.findItemIndex(p);if(y.appendInPlace){const b=p.playout.start+p.event.duration;c(b+.001,"playout")}else e.advanceAfterAssetEnded(y,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||!xt(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} ${is(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 a=this.hls,u=e!==a,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(a.media)c&&(r=a.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 ${is(r)}`);else if(!this.detachedData||a.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 p=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",y=p&&r?r:t;this.log(`${p?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(y===r&&v){const b=u&&e.assetId===v.assetIdAtEnd;y.overrides={duration:v.duration,endOfStream:!u||b,cueRemoval:!u}}e.attachMedia(y)}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(Lm("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){const a=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(a);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=vv(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const u=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=vv(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,u=r.length;if(a>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Gr(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(a)){const f=a.event,p=this.playingAsset,y=p?.identifier,v=y?this.getAssetPlayer(y):null;if(v&&y&&(!this.eventItemsMatch(a,r)||t!==void 0&&y!==f.assetList[t].identifier)){var c;const b=f.findAssetIndex(p);if(this.log(`INTERSTITIAL_ASSET_ENDED ${b+1}/${f.assetList.length} ${nc(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger(G.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:b,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),b);return}this.retreiveMediaSource(y,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${Gr(a)}`),f.hasPlayed=!0,this.hls.trigger(G.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,a,u)}return}}this.advanceSchedule(e,n,t,a,u)}advanceSchedule(e,t,i,n,r){const a=this.schedule;if(!a)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const p=f.interstitial,y=a.findEventIndex(p.identifier);(ye+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=a.findAssetIndex(f,this.timelinePos);const b=vv(f,i-1);if(f.isAssetPastPlayoutLimit(b)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=b}const p=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let y=this.preloadAssets(f,i);if(this.eventItemsMatch(u,p||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${Gr(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(G.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(y||(y=this.getAssetPlayer(v.identifier)),y===null||y.destroyed){const b=f.assetList.length;this.warn(`asset ${i+1}/${b} player destroyed ${f}`),y=this.createAssetPlayer(f,v,i),y.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(y,i,t,e,c),this.shouldPlay&&Cw(y.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(a.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 ${Gr(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(Lm("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Gr(e)}`),this.hls.trigger(G.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.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:ri.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(Lm("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(G.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(G.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=Hi(Hi({},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=Hi(Hi({},this.altSelection),{},{audio:i});return}const r=Hi(Hi({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Hi(Hi({},this.altSelection),{},{subtitles:i});return}const r=Hi(Hi({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=P2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=P2(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,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=ri.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Gr(e)} (was ${Gr(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=ri.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 a=this.playingItem,u=this.findItemIndex(a);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=y.event)!=null&&d.appendInPlace&&e+.01>=y.start)&&(c=p),this.isInterstitial(r)){const v=r.event;if(p-u>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(y);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&y.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 a=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 ${Gr(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,p)=>{const y=this.getAssetPlayer(f.identifier);y&&(p===d&&y.loadSource(),y.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(G.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 a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(a,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,a=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const y=this.playingItem;!this.isInterstitial(y)&&(y==null||(u=y.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 y=f-c;y>0&&(d=Math.round(y*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(!a&&n){for(let d=t;d{this.hls.trigger(G.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const P=t.duration;P&&${if($.live){var P;const H=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Pt.OTHER_ERROR,details:Le.INTERSTITIAL_ASSET_ITEM_ERROR,error:H},M=((P=this.schedule)==null?void 0:P.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,M,i,H.message);return}const B=$.edge-$.fragmentStart,O=t.duration;(_||O===null||B>O)&&(_=!1,this.log(`Interstitial asset "${p}" duration change ${O} > ${B}`),t.duration=B,this.updateSchedule())};b.on(G.LEVEL_UPDATED,($,{details:P})=>E(P)),b.on(G.LEVEL_PTS_UPDATED,($,{details:P})=>E(P)),b.on(G.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const L=($,P)=>{const B=this.getAssetPlayer(p);if(B&&P.tracks){B.off(G.BUFFER_CODECS,L),B.tracks=P.tracks;const O=this.primaryMedia;this.bufferingAsset===B.assetItem&&O&&!B.media&&this.bufferAssetPlayer(B,O)}};b.on(G.BUFFER_CODECS,L);const I=()=>{var $;const P=this.getAssetPlayer(p);if(this.log(`buffered to end of asset ${P}`),!P||!this.schedule)return;const B=this.schedule.findEventIndex(e.identifier),O=($=this.schedule.items)==null?void 0:$[B];this.isInterstitial(O)&&this.advanceAssetBuffering(O,t)};b.on(G.BUFFERED_TO_END,I);const R=$=>()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;this.shouldPlay=!0;const B=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,B,$)};return b.once(G.MEDIA_ENDED,R(i)),b.once(G.PLAYOUT_LIMIT_REACHED,R(1/0)),b.on(G.ERROR,($,P)=>{if(!this.schedule)return;const B=this.getAssetPlayer(p);if(P.details===Le.BUFFER_STALLED_ERROR){if(B!=null&&B.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(P,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${P.error} ${e}`)}),b.on(G.DESTROYING,()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;const P=new Error(`Asset player destroyed unexpectedly ${p}`),B={fatal:!0,type:Pt.OTHER_ERROR,details:Le.INTERSTITIAL_ASSET_ITEM_ERROR,error:P};this.handleAssetItemError(B,e,this.schedule.findEventIndex(e.identifier),i,P.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${nc(t)}`),this.hls.trigger(G.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&&Gr(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:a,assetItem:u,assetId:c}=e,d=a.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} ${nc(u)}`),this.hls.trigger(G.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:a,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:a}=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=a;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&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(p&&!wD(p,e.tracks)){const y=new Error(`Asset ${nc(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(p)}')`),v={fatal:!0,type:Pt.OTHER_ERROR,details:Le.INTERSTITIAL_ASSET_ITEM_ERROR,error:y},b=r.findAssetIndex(a);this.handleAssetItemError(v,r,u,b,y.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),a=e.assetList[r];if(a){const u=this.getAssetPlayer(a.identifier);if(u){const c=u.currentTime||n-a.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 p=this.waitingItem,y=p?.event.identifier===a;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(y){var b;const _=this.schedule.findEventIndex(a),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===a){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 Le.ASSET_LIST_PARSING_ERROR:case Le.ASSET_LIST_LOAD_ERROR:case Le.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case Le.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 kw=500;class W7 extends Zb{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",At.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(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Ve.IDLE,this.setInterval(kw),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)||(Is(i)&&(this.fragPrevious=i),this.state=Ve.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){a=r[d];break}const c=i.start+i.duration;a?a.end=c:(a={start:u,end:c},r.push(a)),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(a=>{for(let u=0;unew Rh(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new Rh(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,At.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!==Ve.STOPPED&&this.setInterval(kw)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:a,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 [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(i=c.details)!=null&&i.live){if(a.deltaUpdateFailed)return;const p=this.mainDetails;if(!p){this.startFragRequested=!1;return}const y=p.fragments[0];if(!c.details)a.hasProgramDateTime&&p.hasProgramDateTime?(Ip(a,p),d=a.fragmentStart):y&&(d=y.start,Px(a,d));else{var f;d=this.alignPlaylists(a,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&y&&(d=y.start,Px(a,d))}p&&!this.startFragRequested&&this.setStartPosition(p,d)}c.details=a,this.levelLastLoaded=c,u===n&&(this.hls.trigger(G.SUBTITLE_TRACK_UPDATED,{details:a,id:u,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Ve.IDLE&&(du(null,a.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&&Tc(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Xb(n.method)).catch(u=>{throw r.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(G.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:a,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=Ve.IDLE})}}doTick(){if(!this.media){this.state=Ve.IDLE;return}if(this.state===Ve.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(),a=ri.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=a,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const p=d.fragments,y=p.length,v=d.edge;let b=null;const _=this.fragPrevious;if(uv-I?0:I;b=du(_,p,Math.max(p[0].start,u),R),!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 X7={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},VL=s=>String.fromCharCode(X7[s]||s),zr=15,to=100,Q7={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Z7={17:2,18:4,21:6,22:8,23:10,19:13,20:15},J7={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},e9={25:2,26:4,29:6,30:8,31:10,27:13,28:15},t9=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class i9{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Gi.log(`${this.time} [${e}] ${i}`)}}}const zl=function(e){const t=[];for(let i=0;ito&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=to)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=VL(e);if(this.pos>=to){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 = "+is(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+is(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 Dw{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 xv(i),this.nonDisplayedMemory=new xv(i),this.lastOutputScreen=new xv(i),this.currRollUpRow=this.displayedMemory.rows[zr-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[zr-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: "+is(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 Lw{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=a9(),this.logger=void 0;const n=this.logger=new i9;this.channels=[null,new Dw(e,t,n),new Dw(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"["+zl([t[i],t[i+1]])+"] -> ("+zl([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(r9(n,r,c)){Rm(null,null,c),this.logger.log(3,()=>"Repeated command ("+zl([n,r])+") is dropped");continue}Rm(n,r,this.cmdHistory),a=this.parseCmd(n,r),a||(a=this.parseMidrow(n,r)),a||(a=this.parsePAC(n,r)),a||(a=this.parseBackgroundAttributes(n,r))}else Rm(null,null,c);if(!a&&(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?")}!a&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+zl([n,r])+" orig: "+zl([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,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.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 ("+zl([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 a=e<=23?1:2;t>=64&&t<=95?i=a===1?Q7[e]:J7[e]:i=a===1?Z7[e]:e9[e];const u=this.channels[a];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!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 a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+VL(a)+"' in channel "+i),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+zl(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 a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=t9[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(a),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");B=M,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},p,{get:function(){return O},set:function(M){const W=n(M);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");O=W,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},p,{get:function(){return H},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");H=M,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},p,{get:function(){return D},set:function(M){const W=n(M);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");D=W,this.hasBeenReset=!0}})),f.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class o9{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function qL(s){function e(i,n,r,a){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(a||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 l9{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 KL(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const a=n[r].split(t);if(a.length!==2)continue;const u=a[0],c=a[1];e(u,c)}}const Vx=new cT(0,0,""),Im=Vx.align==="middle"?"middle":"center";function u9(s,e,t){const i=s;function n(){const u=qL(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 l9;KL(u,function(y,v){let b;switch(y){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===v){d.set(y,t[_].region);break}break;case"vertical":d.alt(y,v,["rl","lr"]);break;case"line":b=v.split(","),d.integer(y,b[0]),d.percent(y,b[0])&&d.set("snapToLines",!1),d.alt(y,b[0],["auto"]),b.length===2&&d.alt("lineAlign",b[1],["start",Im,"end"]);break;case"position":b=v.split(","),d.percent(y,b[0]),b.length===2&&d.alt("positionAlign",b[1],["start",Im,"end","line-left","line-right","auto"]);break;case"size":d.percent(y,v);break;case"align":d.alt(y,v,["start",Im,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&Vx.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",Im);let p=d.get("position","auto");p==="auto"&&Vx.position===50&&(p=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=p}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=n(),a(),r(s,e)}function WL(s){return s.replace(//gi,` -`)}class c9{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new o9,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,a=0;for(r=WL(r);a")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{u9(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&&(a=!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 d9=/\r\n|\n\r|\n|\r/g,bv=function(e,t,i=0){return e.slice(i,i+t.length)===t},h9=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(!xt(t)||!xt(i)||!xt(n)||!xt(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function dT(s,e,t){return _h(s.toString())+_h(e.toString())+_h(t)}const f9=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(;(a=r)!=null&&a.new;){var a;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function m9(s,e,t,i,n,r,a){const u=new c9,c=xr(new Uint8Array(s)).trim().replace(d9,` -`).split(` -`),d=[],f=e?bj(e.baseTime,e.timescale):0;let p="00:00.000",y=0,v=0,b,_=!0;u.oncue=function(E){const L=t[i];let I=t.ccOffset;const R=(y-f)/9e4;if(L!=null&&L.new&&(v!==void 0?I=t.ccOffset=L.start:f9(t,i,R)),R){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}I=R-t.presentationOffset}const $=E.endTime-E.startTime,P=gr((E.startTime+I-v)*9e4,n*9e4)/9e4;E.startTime=Math.max(P,0),E.endTime=Math.max(P+$,0);const B=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(B)),E.id||(E.id=dT(E.startTime,E.endTime,B)),E.endTime>0&&d.push(E)},u.onparsingerror=function(E){b=E},u.onflush=function(){if(b){a(b);return}r(d)},c.forEach(E=>{if(_)if(bv(E,"X-TIMESTAMP-MAP=")){_=!1,E.slice(16).split(",").forEach(L=>{bv(L,"LOCAL:")?p=L.slice(6):bv(L,"MPEGTS:")&&(y=parseInt(L.slice(7)))});try{v=h9(p)/1e3}catch(L){b=L}return}else E===""&&(_=!1);u.parse(E+` -`)}),u.flush()}const Tv="stpp.ttml.im1t",YL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,XL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,p9={left:"start",center:"center",right:"end",start:"start",end:"end"};function Rw(s,e,t,i){const n=pi(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>xr(u)),a=xj(e.baseTime,1,e.timescale);try{r.forEach(u=>t(g9(u,a)))}catch(u){i(u)}}function g9(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},a=Object.keys(r).reduce((p,y)=>(p[y]=n.getAttribute(`ttp:${y}`)||r[y],p),{}),u=n.getAttribute("xml:space")!=="preserve",c=Iw(_v(n,"styling","style")),d=Iw(_v(n,"layout","region")),f=_v(n,"body","[begin]");return[].map.call(f,p=>{const y=QL(p,u);if(!y||!p.hasAttribute("begin"))return null;const v=Ev(p.getAttribute("begin"),a),b=Ev(p.getAttribute("dur"),a);let _=Ev(p.getAttribute("end"),a);if(v===null)throw Nw(p);if(_===null){if(b===null)throw Nw(p);_=v+b}const E=new cT(v-e,_-e,y);E.id=dT(E.startTime,E.endTime,E.text);const L=d[p.getAttribute("region")],I=c[p.getAttribute("style")],R=y9(L,I,c),{textAlign:$}=R;if($){const P=p9[$];P&&(E.lineAlign=P),E.align=$}return Qi(E,R),E}).filter(p=>p!==null)}function _v(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Iw(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function QL(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?QL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function y9(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((u,c)=>{const d=Sv(e,i,c)||Sv(s,i,c)||Sv(n,i,c);return d&&(u[c]=d),u},{})}function Sv(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Nw(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Ev(s,e){if(!s)return null;let t=qL(s);return t===null&&(YL.test(s)?t=v9(s,e):XL.test(s)&&(t=x9(s,e))),t}function v9(s,e){const t=YL.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 x9(s,e){const t=XL.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 Nm{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 b9{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=Mw(),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(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Nm(this,"textTrack1"),t=new Nm(this,"textTrack2"),i=new Nm(this,"textTrack3"),n=new Nm(this,"textTrack4");this.cea608Parser1=new Lw(1,e,t),this.cea608Parser2=new Lw(3,i,n)}addCues(e,t,i,n,r){let a=!1;for(let u=r.length;u--;){const c=r[u],d=T9(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,d/(i-t)>.5))return}if(a||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(G.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){const{unparsedVttFrags:u}=this;i===At.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:a}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(G.FRAG_LOADED,c):this.hls.trigger(G.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{uc(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Mw(),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===Tv);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(kL(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,u=a?Wm(a.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let p=null;for(let y=0;yd!==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 a=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(G.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}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]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.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===At.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:a,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&a&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===At.SUBTITLE)if(n.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){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===Tv?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Rw(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,u=r.length-1;if(!r[i.cc]&&u===-1){a.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?Ir(i.initSegment.data,new Uint8Array(n)).buffer:n;m9(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const p=f.message==="Missing initPTS for VTT MPEGTS";p?a.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(p&&u>i.cc)&&c.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Rw(t,this.initPTS[e.cc],()=>{i.textCodec=Tv,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=>HL(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(G.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===At.SUBTITLE&&this.onFragLoaded(G.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===At.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;rGx(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>Gx(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=WL(d.trim()),b=dT(e,t,v);s!=null&&(p=s.cues)!=null&&p.getCueById(b)||(a=new f(e,t,v),a.id=b,a.line=y+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((y,v)=>y.line==="auto"||v.line==="auto"?0:y.line>8&&v.line>8?v.line-y.line:y.line-v.line),n.forEach(y=>HL(s,y))),n}};function E9(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const w9=/(\d+)-(\d+)\/(\d+)/;class Pw{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||D9,this.controller=new self.AbortController,this.stats=new Gb}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=A9(e,this.controller.signal),a=e.responseType==="arraybuffer",u=a?"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&&xt(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Oh(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(p=>{var y;this.response=this.loader=p;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)),!p.ok){const{status:_,statusText:E}=p;throw new L9(E||"fetch, bad network response",_,p)}n.loading.first=v,n.total=k9(p.headers)||n.total;const b=(y=this.callbacks)==null?void 0:y.onProgress;return b&&xt(t.highWaterMark)?this.loadProgressively(p,n,e,t.highWaterMark,b):a?p.arrayBuffer():e.responseType==="json"?p.json():p.text()}).then(p=>{var y,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 _=p[u];_&&(n.loaded=n.total=_);const E={url:b.url,data:p,code:b.status},L=(y=this.callbacks)==null?void 0:y.onProgress;L&&!xt(t.highWaterMark)&&L(n,e,p,b),(v=this.callbacks)==null||v.onSuccess(E,n,e,b)}).catch(p=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=p&&p.code||0,b=p?p.message:null;(y=this.callbacks)==null||y.onError({code:v,text:b},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 a=new lL,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,p=f.length;return t.loaded+=p,p=n&&r(t,i,a.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function A9(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Qi({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function C9(s){const e=w9.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function k9(s){const e=s.get("Content-Range");if(e){const i=C9(e);if(xt(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function D9(s,e){return new self.Request(s.url,e)}class L9 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const R9=/^age:\s*[\d.]+\s*$/im;class JL{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 Gb,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(a=>{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(a=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:a.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:a}=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&&xt(r)?r:a,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 a,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=(a=this.callbacks)==null?void 0:a.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 p=r.loadPolicy.errorRetry,y=i.retry,v={url:e.url,data:void 0,code:d};if(Dp(p,y,!1,v))this.retry(p);else{var c;Gi.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(Dp(e,t,!0))this.retry(e);else{var i;Gi.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=Kb(e,i.retry),i.retry++,Gi.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&&R9.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 I9={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},N9=Hi(Hi({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:JL,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:z6,bufferController:Mj,capLevelController:oT,errorController:X6,fpsController:P7,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:QD,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:I9},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},O9()),{},{subtitleStreamController:W7,subtitleTrackController:U7,timelineController:b9,audioStreamController:Rj,audioTrackController:Ij,emeController:_c,cmcdController:I7,contentSteeringController:O7,interstitialsController:K7});function O9(){return{cueHandler:S9,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 M9(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=zx(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const u=`${a==="level"?"playlist":a}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const p=`${a}Loading${f}`,y=e[p];if(y!==void 0&&c){d.push(p);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=y,v.maxTimeToFirstByteMs=y;break;case"MaxRetry":v.errorRetry.maxNumRetry=y,v.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":v.errorRetry.retryDelayMs=y,v.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=y,v.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${is(e[u])}`)}),Hi(Hi({},i),e)}function zx(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(zx):Object.keys(s).reduce((e,t)=>(e[t]=zx(s[t]),e),{}):s}function P9(s,e){const t=s.loader;t!==Pw&&t!==JL?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):E9()&&(s.loader=Pw,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Ym=2,B9=.1,F9=.05,U9=100;class j9 extends qD{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(G.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.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(U9),this.mediaSource=t.mediaSource;const i=this.media=t.media;In(i,"playing",this.onMediaPlaying),In(i,"waiting",this.onMediaWaiting),In(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Qn(i,"playing",this.onMediaPlaying),Qn(i,"waiting",this.onMediaWaiting),Qn(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 a=this.media;if(!a)return;const{seeking:u}=a,c=this.seeking&&!u,d=!this.seeking&&u,f=a.paused&&!u||a.ended||a.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&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(G.MEDIA_ENDED,{stalled:!1}));return}if(!ri.getBuffered(a).length){this.nudgeRetry=0;return}const p=ri.bufferInfo(a,e,0),y=p.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const B=Bw(this.hls.inFlightFragments,e),O=p.len>Ym,H=!y||B||y-e>Ym&&!v.getPartialFragment(e);if(O||H)return;this.moved=!1}const b=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(p.len>0)&&!y)return;const O=Math.max(y,p.start||0)-e,D=!!(b!=null&&b.live)?b.targetduration*2:Ym,M=Om(e,v);if(O>0&&(O<=D||M)){a.paused||this._trySkipBufferHole(M);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 R=E-I;if(!u&&(R>=_||L)&&this.hls){var $;if((($=this.mediaSource)==null?void 0:$.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-(b?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(G.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(p),!this.media||!this.hls)return}const P=ri.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(P,R,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(G.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=ri.bufferedInfo(ri.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=ri.timeRangesToArray(n),u=ri.bufferedInfo(a,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 y=Om(e,this.fragmentTracker);y&&"fragment"in y?y=y.fragment:y||(y=void 0);const v=ri.bufferInfo(this.media,e,0);this.hls.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,frag:y,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:a,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!a||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=Om(i,a);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,At.MAIN),a=i.getFragAtPos(n,At.MAIN);if(r&&a)return a.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 a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${is(e)})`);this.warn(a.message),t.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.BUFFER_STALLED_ERROR,fatal:!1,error:a,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 a=n.currentTime,u=ri.bufferInfo(n,a,0),c=a0&&u.len<1&&n.readyState<3,y=c-a;if(y>0&&(f||p)){if(y>r.maxBufferHole){let b=!1;if(a===0){const _=i.getAppendedFrag(0,At.MAIN);_&&c<_.end&&(b=!0)}if(!b&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Bw(this.hls.inFlightFragments,c))return 0;let E=!1,L=e.end;for(;L"u"))return self.VTTCue||self.TextTrackCue}function wv(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,is(n?Hi({type:n},i):i))}return r}const Mm=(()=>{const s=qx();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class H9{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(G.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(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.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&&uc(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;tMm&&(p=Mm),p-f<=0&&(p=f+$9);for(let v=0;vf.type===yr.audioId3&&c:n==="video"?d=f=>f.type===yr.emsg&&u:d=f=>f.type===yr.audioId3&&c||f.type===yr.emsg&&u,Gx(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:a}=this.hls.config;if(!r)return;const u=qx();if(i&&n&&!a){const{fragmentStart:_,fragmentEnd:E}=e;let L=this.assetCue;L?(L.startTime=_,L.endTime=E):u&&(L=this.assetCue=wv(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 p=this.dateRangeCuesAppended;if(c&&t){var y;if((y=c.cues)!=null&&y.length){const _=Object.keys(p).filter(E=>!f.includes(E));for(let E=_.length;E--;){var v;const L=_[E],I=(v=p[L])==null?void 0:v.cues;delete p[L],I&&Object.keys(I).forEach(R=>{const $=I[R];if($){$.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue($)}catch{}}})}}else p=this.dateRangeCuesAppended={}}const b=e.fragments[e.fragments.length-1];if(!(f.length===0||!xt(b?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(K!==L.id){const J=d[K];if(J.class===L.class&&J.startDate>L.startDate&&(!W||L.startDate.01&&(K.startTime=I,K.endTime=B);else if(u){let J=L.attr[W];cU(W)&&(J=AD(J));const se=wv(u,I,B,{key:W,data:J},yr.dateRange);se&&(se.id=E,this.id3Track.addCue(se),$[W]=se,a&&(W==="X-ASSET-LIST"||W==="X-ASSET-URL")&&se.addEventListener("enter",this.onEventCueEnter))}}p[E]={cues:$,dateRange:L,durationKnown:P}}}}}class G9{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:a}=this.config;if(!r||a===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,a)),y=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(p,Math.max(1,y));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:a,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:a*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,a=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,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(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.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===Le.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 V9 extends aT{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(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.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={},a={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const p=f.attrs;let{audioCodec:y,videoCodec:v}=f;y&&(f.audioCodec=y=wp(y,i)||void 0),v&&(v=f.videoCodec=A6(v));const{width:b,height:_,unknownCodecs:E}=f,L=E?.length||0;if(u||(u=!!(b&&_)),c||(c=!!v),d||(d=!!y),L||y&&!this.isAudioSupported(y)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${p.CODECS}"`);return}const{CODECS:I,"FRAME-RATE":R,"HDCP-LEVEL":$,"PATHWAY-ID":P,RESOLUTION:B,"VIDEO-RANGE":O}=p,D=`${`${P||"."}-`}${f.bitrate}-${B}-${R}-${I}-${O}-${$}`;if(r[D])if(r[D].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const M=a[D]+=1;f.attrs["PATHWAY-ID"]=new Array(M+1).join(".");const W=this.createLevel(f);r[D]=W,n.push(W)}else r[D].addGroupId("audio",p.AUDIO),r[D].addGroupId("text",p.SUBTITLES);else{const M=this.createLevel(f);r[D]=M,a[D]=1,n.push(M)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new Rh(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=FD(n,[])}return t}isAudioSupported(e){return Dh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Dh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var a;let u=[],c=[],d=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:I,videoRange:R,width:$,height:P})=>(!!I||!!($&&P))&&P6(R))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let I="no level with compatible codecs found in manifest",R=I;t.levels.length&&(R=`one or more CODECS in variant not supported: ${is(t.levels.map(P=>P.attrs.CODECS).filter((P,B,O)=>O.indexOf(P)===B))}`,this.warn(R),I+=` (${R})`);const $=new Error(I);this.hls.trigger(G.ERROR,{type:Pt.MEDIA_ERROR,details:Le.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:$,reason:R})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(I=>!I.audioCodec||this.isAudioSupported(I.audioCodec)),Uw(u)),t.subtitles&&(c=t.subtitles,Uw(c));const p=d.slice(0);d.sort((I,R)=>{if(I.attrs["HDCP-LEVEL"]!==R.attrs["HDCP-LEVEL"])return(I.attrs["HDCP-LEVEL"]||"")>(R.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&I.height!==R.height)return I.height-R.height;if(I.frameRate!==R.frameRate)return I.frameRate-R.frameRate;if(I.videoRange!==R.videoRange)return Ap.indexOf(I.videoRange)-Ap.indexOf(R.videoRange);if(I.videoCodec!==R.videoCodec){const $=L2(I.videoCodec),P=L2(R.videoCodec);if($!==P)return P-$}if(I.uri===R.uri&&I.codecSet!==R.codecSet){const $=Ep(I.codecSet),P=Ep(R.codecSet);if($!==P)return P-$}return I.averageBitrate!==R.averageBitrate?I.averageBitrate-R.averageBitrate:0});let y=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==p.length)){for(let I=0;I$&&$===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=P)}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(G.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"),p=e<0;if(this.hls.trigger(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.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,a=t[e],u=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(G.LEVEL_SWITCHING,c);const d=a.details;if(!d||d.live){const f=this.switchParams(a.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===yi.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===At.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,a=t.levelInfo;if(!a){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.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"],a=e.details,u=a?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(G.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,a)=>a!==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));rL(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(G.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(G.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Uw(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function eR(){return self.SourceBuffer||self.WebKitSourceBuffer}function tR(){if(!gl())return!1;const e=eR();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function z9(){if(!tR())return!1;const s=gl();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Lh(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Lh(e,"audio"))))}function q9(){var s;const e=eR();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const K9=100;class W9 extends Zb{constructor(e,t,i){super(e,t,i,"stream-controller",At.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||!xt(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(n,r,At.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(G.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(G.BUFFER_CREATED,this.onBufferCreated,this),e.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(G.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(G.BUFFER_CREATED,this.onBufferCreated,this),e.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.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(K9),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=Ve.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Ve.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ve.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=Ve.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Ve.IDLE;break}break}case Ve.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Ve.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 a=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(G.BUFFER_EOS,_),this.state=Ve.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=a.details;if(!d||this.state===Ve.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=Ve.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,p=this.getMaxBufferLength(a.maxBitrate);if(f>=p)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&Is(v)&&this.fragmentTracker.getState(v)!==Zs.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,y)){if(!v.gap){const E=this.audioOnly&&!this.altAudio?es.AUDIO:es.VIDEO,L=(E===es.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,E,At.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,At.MAIN,p)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,a,y))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===Zs.NOT_LOADED||n===Zs.PARTIAL?Is(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,At.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=a-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(G.AUDIO_TRACK_SWITCHED,t)}),i.trigger(G.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(G.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Cp(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,a=!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 a=!0}a&&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===At.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===Ve.PARSED&&(this.state=Ve.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),Is(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const a=this.media;a&&(!this._hasEnoughToStart&&ri.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=Ve.ERROR;return}switch(t.details){case Le.FRAG_GAP:case Le.FRAG_PARSING_ERROR:case Le.FRAG_DECRYPT_ERROR:case Le.FRAG_LOAD_ERROR:case Le.FRAG_LOAD_TIMEOUT:case Le.KEY_LOAD_ERROR:case Le.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(At.MAIN,t);break;case Le.LEVEL_LOAD_ERROR:case Le.LEVEL_LOAD_TIMEOUT:case Le.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ve.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===yi.LEVEL&&(this.state=Ve.IDLE);break;case Le.BUFFER_ADD_CODEC_ERROR:case Le.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Le.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 Le.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Ve.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==es.AUDIO||!this.altAudio){const i=(t===es.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,At.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=Ve.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(G.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===Ve.STOPPED||this.state===Ve.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=a,{video:f,text:p,id3:y,initSegment:v}=n,{details:b}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=Ve.PARSING,v){const E=v.tracks;if(E){const $=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,E,$,r),i.trigger(G.FRAG_PARSING_INIT_SEGMENT,{frag:$,id:t,tracks:E})}const L=v.initPTS,I=v.timescale,R=this.initPTS[u.cc];if(xt(L)&&(!R||R.baseTime!==L||R.timescale!==I)){const $=v.trackId;this.initPTS[u.cc]={baseTime:L,timescale:I,trackId:$},i.trigger(G.INIT_PTS_FOUND,{frag:u,id:t,initPTS:L,timescale:I,trackId:$})}}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:R,endPTS:$,startDTS:P,endDTS:B}=f;if(c)c.elementaryStreams[f.type]={startPTS:R,endPTS:$,startDTS:P,endDTS:B};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!I&&(this.couldBacktrack=!0),f.dropped&&f.independent){const O=this.getMainFwdBufferInfo(),H=(O?O.end:this.getLoadPosition())+this.config.maxBufferHole,D=f.firstKeyFramePTS?f.firstKeyFramePTS:R;if(!L&&HYm&&(u.gap=!0);u.setElementaryStreamInfo(f.type,R,$,P,B),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:R}=_;c&&(c.elementaryStreams[es.AUDIO]={startPTS:E,endPTS:L,startDTS:I,endDTS:R}),u.setElementaryStreamInfo(es.AUDIO,E,L,I,R),this.bufferFragmentData(_,u,c,r)}if(b&&y!=null&&y.samples.length){const E={id:t,frag:u,details:b,samples:y.samples};i.trigger(G.FRAG_PARSING_METADATA,E)}if(b&&p){const E={id:t,frag:u,details:b,samples:p.samples};i.trigger(G.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${Is(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==Ve.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=Hm(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 y=r.metadata;y&&"channelCount"in y&&(y.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=At.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=At.MAIN;const d=a.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.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(G.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const p=t[d].initSegment;p!=null&&p.byteLength&&this.hls.trigger(G.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,At.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=Ve.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ri.isBuffered(e,i)?t=this.getAppendedFrag(i):ri.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(G.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(G.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 xt(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(xt(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?du(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const a=r+(t-n.start)*1e3;return new Date(a)}}}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 Y9 extends Mr{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=Le.KEY_LOAD_ERROR,i,n,r){return new no({type:Pt.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;a.setKeyFormat(u);const c=Vm(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=lh(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,Le.KEY_LOAD_ERROR,d))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,Le.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const u=Av(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: "+dn(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,Le.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 a=m6(t.initSegment.data);if(a.length){let u=a[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${dn(u)}`),fl.setKeyIdForUri(e.decryptdata.uri,u)):(u=fl.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${dn(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!Is(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}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((a,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:(y,v,b,_)=>{const{frag:E,keyInfo:L}=b,I=Av(L.decryptdata);if(!E.decryptdata||L!==this.keyIdToKeyInfo[I])return u(this.createKeyLoadError(E,Le.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));L.decryptdata.key=E.decryptdata.key=new Uint8Array(y.data),E.keyLoader=null,L.loader=null,a({frag:E,keyInfo:L})},onError:(y,v,b,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Le.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),b,Hi({url:c.url,data:void 0},y)))},onTimeout:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Le.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Le.INTERNAL_ABORTED,new Error("key loading aborted"),b))}};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 a=Av(i.decryptdata)||n;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function Av(s){if(s.keyFormat!==hn.FAIRPLAY){const e=s.keyId;if(e)return dn(e)}return s.uri}function jw(s){const{type:e}=s;switch(e){case yi.AUDIO_TRACK:return At.AUDIO;case yi.SUBTITLE_TRACK:return At.SUBTITLE;default:return At.MAIN}}function Cv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class X9{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(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}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:yi.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:a,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:yi.LEVEL,url:a,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:yi.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:yi.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[yi.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[yi.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===yi.MANIFEST?r=i.manifestLoadPolicy.default:r=Qi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),xt((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===yi.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===yi.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===yi.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,p=d.targetduration;if(f&&p){const y=Math.max(f*3,p*.8)*1e3;r=Qi({},r,{maxTimeToFirstByteMs:Math.min(y,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(d,f,p,y)=>{const v=this.getInternalLoader(p);this.resetInternalLoader(p.type);const b=d.data;f.parsing.start=performance.now(),Ea.isMediaPlaylist(b)||p.type!==yi.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,p,y||null,v):this.handleMasterPlaylist(d,f,p,y)},onError:(d,f,p,y)=>{this.handleNetworkError(f,p,!1,d,y)},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,a=e.data,u=Cv(e,i),c=Ea.parseMasterPlaylist(a,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:y,startTimeOffset:v,variableList:b}=c;this.variableList=b,f.forEach(I=>{const{unknownCodecs:R}=I;if(R){const{preferManagedMediaSource:$}=this.hls.config;let{audioCodec:P,videoCodec:B}=I;for(let O=R.length;O--;){const H=R[O];Dh(H,"audio",$)?(I.audioCodec=P=P?`${P},${H}`:H,Bc.audio[P.substring(0,4)]=2,R.splice(O,1)):Dh(H,"video",$)&&(I.videoCodec=B=B?`${B},${H}`:H,Bc.video[B.substring(0,4)]=2,R.splice(O,1))}}});const{AUDIO:_=[],SUBTITLES:E,"CLOSED-CAPTIONS":L}=Ea.parseMasterPlaylistMedia(a,u,c);_.length&&!_.some(R=>!R.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 xs({}),bitrate:0,url:""})),r.trigger(G.MANIFEST_LOADED,{levels:f,audioTracks:_,subtitles:E,captions:L,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:p,sessionKeys:y,startTimeOffset:v,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:u,level:c,type:d}=i,f=Cv(e,i),p=xt(c)?c:xt(u)?u:0,y=jw(i),v=Ea.parseLevelPlaylist(e.data,f,p,y,0,this.variableList);if(d===yi.MANIFEST){const b={attrs:new xs({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+iL(v,0),a.trigger(G.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(G.ERROR,{type:Pt.NETWORK_ERROR,details:Le.MANIFEST_PARSING_ERROR,fatal:t.type===yi.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 a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===yi.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===yi.AUDIO_TRACK||e.type===yi.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=Le.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case yi.MANIFEST:c=i?Le.MANIFEST_LOAD_TIMEOUT:Le.MANIFEST_LOAD_ERROR,d=!0;break;case yi.LEVEL:c=i?Le.LEVEL_LOAD_TIMEOUT:Le.LEVEL_LOAD_ERROR,d=!1;break;case yi.AUDIO_TRACK:c=i?Le.AUDIO_TRACK_LOAD_TIMEOUT:Le.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case yi.SUBTITLE_TRACK:c=i?Le.SUBTITLE_TRACK_LOAD_TIMEOUT:Le.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const p={type:Pt.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const y=t?.url||e.url;p.response=Hi({url:y,data:void 0},n)}this.hls.trigger(G.ERROR,p)}handlePlaylistLoaded(e,t,i,n,r,a){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:p,groupId:y,deliveryDirectives:v}=n,b=Cv(t,n),_=jw(n);let E=typeof n.level=="number"&&_===At.MAIN?d:void 0;const L=e.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger(G.ERROR,{type:Pt.NETWORK_ERROR,details:Le.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(G.ERROR,{type:Pt.NETWORK_ERROR,details:Le.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&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case yi.MANIFEST:case yi.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(G.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:E||0,id:p||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===yi.MANIFEST});break;case yi.AUDIO_TRACK:u.trigger(G.AUDIO_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case yi.SUBTITLE_TRACK:u.trigger(G.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class vr{static get version(){return Ih}static isMSESupported(){return tR()}static isSupported(){return z9()}static getMediaSource(){return gl()}static get Events(){return G}static get MetadataSchema(){return yr}static get ErrorTypes(){return Pt}static get ErrorDetails(){return Le}static get DefaultConfig(){return vr.defaultConfig?vr.defaultConfig:N9}static set DefaultConfig(e){vr.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 Jb,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=i6(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=M9(vr.DefaultConfig,e,t);this.userConfig=e,i.progressive&&P9(i,t);const{abrController:n,bufferController:r,capLevelController:a,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),p=new Q6(this),y=i.interstitialsController,v=y?this.interstitialsController=new y(this,vr):null,b=this.bufferController=new r(this,p),_=this.capLevelController=new a(this),E=new c(this),L=new X9(this),I=i.contentSteeringController,R=I?new I(this):null,$=this.levelController=new V9(this,R),P=new H9(this),B=new Y9(this.config,this.logger),O=this.streamController=new W9(this,p,B),H=this.gapController=new j9(this,p);_.setStreamController(O),E.setStreamController(O);const D=[L,$,O];v&&D.splice(1,0,v),R&&D.splice(1,0,R),this.networkControllers=D;const M=[f,b,H,_,E,P,p];this.audioTrackController=this.createController(i.audioTrackController,D);const W=i.audioStreamController;W&&D.push(this.audioStreamController=new W(this,p,B)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const K=i.subtitleStreamController;K&&D.push(this.subtititleStreamController=new K(this,p,B)),this.createController(i.timelineController,M),B.emeController=this.emeController=this.createController(i.emeController,M),this.cmcdController=this.createController(i.cmcdController,M),this.latencyController=this.createController(G9,M),this.coreComponents=M,D.push(d);const J=d.onErrorOut;typeof J=="function"&&this.on(G.ERROR,J,d),this.on(G.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===G.ERROR;this.trigger(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.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(G.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(G.ERROR,{type:Pt.OTHER_ERROR,details:Le.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(G.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(G.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(G.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Hb.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(G.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={[At.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[At.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[At.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=j7()),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){M6(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 a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=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=$D(t);return UD(e,i,navigator.mediaCapabilities)}}vr.defaultConfig=void 0;function $w(s,e){const t=s.includes("?")?"&":"?";return`${s}${t}v=${e}`}function iR({src:s,muted:e=tp,className:t}){const i=w.useRef(null),[n,r]=w.useState(!1),[a,u]=w.useState(null),[c,d]=w.useState(1),f=w.useMemo(()=>$w(s,c),[s,c]);return w.useEffect(()=>{let p=!1,y=null,v=null,b=null;const _=i.current;if(!_)return;const E=_;r(!1),u(null),ip(E,{muted:e});const L=()=>{v&&window.clearTimeout(v),b&&window.clearInterval(b),v=null,b=null},I=()=>{p||(L(),d(B=>B+1))};async function R(){const B=Date.now();for(;!p&&Date.now()-B<9e4;){try{const O=$w(s,Date.now()),H=await fetch(O,{cache:"no-store"});if(H.status===403)return{ok:!1,reason:"private"};if(H.status===404)return{ok:!1,reason:"offline"};if(H.ok&&(await H.text()).includes("#EXTINF"))return{ok:!0}}catch{}await new Promise(O=>setTimeout(O,500))}return{ok:!1}}async function $(){const B=await R();if(!p){if(!B.ok){if(B.reason==="private"||B.reason==="offline"){u(B.reason),r(!0);return}window.setTimeout(()=>{p||I()},800);return}if(E.canPlayType("application/vnd.apple.mpegurl")){E.pause(),E.removeAttribute("src"),E.load(),E.src=f,E.load(),E.play().catch(()=>{});let O=Date.now(),H=-1;const D=()=>{E.currentTime>H+.01&&(H=E.currentTime,O=Date.now())},M=()=>{v||(v=window.setTimeout(()=>{v=null,!p&&Date.now()-O>3500&&I()},800))};return E.addEventListener("timeupdate",D),E.addEventListener("waiting",M),E.addEventListener("stalled",M),E.addEventListener("error",M),b=window.setInterval(()=>{p||!E.paused&&Date.now()-O>6e3&&I()},2e3),()=>{E.removeEventListener("timeupdate",D),E.removeEventListener("waiting",M),E.removeEventListener("stalled",M),E.removeEventListener("error",M)}}if(!vr.isSupported()){r(!0);return}y=new vr({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:8}),y.on(vr.Events.ERROR,(O,H)=>{if(y&&H.fatal){if(H.type===vr.ErrorTypes.NETWORK_ERROR){y.startLoad();return}if(H.type===vr.ErrorTypes.MEDIA_ERROR){y.recoverMediaError();return}I()}}),y.loadSource(f),y.attachMedia(E),y.on(vr.Events.MANIFEST_PARSED,()=>{E.play().catch(()=>{})})}}let P;return(async()=>{const B=await $();typeof B=="function"&&(P=B)})(),()=>{p=!0,L();try{P?.()}catch{}try{y?.destroy()}catch{}}},[s,e,f]),n?g.jsx("div",{className:"text-xs text-gray-400 italic",children:a==="private"?"Private":a==="offline"?"Offline":"–"}):g.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,preload:"auto",crossOrigin:"anonymous",onClick:()=>{const p=i.current;p&&(p.muted=!1,p.play().catch(()=>{}))}})}function Q9(){const s=De;if(s.__gearControlRegistered)return;s.__gearControlRegistered=!0;const e=De.getComponent("MenuButton"),t=De.getComponent("MenuItem");class i extends t{_onSelect;constructor(a,u){super(a,u),this._onSelect=u?.onSelect,this.on("click",()=>this._onSelect?.())}}class n extends e{constructor(a,u){super(a,u),this.controlText("Settings");const d=this.el().querySelector(".vjs-icon-placeholder");d&&(d.innerHTML=` - - `),this.player().on("gear:refresh",()=>this.update())}update(){try{super.update?.()}catch{}const a=this.player(),u=String(a.options_?.__gearQuality??"auto"),c=this.items||[];for(const d of c){const f=d?.options_?.__kind,p=d?.options_?.__value;f==="quality"&&d.selected?.(String(p)===u)}}createItems(){const a=this.player(),u=[],c=a.options_?.gearQualities||["auto","1080p","720p","480p"],d=String(a.options_?.__gearQuality??"auto");for(const f of c)u.push(new i(a,{label:f==="auto"?"Auto":f,selectable:!0,selected:d===f,__kind:"quality",__value:f,onSelect:()=>{a.options_.__gearQuality=f,a.trigger({type:"gear:quality",quality:f}),a.trigger("gear:refresh")}}));return u}}if(De.getComponent("Component"),De.registerComponent("GearMenuButton",n),!s.__gearControlCssInjected){s.__gearControlCssInjected=!0;const r=document.createElement("style");r.textContent=` - #player-root .vjs-gear-menu .vjs-icon-placeholder { - display: inline-flex; - align-items: center; - justify-content: center; - } - - /* ✅ Menübreite nicht aufblasen */ - #player-root .vjs-gear-menu .vjs-menu { - min-width: 0 !important; - width: fit-content !important; - } - - /* ✅ die UL auch nicht breit ziehen */ - #player-root .vjs-gear-menu .vjs-menu-content { - width: fit-content !important; - min-width: 0 !important; - padding: 2px 0 !important; - } - - /* ✅ Items kompakter */ - #player-root .vjs-gear-menu .vjs-menu-content .vjs-menu-item { - padding: 4px 10px !important; - line-height: 1.1 !important; - } - - /* ✅ Gear-Button als Anker */ - #player-root .vjs-gear-menu { - position: relative !important; - } - - /* ✅ Popup wirklich über dem Gear-Icon zentrieren */ - #player-root .vjs-gear-menu .vjs-menu { - position: absolute !important; - - left: 0% !important; - right: 0% !important; - - transform: translateX(-50%) !important; - transform-origin: 50% 100% !important; - - z-index: 9999 !important; - } - - /* ✅ Manche Skins setzen am UL noch Layout/Width – neutralisieren */ - #player-root .vjs-gear-menu .vjs-menu-content { - width: max-content !important; - min-width: 0 !important; - } - - /* ✅ Menü horizontal zentrieren über dem Gear-Icon */ - #player-root .vjs-gear-menu .vjs-menu { - z-index: 9999 !important; - } - `,document.head.appendChild(r)}}const pa=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",hT=s=>s.startsWith("HOT ")?s.slice(4):s,Z9=s=>(s||"").trim().toLowerCase(),J9=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n};function Hw(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 e$(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 Gw(s){if(!s)return"—";const e=s instanceof Date?s:new Date(s),t=e.getTime();return Number.isFinite(t)?e.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"—"}const kv=(...s)=>{for(const e of s){const t=typeof e=="string"?Number(e):e;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t}return null};function t$(s){if(!s||!Number.isFinite(s))return"—";const e=s>=10?0:2;return`${s.toFixed(e)} fps`}function i$(s,e){if(!s||!e)return"—";const t=Math.round(e);return`${s}×${e} (${t}p)`}function s$(s){const e=pa(s||""),t=hT(e);if(!t)return null;const n=t.replace(/\.[^.]+$/,"").match(/_(\d{1,2})_(\d{1,2})_(\d{4})__(\d{1,2})-(\d{2})-(\d{2})$/);if(!n)return null;const r=Number(n[1]),a=Number(n[2]),u=Number(n[3]),c=Number(n[4]),d=Number(n[5]),f=Number(n[6]);return[r,a,u,c,d,f].every(p=>Number.isFinite(p))?new Date(u,r-1,a,c,d,f):null}const n$=s=>{const e=pa(s||""),t=hT(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},r$=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 io(...s){return s.filter(Boolean).join(" ")}function a$(s){const[e,t]=w.useState(!1);return w.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 Dv(s,e=["1080p","720p","480p"]){const t=typeof s=="number"&&Number.isFinite(s)&&s>0?s:0,i=a=>{const u=String(a).match(/(\d{3,4})p/i);return u?Number(u[1]):0},r=["auto",...e.filter(a=>{const u=i(a);return u?t?u<=t+8:!0:!1}).sort((a,u)=>i(u)-i(a))];return Array.from(new Set(r))}function Lv(s){const e=typeof s=="number"&&Number.isFinite(s)&&s>0?Math.round(s):0;return e?e>=1e3?"1080p":e>=700?"720p":e>=460?"480p":`${e}p`:"auto"}function o$({job:s,expanded:e,onClose:t,onToggleExpand:i,modelKey:n,modelsByKey:r,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onKeep:f,onDelete:p,onToggleHot:y,onToggleFavorite:v,onToggleLike:b,onToggleWatch:_,onStopJob:E,startMuted:L=dO}){const I=w.useMemo(()=>pa(s.output?.trim()||"")||s.id,[s.output,s.id]),R=w.useMemo(()=>pa(s.output?.trim()||""),[s.output]),$=w.useMemo(()=>pa(s.output?.trim()||""),[s.output]),P=w.useMemo(()=>e$(r$(s)),[s]),B=s,O=s.status==="running",[H,D]=w.useState(!1),M=O&&H,W=w.useMemo(()=>($||"").replace(/\.[^.]+$/,""),[$]),K=w.useMemo(()=>O?s.id:W||s.id,[O,s.id,W]),J=R.startsWith("HOT "),ue=w.useMemo(()=>{const ce=(n||"").trim();return ce||n$(s.output)},[n,s.output]),se=w.useMemo(()=>hT(R),[R]),q=w.useMemo(()=>{const ce=Date.parse(String(s.startedAt||"")),Se=Date.parse(String(s.endedAt||""));if(Number.isFinite(ce)&&Number.isFinite(Se)&&Se>ce)return Hw(Se-ce);const rt=s.durationSeconds;return typeof rt=="number"&&Number.isFinite(rt)&&rt>0?Hw(rt*1e3):"—"},[s]),Y=w.useMemo(()=>{const ce=s$(s.output);if(ce)return Gw(ce);const Se=B.startedAt??B.endedAt??B.createdAt??B.fileCreatedAt??B.ctime??null,rt=Se?new Date(Se):null;return Gw(rt&&Number.isFinite(rt.getTime())?rt:null)},[s.output,B.startedAt,B.endedAt,B.createdAt,B.fileCreatedAt,B.ctime]),ie=w.useMemo(()=>Z9((n||ue||"").trim()),[n,ue]),Q=w.useMemo(()=>{const ce=r?.[ie];return J9(ce?.tags)},[r,ie]),oe=w.useMemo(()=>sc(`/api/record/preview?id=${encodeURIComponent(K)}&file=preview.jpg`),[K]),F=w.useMemo(()=>sc(`/api/record/preview?id=${encodeURIComponent(K)}&file=thumbs.jpg`),[K]),ee=w.useMemo(()=>sc(`/api/record/preview?id=${encodeURIComponent(K)}&play=1&file=index_hq.m3u8`),[K]),[he,be]=w.useState(oe);w.useEffect(()=>{be(oe)},[oe]);const pe=w.useMemo(()=>kv(B.videoWidth,B.width,B.meta?.width),[B.videoWidth,B.width,B.meta?.width]),Ce=w.useMemo(()=>kv(B.videoHeight,B.height,B.meta?.height),[B.videoHeight,B.height,B.meta?.height]),Re=w.useMemo(()=>kv(B.fps,B.frameRate,B.meta?.fps,B.meta?.frameRate),[B.fps,B.frameRate,B.meta?.fps,B.meta?.frameRate]),Ze=w.useMemo(()=>i$(pe,Ce),[pe,Ce]),Ge=w.useMemo(()=>t$(Re),[Re]);w.useEffect(()=>{const ce=Se=>Se.key==="Escape"&&t();return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[t]);const it=w.useMemo(()=>{const ce=`/api/record/preview?id=${encodeURIComponent(K)}&file=index_hq.m3u8&play=1`;return sc(O?`${ce}&t=${Date.now()}`:ce)},[K,O]);w.useEffect(()=>{if(!O){D(!1);return}let ce=!0;const Se=new AbortController;return D(!1),(async()=>{for(let wt=0;wt<120&&ce&&!Se.signal.aborted;wt++){try{const Rt=await K8(it,{method:"GET",cache:"no-store",signal:Se.signal,headers:{"cache-control":"no-cache"}});if(Rt.ok){const Yt=await Rt.text(),zt=Yt.includes("#EXTM3U"),ni=/#EXTINF:/i.test(Yt)||/\.ts(\?|$)/i.test(Yt)||/\.m4s(\?|$)/i.test(Yt);if(zt&&ni){ce&&D(!0);return}}}catch{}await new Promise(Rt=>setTimeout(Rt,500))}})(),()=>{ce=!1,Se.abort()}},[O,it]);const dt=w.useCallback(ce=>{const Se=String(ce.quality||"auto"),rt=new URLSearchParams;return ce.file&&rt.set("file",ce.file),ce.id&&rt.set("id",ce.id),Se&&Se!=="auto"&&(rt.set("quality",Se),rt.set("stream","1")),sc(`/api/record/video?${rt.toString()}`)},[]),[ot,nt]=w.useState("auto"),ft=w.useMemo(()=>{if(O)return{src:"",type:""};const ce=pa(s.output?.trim()||"");if(ce){const Se=ce.toLowerCase().split(".").pop(),rt=Se==="mp4"?"video/mp4":Se==="ts"?"video/mp2t":"application/octet-stream";return{src:dt({file:ce,quality:ot}),type:rt}}return{src:dt({id:s.id,quality:ot}),type:"video/mp4"}},[O,s.output,s.id,ot,dt]),gt=w.useRef(null),je=w.useRef(null),bt=w.useRef(null),[vt,jt]=w.useState(!1),[We,ut]=w.useState(0),ge=w.useMemo(()=>pa(s.output?.trim()||"")||s.id,[s.output,s.id]),Je=w.useMemo(()=>Dv(Ce,["1080p","720p","480p"]),[Ce]),Ye=w.useMemo(()=>{const ce=Lv(Ce);return Je.includes(ce)?ce:"auto"},[Je,Ce]),Qe=w.useRef("");w.useEffect(()=>{Qe.current!==ge&&(Qe.current=ge,nt(Ye))},[ge,Ye]);const[,mt]=w.useState(0);w.useEffect(()=>{if(typeof window>"u")return;const ce=window.visualViewport;if(!ce)return;const Se=()=>mt(rt=>rt+1);return Se(),ce.addEventListener("resize",Se),ce.addEventListener("scroll",Se),window.addEventListener("resize",Se),window.addEventListener("orientationchange",Se),()=>{ce.removeEventListener("resize",Se),ce.removeEventListener("scroll",Se),window.removeEventListener("resize",Se),window.removeEventListener("orientationchange",Se)}},[]);const[ct,et]=w.useState(56),[Gt,Jt]=w.useState(null),It=!e,Ft=a$("(min-width: 640px)"),$t=It&&Ft,Ke="player_window_v1",Lt=420,Qt=280,Ut=12,ci=320,vi=200;w.useEffect(()=>{if(!vt)return;const ce=je.current;if(!ce||ce.isDisposed?.())return;const Se=ce.el();if(!Se)return;const rt=Se.querySelector(".vjs-control-bar");if(!rt)return;const wt=()=>{const Yt=Math.round(rt.getBoundingClientRect().height||0);Yt>0&&et(Yt)};wt();let Rt=null;return typeof ResizeObserver<"u"&&(Rt=new ResizeObserver(wt),Rt.observe(rt)),window.addEventListener("resize",wt),()=>{window.removeEventListener("resize",wt),Rt?.disconnect()}},[vt,e]),w.useEffect(()=>{const ce=je.current;if(!ce||ce.isDisposed?.())return;const Se=rt=>{const wt=String(rt?.quality??"auto");if(O)return;const Rt=pa(s.output?.trim()||"");if(!Rt)return;const Yt=ce.currentTime?.()||0,zt=ce.paused?.()??!1;nt(wt);const ni=dt({file:Rt,quality:wt});try{ce.src({src:ni,type:"video/mp4"})}catch{}ce.one("loadedmetadata",()=>{console.log("[Player] loadedmetadata after switch",{h:typeof ce.videoHeight=="function"?ce.videoHeight():null,w:typeof ce.videoWidth=="function"?ce.videoWidth():null});try{Yt>0&&ce.currentTime(Yt)}catch{}if(!zt){const vs=ce.play?.();vs&&typeof vs.catch=="function"&&vs.catch(()=>{})}})};return ce.on("gear:quality",Se),()=>{try{ce.off("gear:quality",Se)}catch{}}},[We,s.output,O,dt]),w.useEffect(()=>jt(!0),[]),w.useEffect(()=>{let ce=document.getElementById("player-root");ce||(ce=document.createElement("div"),ce.id="player-root");let Se=null;if(Ft){const rt=Array.from(document.querySelectorAll("dialog[open]"));Se=rt.length?rt[rt.length-1]:null}Se=Se??document.body,Se.appendChild(ce),ce.style.position="relative",ce.style.zIndex="2147483647",Jt(ce)},[Ft]),w.useEffect(()=>{const ce=je.current;if(!ce||ce.isDisposed?.()||!M||!ft.src)return;const Se=()=>{try{const Yt=ce.liveTracker;if(Yt&&typeof Yt.seekToLiveEdge=="function"){Yt.seekToLiveEdge();return}const zt=Yt?.liveCurrentTime?.();typeof zt=="number"&&Number.isFinite(zt)&&zt>0&&ce.currentTime(Math.max(0,zt-.2))}catch{}},rt=()=>Se();ce.on("loadedmetadata",rt);const wt=()=>Se();ce.on("playing",wt);const Rt=window.setInterval(()=>{try{if(ce.paused()||ce.seeking?.())return;const zt=ce.liveTracker?.liveCurrentTime?.();if(typeof zt!="number"||!Number.isFinite(zt))return;const ni=ce.currentTime()||0;zt-ni>4&&ce.currentTime(Math.max(0,zt-.2))}catch{}},1500);return Se(),()=>{try{ce.off("loadedmetadata",rt)}catch{}try{ce.off("playing",wt)}catch{}window.clearInterval(Rt)}},[M,ft.src,ft.type]),w.useEffect(()=>{const ce=je.current;if(!ce||ce.isDisposed?.()||!O||!H)return;let Se=-1,rt=Date.now();const wt=window.setInterval(()=>{try{if(ce.paused())return;const Rt=ce.currentTime()||0;if(Rt<=Se+.01){if(Date.now()-rt>4e3){const zt=ce.liveTracker;zt?.seekToLiveEdge?zt.seekToLiveEdge():ce.currentTime(Math.max(0,Rt+.5)),rt=Date.now()}}else Se=Rt,rt=Date.now()}catch{}},1e3);return()=>window.clearInterval(wt)},[O,H]),w.useLayoutEffect(()=>{if(!vt||!gt.current||je.current||O)return;const ce=document.createElement("video");ce.className="video-js vjs-big-play-centered w-full h-full",ce.setAttribute("playsinline","true"),gt.current.appendChild(ce),bt.current=ce,Q9();const Se=Dv(Ce,["1080p","720p","480p"]),rt=Lv(Ce),wt=Se.includes(rt)?rt:"auto";nt(wt);const Rt=De(ce,{autoplay:!0,muted:L,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,liveui:!1,html5:{vhs:{lowLatencyMode:!0}},inactivityTimeout:0,gearQualities:Se,__gearQuality:wt,controlBar:{skipButtons:{backward:10,forward:10},volumePanel:{inline:!1},children:["skipBackward","playToggle","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","spacer","playbackRateMenuButton","GearMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});je.current=Rt,ut(Yt=>Yt+1),Rt.one("loadedmetadata",()=>{try{const Yt=typeof Rt.videoHeight=="function"?Rt.videoHeight():0,zt=Dv(Yt,["1080p","720p","480p"]);Rt.options_.gearQualities=zt;const ni=Lv(Yt);Rt.options_.__gearQuality=zt.includes(ni)?ni:"auto",Rt.trigger("gear:refresh")}catch{}});try{const Yt=Rt.getChild("controlBar")?.getChild("GearMenuButton");Yt?.el&&Yt.el().classList.add("vjs-gear-menu")}catch{}return Rt.userActive(!0),Rt.on("userinactive",()=>Rt.userActive(!0)),()=>{try{je.current&&(je.current.dispose(),je.current=null)}finally{bt.current&&(bt.current.remove(),bt.current=null)}}},[vt,L,O,Ce]),w.useEffect(()=>{const ce=je.current;if(!ce||ce.isDisposed?.())return;const Se=ce.el();Se&&Se.classList.toggle("is-live-download",!!M)},[M]),w.useEffect(()=>{if(!vt)return;const ce=je.current;if(!ce||ce.isDisposed?.())return;const Se=ce.currentTime()||0;if(ce.muted(L),!ft.src){try{ce.pause(),ce.reset?.(),ce.error(null)}catch{}return}ce.src({src:ft.src,type:ft.type});const rt=()=>{const wt=ce.play?.();wt&&typeof wt.catch=="function"&&wt.catch(()=>{})};ce.one("loadedmetadata",()=>{if(ce.isDisposed?.())return;try{ce.playbackRate(1)}catch{}const wt=/mpegurl/i.test(ft.type);Se>0&&!wt&&ce.currentTime(Se),rt()}),rt()},[vt,ft.src,ft.type,L]),w.useEffect(()=>{if(!vt)return;const ce=je.current;if(!ce||ce.isDisposed?.())return;const Se=()=>{s.status==="running"&&D(!1)};return ce.on("error",Se),()=>{try{ce.off("error",Se)}catch{}}},[vt,s.status]),w.useEffect(()=>{const ce=je.current;!ce||ce.isDisposed?.()||queueMicrotask(()=>ce.trigger("resize"))},[e]);const ei=w.useCallback(()=>{const ce=je.current;if(!(!ce||ce.isDisposed?.())){try{ce.pause(),ce.reset?.()}catch{}try{ce.src({src:"",type:"video/mp4"}),ce.load?.()}catch{}}},[]);w.useEffect(()=>{const ce=Se=>{const wt=(Se.detail?.file??"").trim();if(!wt)return;const Rt=pa(s.output?.trim()||"");Rt&&Rt===wt&&ei()};return window.addEventListener("player:release",ce),()=>window.removeEventListener("player:release",ce)},[s.output,ei]),w.useEffect(()=>{const ce=Se=>{const wt=(Se.detail?.file??"").trim();if(!wt)return;const Rt=pa(s.output?.trim()||"");Rt&&Rt===wt&&(ei(),t())};return window.addEventListener("player:close",ce),()=>window.removeEventListener("player:close",ce)},[s.output,ei,t]);const Bi=()=>{if(typeof window>"u")return{w:0,h:0,ox:0,oy:0,bottomInset:0};const ce=window.visualViewport;if(ce&&Number.isFinite(ce.width)&&Number.isFinite(ce.height)){const Rt=Math.floor(ce.width),Yt=Math.floor(ce.height),zt=Math.floor(ce.offsetLeft||0),ni=Math.floor(ce.offsetTop||0),vs=Math.max(0,Math.floor(window.innerHeight-(ce.height+ce.offsetTop)));return{w:Rt,h:Yt,ox:zt,oy:ni,bottomInset:vs}}const Se=document.documentElement,rt=Se?.clientWidth||window.innerWidth,wt=Se?.clientHeight||window.innerHeight;return{w:rt,h:wt,ox:0,oy:0,bottomInset:0}},yt=w.useCallback((ce,Se)=>{if(typeof window>"u")return ce;const{w:rt,h:wt}=Bi(),Rt=rt-Ut*2,Yt=wt-Ut*2;let zt=ce.w,ni=ce.h;Se&&Number.isFinite(Se)&&Se>.1?(zt=Math.max(ci,zt),ni=zt/Se,niRt&&(zt=Rt,ni=zt/Se),ni>Yt&&(ni=Yt,zt=ni*Se)):(zt=Math.max(ci,Math.min(zt,Rt)),ni=Math.max(vi,Math.min(ni,Yt)));const vs=Math.max(Ut,Math.min(ce.x,rt-zt-Ut)),us=Math.max(Ut,Math.min(ce.y,wt-ni-Ut));return{x:vs,y:us,w:zt,h:ni}},[]),z=w.useCallback(()=>{if(typeof window>"u")return{x:Ut,y:Ut,w:Lt,h:Qt};try{const zt=window.localStorage.getItem(Ke);if(zt){const ni=JSON.parse(zt);if(typeof ni.x=="number"&&typeof ni.y=="number"&&typeof ni.w=="number"&&typeof ni.h=="number"){const vs=ni.w,us=ni.h,Ks=ni.x,Nn=ni.y;return yt({x:Ks,y:Nn,w:vs,h:us},vs/us)}}}catch{}const{w:ce,h:Se}=Bi(),rt=Lt,wt=Qt,Rt=Math.max(Ut,ce-rt-Ut),Yt=Math.max(Ut,Se-wt-Ut);return yt({x:Rt,y:Yt,w:rt,h:wt},rt/wt)},[yt]),[V,te]=w.useState(()=>z()),_e=$t&&V.w<380,Oe=w.useCallback(ce=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ke,JSON.stringify(ce))}catch{}},[]),tt=w.useRef(V);w.useEffect(()=>{tt.current=V},[V]),w.useEffect(()=>{$t&&te(z())},[$t,z]),w.useEffect(()=>{if(!$t)return;const ce=()=>te(Se=>yt(Se,Se.w/Se.h));return window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce)},[$t,yt]);const Ot=w.useRef(null);w.useEffect(()=>{const ce=je.current;if(!(!ce||ce.isDisposed?.()))return Ot.current!=null&&cancelAnimationFrame(Ot.current),Ot.current=requestAnimationFrame(()=>{Ot.current=null;try{ce.trigger("resize")}catch{}}),()=>{Ot.current!=null&&(cancelAnimationFrame(Ot.current),Ot.current=null)}},[$t,V.w,V.h]);const[xi,Vi]=w.useState(!1),[zi,Oi]=w.useState(!1),Ai=w.useRef(null),Ci=w.useRef(null),Fi=w.useRef(null),Mi=w.useCallback(ce=>{const{w:Se,h:rt}=Bi(),wt=Ut,Rt=Se-ce.w-Ut,Yt=rt-ce.h-Ut,ni=ce.x+ce.w/2{const Se=Fi.current;if(!Se)return;const rt=ce.clientX-Se.sx,wt=ce.clientY-Se.sy,Rt=Se.start,Yt=yt({x:Rt.x+rt,y:Rt.y+wt,w:Rt.w,h:Rt.h});Ci.current={x:Yt.x,y:Yt.y},Ai.current==null&&(Ai.current=requestAnimationFrame(()=>{Ai.current=null;const zt=Ci.current;zt&&te(ni=>({...ni,x:zt.x,y:zt.y}))}))},[yt]),oi=w.useCallback(()=>{Fi.current&&(Oi(!1),Ai.current!=null&&(cancelAnimationFrame(Ai.current),Ai.current=null),Fi.current=null,window.removeEventListener("pointermove",Li),window.removeEventListener("pointerup",oi),te(ce=>{const Se=Mi(yt(ce));return queueMicrotask(()=>Oe(Se)),Se}))},[Li,Mi,yt,Oe]),ti=w.useCallback(ce=>{if(!$t||xi||ce.button!==0)return;ce.preventDefault(),ce.stopPropagation();const Se=tt.current;Fi.current={sx:ce.clientX,sy:ce.clientY,start:Se},Oi(!0),window.addEventListener("pointermove",Li),window.addEventListener("pointerup",oi)},[$t,xi,Li,oi]),Kt=w.useRef(null),Gs=w.useRef(null),qi=w.useRef(null),fn=w.useCallback(ce=>{const Se=qi.current;if(!Se)return;const rt=ce.clientX-Se.sx,wt=ce.clientY-Se.sy,Rt=Se.ratio,Yt=Se.dir.includes("w"),zt=Se.dir.includes("e"),ni=Se.dir.includes("n"),vs=Se.dir.includes("s");let us=Se.start.w,Ks=Se.start.h,Nn=Se.start.x,ir=Se.start.y;const{w:Pr,h:fu}=Bi(),Oa=24,mu=Se.start.x+Se.start.w,_r=Se.start.y+Se.start.h,pn=Math.abs(Pr-Ut-mu)<=Oa,go=Math.abs(fu-Ut-_r)<=Oa,Qr=hs=>{hs=Math.max(ci,hs);let cs=hs/Rt;return cs{hs=Math.max(vi,hs);let cs=hs*Rt;return cs=Math.abs(wt)){const cs=zt?Se.start.w+rt:Se.start.w-rt,{newW:On,newH:yo}=Qr(cs);us=On,Ks=yo}else{const cs=vs?Se.start.h+wt:Se.start.h-wt,{newW:On,newH:yo}=sr(cs);us=On,Ks=yo}Yt&&(Nn=Se.start.x+(Se.start.w-us)),ni&&(ir=Se.start.y+(Se.start.h-Ks))}else if(zt||Yt){const hs=zt?Se.start.w+rt:Se.start.w-rt,{newW:cs,newH:On}=Qr(hs);us=cs,Ks=On,Yt&&(Nn=Se.start.x+(Se.start.w-us)),ir=go?Se.start.y+(Se.start.h-Ks):Se.start.y}else if(ni||vs){const hs=vs?Se.start.h+wt:Se.start.h-wt,{newW:cs,newH:On}=sr(hs);us=cs,Ks=On,ni&&(ir=Se.start.y+(Se.start.h-Ks)),pn?Nn=Se.start.x+(Se.start.w-us):Nn=Se.start.x}const Ma=yt({x:Nn,y:ir,w:us,h:Ks},Rt);Gs.current=Ma,Kt.current==null&&(Kt.current=requestAnimationFrame(()=>{Kt.current=null;const hs=Gs.current;hs&&te(hs)}))},[yt]),tr=w.useCallback(()=>{qi.current&&(Vi(!1),Kt.current!=null&&(cancelAnimationFrame(Kt.current),Kt.current=null),qi.current=null,window.removeEventListener("pointermove",fn),window.removeEventListener("pointerup",tr),Oe(tt.current))},[fn,Oe]),ss=w.useCallback(ce=>Se=>{if(!$t||Se.button!==0)return;Se.preventDefault(),Se.stopPropagation();const rt=tt.current;qi.current={dir:ce,sx:Se.clientX,sy:Se.clientY,start:rt,ratio:rt.w/rt.h},Vi(!0),window.addEventListener("pointermove",fn),window.addEventListener("pointerup",tr)},[$t,fn,tr]),[bi,ks]=w.useState(!1),[Os,Vs]=w.useState(!1);w.useEffect(()=>{const ce=window.matchMedia?.("(hover: hover) and (pointer: fine)"),Se=()=>ks(!!ce?.matches);return Se(),ce?.addEventListener?.("change",Se),()=>ce?.removeEventListener?.("change",Se)},[]);const zs=$t&&(Os||zi||xi),[ki,qs]=w.useState(!1);if(w.useEffect(()=>{s.status!=="running"&&qs(!1)},[s.id,s.status]),!vt||!Gt)return null;const ls="inline-flex items-center justify-center rounded-md p-2 transition bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 active:scale-[0.98] dark:bg-black/45 dark:text-white dark:ring-white/10 dark:hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",Di=String(s.phase??"").toLowerCase(),Ms=Di==="stopping"||Di==="remuxing"||Di==="moving",mn=!E||!O||Ms||ki,rs=g.jsx("div",{className:"flex items-center gap-1 min-w-0",children:O?g.jsxs(g.Fragment,{children:[g.jsx(Zt,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:mn,title:Ms||ki?"Stoppe…":"Stop","aria-label":Ms||ki?"Stoppe…":"Stop",onClick:async ce=>{if(ce.preventDefault(),ce.stopPropagation(),!mn)try{qs(!0),await E?.(s.id)}finally{qs(!1)}},className:io("shadow-none shrink-0",_e&&"px-2"),children:g.jsx("span",{className:"whitespace-nowrap",children:Ms||ki?"Stoppe…":_e?"Stop":"Stoppen"})}),g.jsx(Aa,{job:s,variant:"overlay",collapseToMenu:!0,busy:Ms||ki,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?ce=>_(ce):void 0,onToggleFavorite:v?ce=>v(ce):void 0,onToggleLike:b?ce=>b(ce):void 0,order:["watch","favorite","like","details"],className:"gap-1 min-w-0 flex-1"})]}):g.jsx(Aa,{job:s,variant:"overlay",collapseToMenu:!0,isHot:a||J,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?ce=>_(ce):void 0,onToggleFavorite:v?ce=>v(ce):void 0,onToggleLike:b?ce=>b(ce):void 0,onToggleHot:y?async ce=>{ei(),await new Promise(rt=>setTimeout(rt,150)),await y(ce),await new Promise(rt=>setTimeout(rt,0));const Se=je.current;if(Se&&!Se.isDisposed?.()){const rt=Se.play?.();rt&&typeof rt.catch=="function"&&rt.catch(()=>{})}}:void 0,onKeep:f?async ce=>{ei(),t(),await new Promise(Se=>setTimeout(Se,150)),await f(ce)}:void 0,onDelete:p?async ce=>{ei(),t(),await new Promise(Se=>setTimeout(Se,150)),await p(ce)}:void 0,order:["watch","favorite","like","hot","keep","delete","details"],className:"gap-1 min-w-0 flex-1"})}),ye=e||$t,X="env(safe-area-inset-bottom)",ae=`calc(${ct}px + env(safe-area-inset-bottom))`,re=O?X:ae,xe=O?"calc(8px + env(safe-area-inset-bottom))":`calc(${ct+8}px + env(safe-area-inset-bottom))`,we=$t?"top-4":"top-2",He=e&&Ft,st=g.jsx("div",{className:io("relative overflow-visible",e||$t?"flex-1 min-h-0":"aspect-video"),onMouseEnter:()=>{!$t||!bi||Vs(!0)},onMouseLeave:()=>{!$t||!bi||Vs(!1)},children:g.jsxs("div",{className:io("relative w-full h-full",$t&&"vjs-mini"),children:[O?g.jsxs("div",{className:"absolute inset-0 bg-black",children:[g.jsx(iR,{src:ee,muted:L,className:"w-full h-full object-contain"}),g.jsxs("div",{className:"absolute right-2 bottom-2 z-[60] pointer-events-none 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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]})]}):g.jsx("div",{ref:gt,className:"absolute inset-0"}),g.jsx("div",{className:io("absolute inset-x-2 z-30",we),children:g.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-2",children:[g.jsx("div",{className:"min-w-0 pointer-events-auto overflow-visible",children:He?null:rs}),$t?g.jsxs("button",{type:"button","aria-label":"Player-Fenster verschieben",title:"Ziehen zum Verschieben",onPointerDown:ti,onClick:ce=>{ce.preventDefault(),ce.stopPropagation()},className:io(ls,"px-3 gap-1 cursor-grab active:cursor-grabbing select-none",zs?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none -translate-y-1",zi&&"scale-[0.98] opacity-90"),children:[g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"})]}):null,g.jsxs("div",{className:"shrink-0 flex items-center gap-1 pointer-events-auto",children:[g.jsx("button",{type:"button",className:ls,onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?g.jsx(xO,{className:"h-5 w-5"}):g.jsx(TO,{className:"h-5 w-5"})}),g.jsx("button",{type:"button",className:ls,onClick:t,"aria-label":"Schließen",title:"Schließen",children:g.jsx(ib,{className:"h-5 w-5"})})]})]})}),g.jsx("div",{className:io("player-ui pointer-events-none absolute inset-x-0 z-40","bg-gradient-to-t from-black/70 to-transparent","transition-all duration-200 ease-out",e?"h-28":"h-24"),style:{bottom:re}}),g.jsxs("div",{className:io("player-ui pointer-events-none absolute inset-x-2 z-50","flex items-end justify-between gap-2","transition-all duration-200 ease-out"),style:{bottom:xe},children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white",children:ue}),g.jsx("div",{className:"truncate text-[11px] text-white/80",children:se||I})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[!O&&g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-semibold",children:s.status}),a||J?g.jsx("span",{className:"rounded bg-amber-500/25 px-1.5 py-0.5 font-semibold text-white",children:"HOT"}):null,!O&&g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:q}),P!=="—"?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:P}):null]})]})]})}),Xe=g.jsx("div",{className:"w-[360px] shrink-0 border-r border-white/10 bg-black/40 text-white",children:g.jsxs("div",{className:"h-full p-4 flex flex-col gap-3 overflow-y-auto",children:[g.jsx("div",{className:"rounded-lg overflow-hidden ring-1 ring-white/10 bg-black/30",children:g.jsx("div",{className:"relative aspect-video",children:g.jsx("img",{src:he,alt:"Vorschau",className:"absolute inset-0 h-full w-full object-cover",loading:"lazy",onError:()=>{he!==F&&be(F)}})})}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("div",{className:"text-lg font-semibold truncate",children:ue}),g.jsx("div",{className:"text-xs text-white/70 break-all",children:se||I})]}),g.jsx("div",{className:"pointer-events-auto",children:g.jsxs("div",{className:"flex items-center justify-center gap-2 flex-wrap",children:[O?g.jsx(Zt,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:mn,title:Ms||ki?"Stoppe…":"Stop","aria-label":Ms||ki?"Stoppe…":"Stop",onClick:async ce=>{if(ce.preventDefault(),ce.stopPropagation(),!mn)try{qs(!0),await E?.(s.id)}finally{qs(!1)}},className:"shadow-none",children:Ms||ki?"Stoppe…":"Stoppen"}):null,g.jsx(Aa,{job:s,variant:"table",collapseToMenu:!1,busy:Ms||ki,isHot:a||J,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?ce=>_(ce):void 0,onToggleFavorite:v?ce=>v(ce):void 0,onToggleLike:b?ce=>b(ce):void 0,onToggleHot:y?async ce=>{ei(),await new Promise(rt=>setTimeout(rt,150)),await y(ce),await new Promise(rt=>setTimeout(rt,0));const Se=je.current;if(Se&&!Se.isDisposed?.()){const rt=Se.play?.();rt&&typeof rt.catch=="function"&&rt.catch(()=>{})}}:void 0,onKeep:f?async ce=>{ei(),t(),await new Promise(Se=>setTimeout(Se,150)),await f(ce)}:void 0,onDelete:p?async ce=>{ei(),t(),await new Promise(Se=>setTimeout(Se,150)),await p(ce)}:void 0,order:O?["watch","favorite","like","details"]:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-start gap-1"})]})}),g.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-2 text-sm",children:[g.jsx("div",{className:"text-white/60",children:"Status"}),g.jsx("div",{className:"font-medium",children:s.status}),g.jsx("div",{className:"text-white/60",children:"Auflösung"}),g.jsx("div",{className:"font-medium",children:Ze}),g.jsx("div",{className:"text-white/60",children:"FPS"}),g.jsx("div",{className:"font-medium",children:Ge}),g.jsx("div",{className:"text-white/60",children:"Laufzeit"}),g.jsx("div",{className:"font-medium",children:q}),g.jsx("div",{className:"text-white/60",children:"Größe"}),g.jsx("div",{className:"font-medium",children:P}),g.jsx("div",{className:"text-white/60",children:"Datum"}),g.jsx("div",{className:"font-medium",children:Y}),g.jsx("div",{className:"col-span-2",children:Q.length?g.jsx("div",{className:"flex flex-wrap gap-1.5",children:Q.map(ce=>g.jsx("span",{className:"rounded bg-white/10 px-2 py-0.5 text-xs text-white/90",children:ce},ce))}):g.jsx("span",{className:"text-white/50",children:"—"})})]})]})}),kt=g.jsx(Ca,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:io("relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10","w-full",ye?"h-full":"h-[220px] max-h-[40vh]",e?"rounded-2xl":$t?"rounded-lg":"rounded-none"),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:g.jsxs("div",{className:"flex flex-1 min-h-0",children:[He?Xe:null,st]})}),{w:Tt,h:Bt,ox:lt,oy:pt,bottomInset:Et}=Bi(),Nt={left:lt+16,top:pt+16,width:Math.max(0,Tt-32),height:Math.max(0,Bt-32)},Dt=e?Nt:$t?{left:V.x,top:V.y,width:V.w,height:V.h}:void 0;return Ec.createPortal(g.jsxs(g.Fragment,{children:[g.jsx("style",{children:` - /* Live-Download: Progress/Seek-Bar ausblenden */ - .is-live-download .vjs-progress-control { - display: none !important; - } - `}),e||$t?g.jsxs("div",{className:io("fixed z-[2147483647]",!xi&&!zi&&"transition-[left,top,width,height] duration-300 ease-[cubic-bezier(.2,.9,.2,1)]"),style:{...Dt,willChange:xi?"left, top, width, height":void 0},children:[kt,$t?g.jsxs("div",{className:"pointer-events-none absolute inset-0",children:[g.jsx("div",{className:"pointer-events-auto absolute -left-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:ss("w")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:ss("e")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -top-1 h-3 cursor-ns-resize",onPointerDown:ss("n")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -bottom-1 h-3 cursor-ns-resize",onPointerDown:ss("s")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -top-1 h-4 w-4 cursor-nwse-resize",onPointerDown:ss("nw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -top-1 h-4 w-4 cursor-nesw-resize",onPointerDown:ss("ne")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -bottom-1 h-4 w-4 cursor-nesw-resize",onPointerDown:ss("sw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -bottom-1 h-4 w-4 cursor-nwse-resize",onPointerDown:ss("se")})]}):null]}):g.jsx("div",{className:` - fixed z-[2147483647] inset-x-0 w-full - shadow-2xl - md:bottom-4 md:left-1/2 md:right-auto md:inset-x-auto md:w-[min(760px,calc(100vw-32px))] md:-translate-x-1/2 - `,style:{bottom:`calc(${Et}px + env(safe-area-inset-bottom))`},children:kt})]}),Gt)}function sR({jobId:s,thumbTick:e,autoTickMs:t=1e4,blur:i=!1,alignStartAt:n,alignEndAt:r=null,alignEveryMs:a,fastRetryMs:u,fastRetryMax:c,fastRetryWindowMs:d,className:f}){const[p,y]=w.useState(()=>typeof document>"u"?!0:!document.hidden),v=i?"blur-md":"",[b,_]=w.useState(0),[E,L]=w.useState(!1),I=w.useRef(null),[R,$]=w.useState(!1),P=w.useRef(null),B=w.useRef(0),O=w.useRef(!1),H=w.useRef(!1),D=J=>{if(typeof J=="number"&&Number.isFinite(J))return J;if(J instanceof Date)return J.getTime();const ue=Date.parse(String(J??""));return Number.isFinite(ue)?ue:NaN};w.useEffect(()=>{const J=()=>y(!document.hidden);return document.addEventListener("visibilitychange",J),()=>document.removeEventListener("visibilitychange",J)},[]),w.useEffect(()=>()=>{P.current&&window.clearTimeout(P.current)},[]),w.useEffect(()=>{typeof e!="number"&&(!R||!p||H.current||(H.current=!0,_(J=>J+1)))},[R,e,p]),w.useEffect(()=>{if(typeof e=="number"||!R||!p)return;const J=Number(a??t??1e4);if(!Number.isFinite(J)||J<=0)return;const ue=n?D(n):NaN,se=r?D(r):NaN;if(Number.isFinite(ue)){let Y;const ie=()=>{const Q=Date.now();if(Number.isFinite(se)&&Q>=se)return;const F=Math.max(0,Q-ue)%J,ee=F===0?J:J-F;Y=window.setTimeout(()=>{_(he=>he+1),ie()},ee)};return ie(),()=>{Y&&window.clearTimeout(Y)}}const q=window.setInterval(()=>{_(Y=>Y+1)},J);return()=>window.clearInterval(q)},[e,t,R,p,n,r,a]),w.useEffect(()=>{const J=I.current;if(!J)return;const ue=new IntersectionObserver(se=>{const q=se[0];$(!!(q&&(q.isIntersecting||q.intersectionRatio>0)))},{root:null,threshold:0,rootMargin:"300px 0px"});return ue.observe(J),()=>ue.disconnect()},[]);const M=typeof e=="number"?e:b;w.useEffect(()=>{L(!1)},[M]),w.useEffect(()=>{O.current=!1,B.current=0,H.current=!1,L(!1),_(J=>J+1)},[s]);const W=w.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${M}`,[s,M]),K=w.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&hover=1&file=index_hq.m3u8`,[s]);return g.jsx(OA,{content:(J,{close:ue})=>J&&g.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:g.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[g.jsx(iR,{src:K,muted:!1,className:["w-full h-full relative z-0"].filter(Boolean).join(" ")}),g.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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),g.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:se=>{se.preventDefault(),se.stopPropagation(),ue()},children:g.jsx(ib,{className:"h-4 w-4"})})]})}),children:g.jsx("div",{ref:I,className:["block relative rounded bg-gray-100 dark:bg-white/5 overflow-hidden",f||"w-full h-full"].join(" "),children:E?g.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"}):g.jsx("img",{src:W,loading:R?"eager":"lazy",fetchPriority:R?"high":"auto",alt:"",className:["block w-full h-full object-cover object-center",v].filter(Boolean).join(" "),onLoad:()=>{O.current=!0,B.current=0,P.current&&window.clearTimeout(P.current),L(!1)},onError:()=>{if(L(!0),!u||!R||!p||O.current)return;const J=n?D(n):NaN,ue=Number(d??6e4);if(!(!Number.isFinite(J)||Date.now()-J=q||(P.current&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{B.current+=1,_(Y=>Y+1)},u))}})})})}const Uc=new Map;let Vw=!1;function l$(){Vw||(Vw=!0,document.addEventListener("visibilitychange",()=>{if(document.hidden)for(const s of Uc.values())s.es&&(s.es.close(),s.es=null,s.dispatchers.clear());else for(const s of Uc.values())s.refs>0&&!s.es&&nR(s)}))}function nR(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 a of t)a(r)};s.dispatchers.set(e,i),s.es.addEventListener(e,i)}s.es.onerror=()=>{}}}function u$(s){s.es&&(s.es.close(),s.es=null,s.dispatchers.clear())}function c$(s){let e=Uc.get(s);return e||(e={url:s,es:null,refs:0,listeners:new Map,dispatchers:new Map},Uc.set(s,e)),e}function rR(s,e,t){l$();const i=c$(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=a=>{let u=null;try{u=JSON.parse(String(a.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 nR(i);return()=>{const r=Uc.get(s);if(!r)return;const a=r.listeners.get(e);a&&(a.delete(t),a.size===0&&r.listeners.delete(e)),r.refs=Math.max(0,r.refs-1),r.refs===0&&(u$(r),Uc.delete(s))}}const Mp=s=>{const e=s;return e.modelName??e.model??e.modelKey??e.username??e.name??"—"},aR=s=>{const e=s;return e.sourceUrl??e.url??e.roomUrl??""},oR=s=>{const e=s;return String(e.imageUrl??e.image_url??"").trim()},ec=s=>{const e=s;return String(e.key??e.id??Mp(s))},Vr=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},tc=s=>{if(s.kind==="job"){const t=s.job;return Vr(t.addedAt)||Vr(t.createdAt)||Vr(t.enqueuedAt)||Vr(t.queuedAt)||Vr(t.requestedAt)||Vr(t.startedAt)||0}const e=s.pending;return Vr(e.addedAt)||Vr(e.createdAt)||Vr(e.enqueuedAt)||Vr(e.queuedAt)||Vr(e.requestedAt)||0},lR=s=>{switch((s??"").toLowerCase()){case"stopping":return"Stop wird angefordert…";case"probe":return"Analysiere Datei (Dauer/Streams)…";case"remuxing":return"Konvertiere Container zu MP4…";case"moving":return"Verschiebe nach Done…";case"assets":return"Erstelle Vorschau/Thumbnails…";case"postwork":return"Nacharbeiten laufen…";default:return""}};async function d$(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 uR(s){const e=s.postWork;if(!e)return"Warte auf Nacharbeiten…";if(e.state==="running"){const t=typeof e.running=="number"?e.running:0,i=typeof e.maxParallel=="number"?e.maxParallel:0;return i>0?`Nacharbeiten laufen… (${t}/${i} parallel)`:"Nacharbeiten laufen…"}if(e.state==="queued"){const t=typeof e.position=="number"?e.position:0,i=typeof e.waiting=="number"?e.waiting:0,n=typeof e.running=="number"?e.running:0,r=Math.max(i+n,t);return t>0&&r>0?`Warte auf Nacharbeiten… ${t} / ${r}`:"Warte auf Nacharbeiten…"}return"Warte auf Nacharbeiten…"}function h$({job:s}){const e=String(s?.phase??"").trim(),t=Number(s?.progress??0),i=e.toLowerCase(),n=i==="recording";let r=e?lR(e)||e:"";i==="postwork"&&(r=uR(s)),n&&(r="Recording läuft…");const a=r||String(s?.status??"").trim().toLowerCase(),u=!n&&Number.isFinite(t)&&t>0&&t<100,c=!n&&!u&&!!e&&(!Number.isFinite(t)||t<=0||t>=100);return g.jsx("div",{className:"min-w-0",children:u?g.jsx(wc,{label:a,value:Math.max(0,Math.min(100,t)),showPercent:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):c?g.jsx(wc,{label:a,indeterminate:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:a})})})}function Rv({r:s,nowMs:e,blurPreviews:t,modelsByKey:i,stopRequestedIds:n,markStopRequested:r,onOpenPlayer:a,onStopJob:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f}){if(s.kind==="pending"){const q=s.pending,Y=Mp(q),ie=aR(q),Q=(q.currentShow||"unknown").toLowerCase();return g.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:[g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",title:Y,children:Y}),g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[g.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"}),g.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:Q})]})]}),g.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:"⏳"})]}),g.jsx("div",{className:"mt-3",children:(()=>{const oe=oR(q);return g.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:oe?g.jsx("img",{src:oe,alt:Y,className:["h-full w-full object-cover",t?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:F=>{F.currentTarget.style.display="none"}}):g.jsx("div",{className:"grid h-full w-full place-items-center",children:g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-300",children:"Waiting…"})})})})()}),ie?g.jsx("a",{href:ie,target:"_blank",rel:"noreferrer",className:"mt-3 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:oe=>oe.stopPropagation(),title:ie,children:ie}):null]})]})}const p=s.job,y=Kx(p.output),v=fT(p.output||""),b=String(p.phase??"").trim(),_=b.toLowerCase(),E=_==="recording",L=!!n[p.id],I=String(p.status??"").toLowerCase(),$=_!==""&&_!=="recording"||I!=="running"||L;let P=b?lR(b)||b:"";_==="recording"?P="Recording läuft…":_==="postwork"&&(P=uR(p));const B=I||"unknown",O=P||B,H=Number(p.progress??0),D=!E&&Number.isFinite(H)&&H>0&&H<100,M=!E&&!D&&!!b&&(!Number.isFinite(H)||H<=0||H>=100),W=y&&y!=="—"?y.toLowerCase():"",K=W?i[W]:void 0,J=!!K?.favorite,ue=K?.liked===!0,se=!!K?.watching;return g.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:()=>a(p),role:"button",tabIndex:0,onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&a(p)},children:[g.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"}),g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start gap-3",children:[g.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:g.jsx(sR,{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"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-base font-semibold text-gray-900 dark:text-white",title:y,children:y}),g.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",$?"ring-1 ring-amber-500/30":"ring-1 ring-emerald-500/25"].join(" "),title:B,children:B})]}),g.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-600 dark:text-gray-300",title:p.output,children:v||"—"})]}),g.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-1",children:[g.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:cR(p,e)}),g.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:hR(dR(p))})]})]}),p.sourceUrl?g.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:q=>q.stopPropagation(),title:p.sourceUrl,children:p.sourceUrl}):null]})]}),D||M?g.jsx("div",{className:"mt-3",children:D?g.jsx(wc,{label:O,value:Math.max(0,Math.min(100,H)),showPercent:!0,size:"sm",className:"w-full"}):g.jsx(wc,{label:O,indeterminate:!0,size:"sm",className:"w-full"})}):null,g.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2 border-t border-white/30 pt-3 dark:border-white/10",children:[g.jsx("div",{className:"flex items-center gap-1",onClick:q=>q.stopPropagation(),onMouseDown:q=>q.stopPropagation(),children:g.jsx(Aa,{job:p,variant:"table",busy:$,isFavorite:J,isLiked:ue,isWatching:se,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,order:["watch","favorite","like","details"],className:"flex items-center gap-1"})}),g.jsx(Zt,{size:"sm",variant:"primary",disabled:$,className:"shrink-0",onClick:q=>{q.stopPropagation(),!$&&(r(p.id),u(p.id))},children:$?"Stoppe…":"Stop"})]})]})]})}const fT=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",Kx=s=>{const e=fT(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},f$=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`},cR=(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)?f$(i-t):"—"},dR=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},hR=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]}`},Iv=s=>{const e=s,t=String(e.phase??"").trim(),i=e.postWork;return!!(String(e.postWorkKey??"").trim()||i&&(i.state==="queued"||i.state==="running")||s.endedAt&&t||t==="postwork")};function m$({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,modelsByKey:c={},blurPreviews:d}){const[f,p]=w.useState(!1),[y,v]=w.useState(!1),b=w.useRef(null),[_,E]=w.useState(!1),L=w.useCallback(async()=>{try{const oe=!!(await d$("/api/autostart/state",{cache:"no-store"}))?.paused;b.current=oe,v(oe)}catch{}},[]);w.useEffect(()=>{L();const Q=rR("/api/autostart/state/stream","autostart",oe=>{const F=!!oe?.paused;b.current!==F&&(b.current=F,v(F))});return()=>{Q()}},[L]);const I=w.useCallback(async()=>{if(!(_||y)){E(!0);try{await fetch("/api/autostart/pause",{method:"POST"}),v(!0)}catch{}finally{E(!1)}}},[_,y]),R=w.useCallback(async()=>{if(!(_||!y)){E(!0);try{await fetch("/api/autostart/resume",{method:"POST"}),v(!1)}catch{}finally{E(!1)}}},[_,y]),[$,P]=w.useState({}),[B,O]=w.useState({}),H=w.useCallback(Q=>{const oe=Array.isArray(Q)?Q:[Q];P(F=>{const ee={...F};for(const he of oe)he&&(ee[he]=!0);return ee}),O(F=>{const ee={...F};for(const he of oe)he&&(ee[he]=!0);return ee})},[]);w.useEffect(()=>{P(Q=>{const oe=Object.keys(Q);if(oe.length===0)return Q;const F={};for(const ee of oe){const he=s.find(Re=>Re.id===ee);if(!he)continue;const be=String(he.phase??"").trim().toLowerCase();be!==""&&be!=="recording"||he.status!=="running"||(F[ee]=!0)}return F})},[s]);const[D,M]=w.useState(()=>Date.now()),W=w.useMemo(()=>s.some(Q=>!Q.endedAt&&Q.status==="running"),[s]);w.useEffect(()=>{if(!W)return;const Q=window.setInterval(()=>M(Date.now()),15e3);return()=>window.clearInterval(Q)},[W]);const K=w.useMemo(()=>s.filter(Q=>{if(Iv(Q)||Q.endedAt)return!1;const oe=String(Q.phase??"").trim(),F=!!$[Q.id],ee=oe.trim().toLowerCase();return!(ee!==""&&ee!=="recording"||Q.status!=="running"||F)}).map(Q=>Q.id),[s,$]),J=w.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[96px]",cell:Q=>{if(Q.kind==="job"){const he=Q.job;return g.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md",children:g.jsx(sR,{jobId:he.id,blur:d,alignStartAt:he.startedAt,alignEndAt:he.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})})}const oe=Q.pending,F=Mp(oe),ee=oR(oe);return ee?g.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:g.jsx("img",{src:ee,alt:F,className:["h-full w-full object-cover",d?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:he=>{he.currentTarget.style.display="none"}})}):g.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:Q=>{if(Q.kind==="job"){const he=Q.job,be=fT(he.output||""),pe=Kx(he.output),Ce=String(he.status??"").toLowerCase(),Re=!!$[he.id],Ze=!!B[he.id],Ge=Ce==="stopped"||Ze&&!!he.endedAt,it=Ge?"stopped":Ce||"unknown",dt=!Ge&&Re,ot=dt?"stopping":it;return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"min-w-0 block max-w-[170px] truncate font-medium",title:pe,children:pe}),g.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1",Ce==="running"?"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":Ge?"bg-slate-500/15 text-slate-900 ring-slate-500/30 dark:bg-slate-400/10 dark:text-slate-200 dark:ring-slate-400/25":Ce==="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":Ce==="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":dt?"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:ot,children:ot})]}),g.jsx("span",{className:"block max-w-[220px] truncate",title:he.output,children:be}),he.sourceUrl?g.jsx("a",{href:he.sourceUrl,target:"_blank",rel:"noreferrer",title:he.sourceUrl,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:nt=>nt.stopPropagation(),children:he.sourceUrl}):g.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}const oe=Q.pending,F=Mp(oe),ee=aR(oe);return g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"block max-w-[170px] truncate font-medium",title:F,children:F}),ee?g.jsx("a",{href:ee,target:"_blank",rel:"noreferrer",title:ee,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:he=>he.stopPropagation(),children:ee}):g.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:Q=>{if(Q.kind==="job"){const ee=Q.job;return g.jsx(h$,{job:ee})}const F=(Q.pending.currentShow||"unknown").toLowerCase();return g.jsx("div",{className:"min-w-0",children:g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:F})})})}},{key:"runtime",header:"Dauer",widthClassName:"w-[90px]",cell:Q=>Q.kind==="job"?cR(Q.job,D):"—"},{key:"size",header:"Größe",align:"right",widthClassName:"w-[110px]",cell:Q=>Q.kind==="job"?g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white",children:hR(dR(Q.job))}):g.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:Q=>{if(Q.kind!=="job")return g.jsx("div",{className:"pr-2 text-right text-sm text-gray-500 dark:text-gray-400",children:"—"});const oe=Q.job,F=String(oe.phase??"").trim(),ee=!!$[oe.id],he=F.trim().toLowerCase(),pe=he!==""&&he!=="recording"||oe.status!=="running"||ee,Ce=Kx(oe.output||""),Re=Ce&&Ce!=="—"?c[Ce.toLowerCase()]:void 0,Ze=!!Re?.favorite,Ge=Re?.liked===!0,it=!!Re?.watching;return g.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pr-2",children:[g.jsx(Aa,{job:oe,variant:"table",busy:pe,isFavorite:Ze,isLiked:Ge,isWatching:it,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,order:["watch","favorite","like","details"],className:"flex items-center gap-1"}),(()=>{const dt=String(oe.phase??"").trim(),ot=!!$[oe.id],nt=dt.trim().toLowerCase(),gt=nt!==""&&nt!=="recording"||oe.status!=="running"||ot;return g.jsx(Zt,{size:"sm",variant:"primary",disabled:gt,className:"shrink-0",onClick:je=>{je.stopPropagation(),!gt&&(H(oe.id),i(oe.id))},children:gt?"Stoppe…":"Stop"})})()]})}}],[d,H,c,D,i,n,r,a,$,B]),ue=w.useMemo(()=>{const Q=s.filter(oe=>!Iv(oe)).map(oe=>({kind:"job",job:oe}));return Q.sort((oe,F)=>tc(F)-tc(oe)),Q},[s]),se=w.useMemo(()=>{const Q=s.filter(oe=>Iv(oe)).map(oe=>({kind:"job",job:oe}));return Q.sort((oe,F)=>tc(F)-tc(oe)),Q},[s]),q=w.useMemo(()=>{const Q=e.map(oe=>({kind:"pending",pending:oe}));return Q.sort((oe,F)=>tc(F)-tc(oe)),Q},[e]),Y=ue.length+se.length+q.length,ie=w.useCallback(async()=>{if(!f&&K.length!==0){p(!0);try{H(K),await Promise.allSettled(K.map(Q=>Promise.resolve(i(Q))))}finally{p(!1)}}},[f,K,H,i]);return g.jsxs("div",{className:"grid gap-3",children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:g.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[g.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Downloads"}),g.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:Y})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[g.jsx(Zt,{size:"sm",variant:y?"secondary":"primary",disabled:_,onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),y?R():I()},className:"hidden sm:inline-flex",title:y?"Autostart fortsetzen":"Autostart pausieren",leadingIcon:y?g.jsx(pM,{className:"size-4 shrink-0"}):g.jsx(yM,{className:"size-4 shrink-0"}),children:"Autostart"}),g.jsx(Zt,{size:"sm",variant:"primary",disabled:f||K.length===0,onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),ie()},className:"hidden sm:inline-flex",title:K.length===0?"Nichts zu stoppen":"Alle laufenden stoppen",children:f?"Stoppe alle…":`Alle stoppen (${K.length})`})]})]})})}),ue.length>0||se.length>0||q.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-3 grid gap-4 sm:hidden",children:[ue.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Downloads (",ue.length,")"]}),ue.map(Q=>g.jsx(Rv,{r:Q,nowMs:D,blurPreviews:d,modelsByKey:c,stopRequestedIds:$,markStopRequested:H,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`dl:${Q.kind==="job"?Q.job.id:ec(Q.pending)}`))]}):null,se.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Nacharbeiten (",se.length,")"]}),se.map(Q=>g.jsx(Rv,{r:Q,nowMs:D,blurPreviews:d,modelsByKey:c,stopRequestedIds:$,markStopRequested:H,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`pw:${Q.kind==="job"?Q.job.id:ec(Q.pending)}`))]}):null,q.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Wartend (",q.length,")"]}),q.map(Q=>g.jsx(Rv,{r:Q,nowMs:D,blurPreviews:d,modelsByKey:c,stopRequestedIds:$,markStopRequested:H,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`wa:${Q.kind==="job"?Q.job.id:ec(Q.pending)}`))]}):null]}),g.jsxs("div",{className:"mt-3 hidden sm:block space-y-4",children:[ue.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Downloads (",ue.length,")"]}),g.jsx(fh,{rows:ue,columns:J,getRowKey:Q=>Q.kind==="job"?`dl:job:${Q.job.id}`:`dl:pending:${ec(Q.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:Q=>{Q.kind==="job"&&t(Q.job)}})]}):null,se.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Nacharbeiten (",se.length,")"]}),g.jsx(fh,{rows:se,columns:J,getRowKey:Q=>Q.kind==="job"?`pw:job:${Q.job.id}`:`pw:pending:${ec(Q.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:Q=>{Q.kind==="job"&&t(Q.job)}})]}):null,q.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Wartend (",q.length,")"]}),g.jsx(fh,{rows:q,columns:J,getRowKey:Q=>Q.kind==="job"?`wa:job:${Q.job.id}`:`wa:pending:${ec(Q.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0})]}):null]})]}):g.jsx(Ca,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"⏸️"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine laufenden Downloads"}),g.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."})]})]})})]})}function Wx({open:s,onClose:e,title:t,children:i,footer:n,icon:r,width:a="max-w-lg"}){return g.jsx(hh,{show:s,as:w.Fragment,children:g.jsxs(cc,{as:"div",className:"relative z-50",onClose:e,children:[g.jsx(hh.Child,{as:w.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:g.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),g.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto px-4 py-6 sm:px-6",children:g.jsx("div",{className:"min-h-full flex items-start justify-center sm:items-center",children:g.jsx(hh.Child,{as:w.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:g.jsxs(cc.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",a].join(" "),children:[r&&g.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}),g.jsxs("div",{className:"px-6 pt-6 flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0",children:t?g.jsx(cc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white truncate",children:t}):null}),g.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:g.jsx(ib,{className:"size-5"})})]}),g.jsx("div",{className:"px-6 pb-6 pt-4 text-sm text-gray-700 dark:text-gray-300 overflow-y-auto",children:i}),n?g.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 Nv(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 zw=(s,e)=>g.jsx("span",{className:mi("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 p$(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 Ov(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 g$(s){return String(s??"").trim().toLowerCase().replace(/^www\./,"")}function y$(s){const t=String(s||"").replaceAll("\\","/").split("/");return t[t.length-1]||""}function v$(s){const e=String(s||"");return e.toUpperCase().startsWith("HOT ")?e.slice(4).trim():e}function x$(s){const e=y$(s||""),t=v$(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}function Mv(s){if(s.isUrl&&/^https?:\/\//i.test(String(s.input??"")))return String(s.input);const e=g$(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 qw({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return g.jsx("span",{className:mi(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:g.jsx(Zt,{variant:e?"soft":"secondary",size:"xs",className:mi("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:g.jsx("span",{className:"text-base leading-none",children:n})})})}function Kw(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 b$(){const[s,e]=w.useState([]),t=w.useRef({}),[i,n]=w.useState(!1),[r,a]=w.useState(null),[u,c]=w.useState(""),[d,f]=w.useState(1),p=10,[y,v]=w.useState([]),[b,_]=w.useState({}),[E,L]=w.useState(!1),[I,R]=w.useState(),$=w.useCallback(async()=>{L(!0);try{const ge=await fetch("/api/record/done?all=1&includeKeep=1",{cache:"no-store"});if(!ge.ok)return;const Je=await ge.json().catch(()=>null),Ye=Array.isArray(Je?.items)?Je.items:Array.isArray(Je)?Je:[],Qe={};for(const mt of Ye){const ct=x$(mt.output);if(!ct||ct==="—")continue;const et=ct.trim().toLowerCase();et&&(Qe[et]=(Qe[et]??0)+1)}_(Qe)}finally{L(!1)}},[]),P=w.useMemo(()=>new Set(y.map(ge=>ge.toLowerCase())),[y]),B=w.useCallback(ge=>{const Je=ge.toLowerCase();v(Ye=>Ye.some(mt=>mt.toLowerCase()===Je)?Ye.filter(mt=>mt.toLowerCase()!==Je):[...Ye,ge])},[]),O=w.useCallback(()=>v([]),[]);w.useEffect(()=>{const ge=Je=>{const Ye=Je,Qe=Array.isArray(Ye.detail?.tags)?Ye.detail.tags:[];v(Qe)};return window.addEventListener("models:set-tag-filter",ge),()=>window.removeEventListener("models:set-tag-filter",ge)},[]),w.useEffect(()=>{try{const ge=localStorage.getItem("models_pendingTags");if(!ge)return;const Je=JSON.parse(ge);Array.isArray(Je)&&v(Je),localStorage.removeItem("models_pendingTags")}catch{}},[]);const[H,D]=w.useState(""),[M,W]=w.useState(null),[K,J]=w.useState(null),[ue,se]=w.useState(!1),[q,Y]=w.useState(!1),[ie,Q]=w.useState(null),[oe,F]=w.useState(null),[ee,he]=w.useState("favorite"),[be,pe]=w.useState(!1),[Ce,Re]=w.useState(null);async function Ze(){if(ie){pe(!0),F(null),a(null);try{const ge=new FormData;ge.append("file",ie),ge.append("kind",ee);const Je=await fetch("/api/models/import",{method:"POST",body:ge});if(!Je.ok)throw new Error(await Je.text());const Ye=await Je.json();F(`✅ Import: ${Ye.inserted} neu, ${Ye.updated} aktualisiert, ${Ye.skipped} übersprungen`),Y(!1),Q(null),await dt(),window.dispatchEvent(new Event("models-changed"))}catch(ge){Re(ge?.message??String(ge))}finally{pe(!1)}}}function Ge(ge){const Je=Mv(ge)??void 0;return{output:`${ge.modelKey}_01_01_2000__00-00-00.mp4`,sourceUrl:Je}}const it=()=>{Re(null),F(null),Q(null),he("favorite"),Y(!0)},dt=w.useCallback(async()=>{n(!0),a(null);try{const ge=await Nv("/api/models/list",{cache:"no-store"});e(Array.isArray(ge)?ge:[]),$()}catch(ge){a(ge?.message??String(ge))}finally{n(!1)}},[$]);w.useEffect(()=>{$()},[$]),w.useEffect(()=>{dt()},[dt]),w.useEffect(()=>{const ge=Je=>{const Qe=Je?.detail??{};if(Qe?.model){const mt=Qe.model;e(ct=>{const et=ct.findIndex(Jt=>Jt.id===mt.id);if(et===-1)return ct;const Gt=ct.slice();return Gt[et]=mt,Gt});return}if(Qe?.removed&&Qe?.id){const mt=String(Qe.id);e(ct=>ct.filter(et=>et.id!==mt));return}dt()};return window.addEventListener("models-changed",ge),()=>window.removeEventListener("models-changed",ge)},[dt]),w.useEffect(()=>{const ge=H.trim();if(!ge){W(null),J(null);return}const Je=p$(ge);if(!Je){W(null),J("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const Ye=window.setTimeout(async()=>{try{const Qe=await Nv("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Je})});if(!Qe?.isUrl){W(null),J("Bitte nur URLs einfügen (keine Modelnamen).");return}W(Qe),J(null)}catch(Qe){W(null),J(Qe?.message??String(Qe))}},300);return()=>window.clearTimeout(Ye)},[H]);const ot=w.useMemo(()=>s.map(ge=>({m:ge,hay:`${ge.modelKey} ${ge.host??""} ${ge.input??""} ${ge.tags??""}`.toLowerCase()})),[s]),nt=w.useDeferredValue(u),ft=w.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:ge=>{const Je=ge.liked===!0,Ye=ge.favorite===!0,Qe=ge.watching===!0,mt=!Qe&&!Ye&&!Je;return g.jsxs("div",{className:"group flex items-center justify-center gap-1 w-[110px]",children:[g.jsx("span",{className:mi(mt&&!Qe?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:g.jsx(Zt,{variant:Qe?"soft":"secondary",size:"xs",className:mi("px-2 py-1 leading-none",!Qe&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:Qe?"Nicht mehr beobachten":"Beobachten",onClick:ct=>{ct.stopPropagation(),ut(ge.id,{watched:!Qe})},children:g.jsx("span",{className:mi("text-base leading-none",Qe?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),g.jsx(qw,{title:Ye?"Favorit entfernen":"Als Favorit markieren",active:Ye,hiddenUntilHover:mt,onClick:ct=>{ct.stopPropagation(),Ye?ut(ge.id,{favorite:!1}):ut(ge.id,{favorite:!0,liked:!1})},icon:g.jsx("span",{className:Ye?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),g.jsx(qw,{title:Je?"Gefällt mir entfernen":"Gefällt mir",active:Je,hiddenUntilHover:mt,onClick:ct=>{ct.stopPropagation(),Je?ut(ge.id,{liked:!1}):ut(ge.id,{liked:!0,favorite:!1})},icon:g.jsx("span",{className:Je?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",sortable:!0,sortValue:ge=>(ge.modelKey||"").toLowerCase(),cell:ge=>{const Je=Mv(ge);return g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"font-medium truncate",children:ge.modelKey}),Je?g.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",title:Je,onClick:Ye=>{Ye.stopPropagation(),window.open(Je,"_blank","noreferrer")},children:"↗"}):null]}),g.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:ge.host??"—"}),Je?g.jsx("div",{className:"text-xs text-indigo-600 dark:text-indigo-400 truncate max-w-[520px]",children:Je}):null]})}},{key:"videos",header:"Videos",sortable:!0,sortValue:ge=>{const Je=String(ge.modelKey||"").trim().toLowerCase(),Ye=b[Je];return typeof Ye=="number"?Ye:0},align:"right",cell:ge=>{const Je=String(ge.modelKey||"").trim().toLowerCase(),Ye=b[Je];return g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white w-[64px] inline-block text-right",children:typeof Ye=="number"?Ye:E?"…":0})}},{key:"tags",header:"Tags",sortable:!0,sortValue:ge=>Ov(ge.tags).length,cell:ge=>{const Je=Ov(ge.tags),Ye=Je.slice(0,6),Qe=Je.length-Ye.length,mt=Je.join(", ");return g.jsxs("div",{className:"flex flex-wrap gap-2 max-w-[520px]",title:mt||void 0,children:[ge.hot?zw(!0,"🔥 HOT"):null,ge.keep?zw(!0,"📌 Behalten"):null,Ye.map(ct=>g.jsx(Kr,{tag:ct,title:ct,active:P.has(ct.toLowerCase()),onClick:B},ct)),Qe>0?g.jsxs(Kr,{title:mt,children:["+",Qe]}):null,!ge.hot&&!ge.keep&&Je.length===0?g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}},{key:"actions",header:"",align:"right",cell:ge=>g.jsx("div",{className:"flex justify-end w-[92px]",children:g.jsx(Aa,{job:Ge(ge),variant:"table",order:["add","details"],className:"flex items-center gap-2"})})}],[P,B,b,E]),gt=w.useMemo(()=>{const ge=nt.trim().toLowerCase(),Je=ge?ot.filter(Ye=>Ye.hay.includes(ge)).map(Ye=>Ye.m):s;return P.size===0?Je:Je.filter(Ye=>{const Qe=Ov(Ye.tags);if(Qe.length===0)return!1;const mt=new Set(Qe.map(ct=>ct.toLowerCase()));for(const ct of P)if(!mt.has(ct))return!1;return!0})},[s,ot,nt,P]),je=w.useMemo(()=>{if(!I)return gt;const ge=ft.find(Qe=>Qe.key===I.key);if(!ge)return gt;const Je=I.direction==="asc"?1:-1,Ye=gt.map((Qe,mt)=>({r:Qe,i:mt}));return Ye.sort((Qe,mt)=>{let ct=0;if(ge.sortFn)ct=ge.sortFn(Qe.r,mt.r);else{const et=ge.sortValue?ge.sortValue(Qe.r):Qe.r?.[ge.key],Gt=ge.sortValue?ge.sortValue(mt.r):mt.r?.[ge.key],Jt=Kw(et),It=Kw(Gt);Jt.isNull&&!It.isNull?ct=1:!Jt.isNull&&It.isNull?ct=-1:Jt.kind==="number"&&It.kind==="number"?ct=Jt.valueIt.value?1:0:ct=String(Jt.value).localeCompare(String(It.value),void 0,{numeric:!0})}return ct===0?Qe.i-mt.i:ct*Je}),Ye.map(Qe=>Qe.r)},[gt,I,ft]);w.useEffect(()=>{f(1)},[u,y]);const bt=je.length,vt=w.useMemo(()=>Math.max(1,Math.ceil(bt/p)),[bt,p]);w.useEffect(()=>{d>vt&&f(vt)},[d,vt]);const jt=w.useMemo(()=>{const ge=(d-1)*p;return je.slice(ge,ge+p)},[je,d,p]),We=async()=>{if(M){if(!M.isUrl){J("Bitte nur URLs einfügen (keine Modelnamen).");return}se(!0),a(null);try{const ge=await Nv("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});e(Je=>{const Ye=Je.filter(Qe=>Qe.id!==ge.id);return[ge,...Ye]}),D(""),W(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:ge}}))}catch(ge){a(ge?.message??String(ge))}finally{se(!1)}}};async function ut(ge,Je){if(a(null),t.current[ge])return;t.current[ge]=!0;const Ye=s.find(Qe=>Qe.id===ge)??null;if(Ye){const Qe={...Ye,...Je};typeof Je?.watched=="boolean"&&(Qe.watching=Je.watched),Je?.favorite===!0&&(Qe.liked=!1),Je?.liked===!0&&(Qe.favorite=!1),e(mt=>mt.map(ct=>ct.id===ge?Qe:ct)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Qe}}))}try{const Qe=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:ge,...Je})});if(Qe.status===204){e(ct=>ct.filter(et=>et.id!==ge)),Ye?window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Ye.id,modelKey:Ye.modelKey}})):window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ge}}));return}if(!Qe.ok){const ct=await Qe.text().catch(()=>"");throw new Error(ct||`HTTP ${Qe.status}`)}const mt=await Qe.json();e(ct=>{const et=ct.findIndex(Jt=>Jt.id===mt.id);if(et===-1)return ct;const Gt=ct.slice();return Gt[et]=mt,Gt}),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:mt}}))}catch(Qe){Ye&&(e(mt=>mt.map(ct=>ct.id===ge?Ye:ct)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Ye}}))),a(Qe?.message??String(Qe))}finally{delete t.current[ge]}}return g.jsxs("div",{className:"space-y-4",children:[g.jsx(Ca,{header:g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:g.jsxs("div",{className:"grid gap-2",children:[g.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[g.jsx("input",{value:H,onChange:ge=>D(ge.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"}),g.jsx(Zt,{className:"px-3 py-2 text-sm",onClick:We,disabled:!M||ue,title:M?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),g.jsx(Zt,{className:"px-3 py-2 text-sm",onClick:dt,disabled:i,children:"Aktualisieren"})]}),K?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:K}):M?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",g.jsx("span",{className:"font-medium",children:M.modelKey}),M.host?g.jsxs("span",{className:"opacity-70",children:[" • ",M.host]}):null]}):null,r?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:r}):null]})}),g.jsxs(Ca,{header:g.jsxs("div",{className:"space-y-2",children:[g.jsxs("div",{className:"grid gap-2 sm:flex sm:items-center sm:justify-between",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",gt.length,")"]})]}),g.jsx("div",{className:"sm:hidden",children:g.jsx(Zt,{variant:"secondary",size:"md",onClick:it,children:"Import"})})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("div",{className:"hidden sm:block",children:g.jsx(Zt,{variant:"secondary",size:"md",onClick:it,children:"Importieren"})}),g.jsx("input",{value:u,onChange:ge=>c(ge.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 - `})]})]}),y.length>0?g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Tag-Filter:"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.map(ge=>g.jsx(Kr,{tag:ge,active:!0,onClick:B,title:ge},ge)),g.jsx(Zt,{size:"sm",variant:"soft",className:"text-xs font-medium text-gray-600 hover:underline dark:text-gray-300",onClick:O,children:"Zurücksetzen"})]})]}):null]}),noBodyPadding:!0,children:[g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:"min-w-[980px]",children:g.jsx(fh,{rows:jt,columns:ft,getRowKey:ge=>ge.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,sort:I,onSortChange:ge=>R(ge),onRowClick:ge=>{const Je=Mv(ge);Je&&window.open(Je,"_blank","noreferrer")}})})}),g.jsx(BA,{page:d,pageSize:p,totalItems:bt,onPageChange:f})]}),g.jsx(Wx,{open:q,onClose:()=>!be&&Y(!1),title:"Models importieren",footer:g.jsxs(g.Fragment,{children:[g.jsx(Zt,{variant:"secondary",onClick:()=>Y(!1),disabled:be,children:"Abbrechen"}),g.jsx(Zt,{variant:"primary",onClick:Ze,isLoading:be,disabled:!ie||be,children:"Import starten"})]}),children:g.jsxs("div",{className:"space-y-3",children:[g.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),g.jsxs("div",{className:"space-y-2",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),g.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:ee==="favorite",onChange:()=>he("favorite"),disabled:be}),"Favoriten (★)"]}),g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:ee==="liked",onChange:()=>he("liked"),disabled:be}),"Gefällt mir (♥)"]})]})]}),g.jsx("input",{type:"file",accept:".csv,text/csv",onChange:ge=>{const Je=ge.target.files?.[0]??null;Re(null),Q(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"}),ie?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",g.jsx("span",{className:"font-medium",children:ie.name})]}):null,Ce?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:Ce}):null,oe?g.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:oe}):null]})})]})}function Dn(...s){return s.filter(Boolean).join(" ")}const T$=new Intl.NumberFormat("de-DE");function Pv(s){return s==null||!Number.isFinite(s)?"—":T$.format(s)}function _$(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 Jd(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 S$(s){return s?s.split(",").map(e=>e.trim()).filter(Boolean):[]}function Xl(s){return(s||"").split(/[\\/]/).pop()||""}function E$(s){return String(s||"").replaceAll("\\","/")}function w$(s){return(E$(s||"").toLowerCase().match(/\/keep\/([^/]+)\//)?.[1]||"").trim().toLowerCase()}function mT(s){return s.startsWith("HOT ")?s.slice(4):s}function A$(s){return String(s||"").startsWith("HOT ")}function C$(s,e){const t=String(s||"");return t&&t.replace(/([\\/])[^\\/]*$/,`$1${e}`)}function k$(s){return A$(s)?mT(s):`HOT ${s}`}function Yw(s){const e=Xl(s||""),t=mT(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}function Bv(s){return s?String(s).replace(/[\s\S]*?<\/script>/gi,"").replace(/[\s\S]*?<\/style>/gi,"").replace(/<\/?[^>]+>/g," ").replace(/\s+/g," ").trim():""}function D$(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 so(s){return Dn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset",s)}const Fv=s=>s?"blur-md scale-[1.03] brightness-90":"";function L$(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 R$(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 I$({open:s,modelKey:e,onClose:t,onOpenPlayer:i,cookies:n,runningJobs:r,blurPreviews:a,onToggleWatch:u,onToggleFavorite:c,onToggleLike:d,onToggleHot:f,onDelete:p}){const[y,v]=w.useState([]),[b,_]=w.useState(!1),[E,L]=w.useState(null),[I,R]=w.useState(null),[$,P]=w.useState(!1),[B,O]=w.useState(null),[H,D]=w.useState(null),[M,W]=w.useState(!1),[K,J]=w.useState([]),[ue,se]=w.useState(!1),[q,Y]=w.useState([]),[ie,Q]=w.useState(!1),[oe,F]=w.useState(0),[ee,he]=w.useState(null),[be,pe]=w.useState(0),Ce=w.useCallback(async()=>{try{const te=await(await fetch("/api/models/list",{cache:"no-store"})).json().catch(()=>null);v(Array.isArray(te)?te:[])}catch{}},[]),Re=w.useCallback(async()=>{try{const _e=await(await fetch("/api/record/done?all=1&sort=completed_desc&includeKeep=1",{cache:"no-store"})).json().catch(()=>null),Oe=Array.isArray(_e)?_e:Array.isArray(_e?.items)?_e.items:[];J(Oe)}catch{}},[]);function Ze(V){return{id:`model:${V}`,output:`${V}_01_01_2000__00-00-00.mp4`,status:"finished"}}const Ge=w.useCallback((V,te)=>{const _e=String(V??"").trim();_e&&he({src:_e,alt:te})},[]);w.useEffect(()=>{s||F(0)},[s]);const[it,dt]=w.useState(1),ot=25,nt=L$(e),ft=w.useMemo(()=>Array.isArray(r)?r:q,[r,q]);w.useEffect(()=>{s&&dt(1)},[s,e]),w.useEffect(()=>{if(!s)return;let V=!0;return _(!0),fetch("/api/models/list",{cache:"no-store"}).then(te=>te.json()).then(te=>{V&&v(Array.isArray(te)?te:[])}).catch(()=>{V&&v([])}).finally(()=>{V&&_(!1)}),()=>{V=!1}},[s]),w.useEffect(()=>{if(!s||!nt)return;let V=!0;return P(!0),L(null),R(null),fetch("/api/chaturbate/online",{cache:"no-store"}).then(te=>te.json()).then(te=>{if(!V)return;R({enabled:te?.enabled,fetchedAt:te?.fetchedAt,lastError:te?.lastError});const Oe=(Array.isArray(te?.rooms)?te.rooms:[]).find(tt=>String(tt?.username??"").trim().toLowerCase()===nt)??null;L(Oe)}).catch(()=>{V&&(R({enabled:void 0,fetchedAt:void 0,lastError:"Fetch fehlgeschlagen"}),L(null))}).finally(()=>{V&&P(!1)}),()=>{V=!1}},[s,nt]),w.useEffect(()=>{if(!s||!nt)return;let V=!0;W(!0),O(null),D(null);const te=R$(n),_e=`/api/chaturbate/biocontext?model=${encodeURIComponent(nt)}${oe>0?"&refresh=1":""}`;return fetch(_e,{cache:"no-store",headers:te?{"X-Chaturbate-Cookie":te}:void 0}).then(async Oe=>{if(!Oe.ok){const tt=await Oe.text().catch(()=>"");throw new Error(tt||`HTTP ${Oe.status}`)}return Oe.json()}).then(Oe=>{V&&(D({enabled:Oe?.enabled,fetchedAt:Oe?.fetchedAt,lastError:Oe?.lastError}),O(Oe?.bio??null))}).catch(Oe=>{V&&(D({enabled:void 0,fetchedAt:void 0,lastError:Oe?.message||"Fetch fehlgeschlagen"}),O(null))}).finally(()=>{V&&W(!1)}),()=>{V=!1}},[s,nt,oe,n]),w.useEffect(()=>{if(!s||!nt)return;let V=!0;se(!0);const te=`/api/record/done?model=${encodeURIComponent(nt)}&page=${it}&pageSize=${ot}&sort=completed_desc&includeKeep=1&withCount=1`;return fetch(te,{cache:"no-store"}).then(_e=>_e.json()).then(_e=>{if(!V)return;const Oe=Array.isArray(_e?.items)?_e.items:[],tt=Number(_e?.count??Oe.length);J(Oe),pe(Number.isFinite(tt)?tt:Oe.length)}).catch(()=>{V&&(J([]),pe(0))}).finally(()=>{V&&se(!1)}),()=>{V=!1}},[s,nt,it]),w.useEffect(()=>{if(!s||Array.isArray(r))return;let V=!0;return Q(!0),fetch("/api/record/jobs",{cache:"no-store"}).then(te=>te.json()).then(te=>{V&&Y(Array.isArray(te)?te:[])}).catch(()=>{V&&Y([])}).finally(()=>{V&&Q(!1)}),()=>{V=!1}},[s,r]);const gt=w.useMemo(()=>nt?y.find(V=>(V.modelKey||"").toLowerCase()===nt)??null:null,[y,nt]),je=w.useMemo(()=>nt?K.filter(V=>{const te=V.output||"",_e=w$(te);if(_e)return _e===nt;const Oe=Yw(te);return Oe!=="—"&&Oe.trim().toLowerCase()===nt}):[],[K,nt]),bt=w.useMemo(()=>Math.max(1,Math.ceil(be/ot)),[be]),vt=w.useMemo(()=>{const V=(it-1)*ot;return je.slice(V,V+ot)},[je,it]),jt=w.useMemo(()=>nt?ft.filter(V=>{const te=Yw(V.output);return te!=="—"&&te.trim().toLowerCase()===nt}):[],[ft,nt]),We=w.useMemo(()=>{const V=S$(gt?.tags),te=Array.isArray(E?.tags)?E.tags:[],_e=new Map;for(const Oe of[...V,...te]){const tt=String(Oe).trim().toLowerCase();tt&&(_e.has(tt)||_e.set(tt,String(Oe).trim()))}return Array.from(_e.values()).sort((Oe,tt)=>Oe.localeCompare(tt,"de"))},[gt?.tags,E?.tags]),ut=E?.display_name||gt?.modelKey||nt||"Model",ge=E?.image_url_360x270||E?.image_url||"",Je=E?.image_url||ge,Ye=E?.chat_room_url_revshare||E?.chat_room_url||"",Qe=(E?.current_show||"").trim().toLowerCase(),mt=Qe?Qe==="public"?"Public":Qe==="private"?"Private":Qe:"",ct=(B?.location||"").trim(),et=B?.follower_count,Gt=B?.display_age,Jt=(B?.room_status||"").trim(),It=B?.last_broadcast?Jd(B.last_broadcast):"—",Ft=Bv(B?.about_me),$t=Bv(B?.wish_list),Ke=Array.isArray(B?.social_medias)?B.social_medias:[],Lt=Array.isArray(B?.photo_sets)?B.photo_sets:[],Qt=Array.isArray(B?.interested_in)?B.interested_in:[],Ut=b||ue||ie||$||M,ci=({icon:V,label:te,value:_e})=>g.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:[g.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[V,te]}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold text-gray-900 dark:text-white",children:_e})]}),vi=w.useCallback(async V=>{const te=V.output||"",_e=Xl(te);if(!_e){await f?.(V);return}const Oe=k$(_e);J(tt=>tt.map(Ot=>Xl(Ot.output||"")!==_e?Ot:{...Ot,output:C$(Ot.output||"",Oe)})),await f?.(V),Re()},[f,Re]),ei=w.useCallback(async V=>{const te=V.output||"",_e=Xl(te);_e&&J(Oe=>Oe.filter(tt=>Xl(tt.output||"")!==_e)),await p?.(V),Re()},[p,Re]),Bi=w.useCallback(async()=>{nt&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===nt?{...te,favorite:!te.favorite}:te)),await c?.(Ze(nt)),Ce())},[nt,c,Ce]),yt=w.useCallback(async()=>{nt&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===nt?{...te,liked:te.liked!==!0}:te)),await d?.(Ze(nt)),Ce())},[nt,d,Ce]),z=w.useCallback(async()=>{nt&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===nt?{...te,watching:!te.watching}:te)),await u?.(Ze(nt)),Ce())},[nt,u,Ce]);return g.jsxs(Wx,{open:s,onClose:t,title:ut,width:"max-w-6xl",footer:g.jsx(Zt,{variant:"secondary",onClick:t,children:"Schließen"}),children:[g.jsxs("div",{className:"space-y-6",children:[g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:nt?g.jsxs("span",{children:["Key: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:nt}),I?.fetchedAt?g.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Online-Stand: ",Jd(I.fetchedAt)]}):null,H?.fetchedAt?g.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Bio-Stand: ",Jd(H.fetchedAt)]}):null]}):"—"}),g.jsx("div",{className:"flex items-center gap-2",children:Ye?g.jsxs("a",{href:Ye,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:[g.jsx(Ty,{className:"size-4"}),"Room öffnen"]}):null})]}),g.jsxs("div",{className:"grid gap-5 lg:grid-cols-[320px_1fr]",children:[g.jsx("div",{className:"space-y-4",children:g.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:[g.jsxs("div",{className:"relative",children:[ge?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ge(Je,ut),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:ge,alt:ut,className:Dn("h-52 w-full object-cover transition",Fv(a))})}):g.jsx("div",{className:"h-52 w-full bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),g.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"}),g.jsxs("div",{className:"absolute left-3 top-3 flex flex-wrap items-center gap-2",children:[mt?g.jsx("span",{className:so("bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20"),children:mt}):null,Jt?g.jsx("span",{className:so(Jt.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:Jt}):null,E?.is_hd?g.jsx("span",{className:so("bg-indigo-500/10 text-indigo-900 ring-indigo-200 backdrop-blur dark:text-indigo-200 dark:ring-indigo-400/20"),children:"HD"}):null,E?.is_new?g.jsx("span",{className:so("bg-amber-500/10 text-amber-900 ring-amber-200 backdrop-blur dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),g.jsxs("div",{className:"absolute bottom-3 left-3 right-3",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white drop-shadow",children:E?.display_name||E?.username||gt?.modelKey||nt||"—"}),g.jsx("div",{className:"truncate text-xs text-white/85 drop-shadow",children:E?.username?`@${E.username}`:gt?.modelKey?`@${gt.modelKey}`:""})]}),g.jsxs("div",{className:"absolute bottom-3 right-3 flex items-center gap-2",children:[g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),z()},className:Dn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.watching?"bg-sky-500/25 ring-sky-200/30":"bg-black/20 ring-white/15"),title:gt?.watching?"Watch entfernen":"Auf Watch setzen","aria-pressed":!!gt?.watching,"aria-label":gt?.watching?"Watch entfernen":"Auf Watch setzen",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(Zv,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Ac,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-200")})]})}),g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),Bi()},className:Dn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.favorite?"bg-amber-500/25 ring-amber-200/30":"bg-black/20 ring-white/15"),title:gt?.favorite?"Favorit entfernen":"Als Favorit markieren","aria-pressed":!!gt?.favorite,"aria-label":gt?.favorite?"Favorit entfernen":"Als Favorit markieren",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(Jv,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Sh,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-200")})]})}),g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),yt()},className:Dn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.liked?"bg-rose-500/25 ring-rose-200/30":"bg-black/20 ring-white/15"),title:gt?.liked?"Like entfernen":"Liken","aria-pressed":gt?.liked===!0,"aria-label":gt?.liked?"Like entfernen":"Liken",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(sp,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Cc,{className:Dn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-200")})]})})]})]}),g.jsxs("div",{className:"p-4",children:[g.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[g.jsx(ci,{icon:g.jsx(iM,{className:"size-4"}),label:"Viewer",value:Pv(E?.num_users)}),g.jsx(ci,{icon:g.jsx(GS,{className:"size-4"}),label:"Follower",value:Pv(E?.num_followers??et)})]}),g.jsxs("dl",{className:"mt-4 grid gap-2 text-xs",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(GO,{className:"size-4"}),"Location"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:E?.location||ct||"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(FO,{className:"size-4"}),"Sprache"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:E?.spoken_languages||"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(jS,{className:"size-4"}),"Online"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:Ww(E?.seconds_online)})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(sp,{className:"size-4"}),"Alter"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:Gt!=null?String(Gt):E?.age!=null?String(E.age):"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(jS,{className:"size-4"}),"Last broadcast"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:It})]})]}),I?.enabled===!1?g.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."}):I?.lastError?g.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: ",I.lastError]}):null,H?.enabled===!1?g.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."}):H?.lastError?g.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: ",H.lastError]}):null]})]})}),g.jsxs("div",{className:"space-y-4",children:[g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Room Subject"}),Ut?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:E?.room_subject?g.jsx("p",{className:"line-clamp-4 whitespace-pre-wrap break-words",children:E.room_subject}):g.jsx("p",{className:"text-gray-600 dark:text-gray-300",children:"Keine Subject-Info vorhanden."})})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Bio"}),g.jsxs("div",{className:"flex items-center gap-2",children:[M?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null,g.jsx(Zt,{variant:"secondary",className:"h-7 px-2 text-xs",disabled:M||!e,onClick:()=>F(V=>V+1),title:"BioContext neu abrufen",children:"Aktualisieren"})]})]}),g.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[g.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(OO,{className:"size-4"}),"Über mich"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Ft?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Ft}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(GS,{className:"size-4"}),"Wishlist"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:$t?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:$t}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]})]}),g.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Real name:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:B?.real_name?Bv(B.real_name):"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Body type:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:B?.body_type||"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Smoke/Drink:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:B?.smoke_drink||"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Sex:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:B?.sex||"—"})]})]}),Qt.length?g.jsxs("div",{className:"mt-3",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Interested in"}),g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Qt.map(V=>g.jsx("span",{className:so("bg-sky-500/10 text-sky-900 ring-sky-200 dark:text-sky-200 dark:ring-sky-400/20"),children:V},V))})]}):null]}),g.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:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tags"}),We.length?g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:We.map(V=>g.jsx(Kr,{tag:V},V))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Tags vorhanden."})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Socials"}),Ke.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[Ke.length," Links"]}):null]}),Ke.length?g.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:Ke.map(V=>{const te=D$(V.link);return g.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",className:Dn("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:V.title_name,children:[g.jsx("div",{className:"flex size-9 items-center justify-center rounded-lg bg-black/5 dark:bg-white/5",children:V.image_url?g.jsx("img",{src:V.image_url,alt:"",className:"size-5"}):g.jsx(jO,{className:"size-5"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:V.title_name}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:V.label_text?V.label_text:V.tokens!=null?`${V.tokens} token(s)`:"Link"})]}),g.jsx(Ty,{className:"ml-auto size-4 text-gray-400 transition group-hover:text-indigo-500 dark:text-gray-500 dark:group-hover:text-indigo-400"})]},V.id)})}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Social-Medias vorhanden."})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Photo sets"}),Lt.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[Lt.length," Sets"]}):null]}),Lt.length?g.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:Lt.slice(0,6).map(V=>g.jsxs("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"relative",children:[V.cover_url?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ge(V.cover_url,V.name),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:V.cover_url,alt:V.name,className:Dn("h-28 w-full object-cover transition",Fv(a))})}):g.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-black/5 dark:bg-white/5",children:g.jsx(zO,{className:"size-6 text-gray-500"})}),g.jsxs("div",{className:"absolute left-2 top-2 flex flex-wrap gap-2",children:[V.is_video?g.jsx("span",{className:so("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"Video"}):g.jsx("span",{className:so("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:"Photos"}),V.fan_club_only?g.jsx("span",{className:so("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"FanClub"}):null]})]}),g.jsxs("div",{className:"p-3",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:V.name}),g.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:["Tokens: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Pv(V.tokens)}),V.user_can_access===!0?g.jsx("span",{className:"ml-2",children:"· Zugriff: ✅"}):null]})]})]},V.id))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Photo-Sets vorhanden."})]})]})]}),g.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:[g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Inkl. Dateien aus ",g.jsx("span",{className:"font-medium",children:"/done/keep/"})]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx(Zt,{size:"sm",variant:"secondary",disabled:ue||it<=1,onClick:()=>dt(V=>Math.max(1,V-1)),children:"Zurück"}),g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Seite ",it," / ",bt]}),g.jsx(Zt,{size:"sm",variant:"secondary",disabled:ue||it>=bt,onClick:()=>dt(V=>Math.min(bt,V+1)),children:"Weiter"})]})]}),g.jsx("div",{className:"mt-3",children:ue?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade Downloads…"}):je.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads für dieses Model gefunden."}):g.jsx("div",{className:"grid gap-2",children:vt.map(V=>{const te=Xl(V.output||""),_e=te.startsWith("HOT "),Oe=V.endedAt?Jd(V.endedAt):"—";return g.jsxs("div",{role:i?"button":void 0,tabIndex:i?0:void 0,className:Dn("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?.(V),onKeyDown:tt=>{i&&(tt.key==="Enter"||tt.key===" ")&&i(V)},children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[g.jsx("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white",children:mT(te)||"—"}),_e?g.jsx("span",{className:so("shrink-0 bg-orange-500/10 text-orange-900 ring-orange-200 dark:text-orange-200 dark:ring-orange-400/20"),children:"HOT"}):null]}),g.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:[g.jsxs("span",{children:["Datum: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Oe})]}),g.jsxs("span",{children:["Dauer:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Ww(V.durationSeconds)})]}),g.jsxs("span",{children:["Größe:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:_$(V.sizeBytes)})]})]})]}),g.jsx("div",{className:"shrink-0 flex items-center gap-2",children:g.jsx("span",{onClick:tt=>tt.stopPropagation(),onMouseDown:tt=>tt.stopPropagation(),onKeyDown:tt=>tt.stopPropagation(),children:g.jsx(Aa,{job:V,variant:"table",isHot:_e,isFavorite:!!gt?.favorite,isLiked:gt?.liked===!0,isWatching:!!gt?.watching,onToggleHot:vi,onDelete:ei,order:["hot","delete"],className:"flex items-center"})})})]},`${V.id}-${te}`)})})})]}),g.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:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Laufende Jobs"}),g.jsx("div",{className:"mt-2",children:ie?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade…"}):jt.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Jobs."}):g.jsx("div",{className:"grid gap-2",children:jt.map(V=>g.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:g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"break-words line-clamp-2 font-medium text-gray-900 dark:text-white",children:Xl(V.output||"")}),g.jsxs("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:["Start:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Jd(V.startedAt)})]})]}),i?g.jsx(Zt,{size:"sm",variant:"secondary",className:"shrink-0",onClick:()=>i(V),children:"Öffnen"}):null]})},V.id))})})]})]}),g.jsx(Wx,{open:!!ee,onClose:()=>he(null),title:ee?.alt||"Bild",width:"max-w-4xl",footer:g.jsxs("div",{className:"flex items-center justify-end gap-2",children:[ee?.src?g.jsxs("a",{href:ee.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:[g.jsx(Ty,{className:"size-4"}),"In neuem Tab"]}):null,g.jsx(Zt,{variant:"secondary",onClick:()=>he(null),children:"Schließen"})]}),children:g.jsx("div",{className:"grid place-items-center",children:ee?.src?g.jsx("img",{src:ee.src,alt:ee.alt||"",className:Dn("max-h-[80vh] w-auto max-w-full rounded-xl object-contain",Fv(a))}):null})})]})}const Pm=s=>Math.max(0,Math.min(1,s));function Bm(s){return s==="good"?"bg-emerald-500":s==="warn"?"bg-amber-500":"bg-red-500"}function N$(s){return s==null?"–":`${Math.round(s)}ms`}function Xw(s){return s==null?"–":`${Math.round(s)}%`}function Uv(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 O$(s=1e3){const[e,t]=Vt.useState(null);return Vt.useEffect(()=>{let i=0,n=performance.now(),r=0,a=!0,u=!1;const c=y=>{if(!a||!u)return;r+=1;const v=y-n;if(v>=s){const b=Math.round(r*1e3/v);t(b),r=0,n=y}i=requestAnimationFrame(c)},d=()=>{a&&(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),()=>{a=!1,document.removeEventListener("visibilitychange",p),f()}},[s]),e}function Qw({mode:s="inline",className:e,pollMs:t=3e3}){const i=O$(1e3),[n,r]=Vt.useState(null),[a,u]=Vt.useState(null),[c,d]=Vt.useState(null),[f,p]=Vt.useState(null),[y,v]=Vt.useState(null),b=5*1024*1024*1024,_=8*1024*1024*1024,E=Vt.useRef(!1);Vt.useEffect(()=>{const J=`/api/perf/stream?ms=${encodeURIComponent(String(t))}`,ue=rR(J,"perf",se=>{const q=typeof se?.cpuPercent=="number"?se.cpuPercent:null,Y=typeof se?.diskFreeBytes=="number"?se.diskFreeBytes:null,ie=typeof se?.diskTotalBytes=="number"?se.diskTotalBytes:null,Q=typeof se?.diskUsedPercent=="number"?se.diskUsedPercent:null;u(q),d(Y),p(ie),v(Q);const oe=typeof se?.serverMs=="number"?se.serverMs:null;r(oe!=null?Math.max(0,Date.now()-oe):null)});return()=>ue()},[t]);const L=n==null?"bad":n<=120?"good":n<=300?"warn":"bad",I=i==null?"bad":i>=55?"good":i>=30?"warn":"bad",R=a==null?"bad":a<=60?"good":a<=85?"warn":"bad",$=Pm((n??999)/500),P=Pm((i??0)/60),B=Pm((a??0)/100),O=c!=null&&f!=null&&f>0?c/f:null,H=y??(O!=null?(1-O)*100:null),D=Pm((H??0)/100);c==null?E.current=!1:E.current?c>=_&&(E.current=!1):c<=b&&(E.current=!0);const M=c==null||E.current||O==null?"bad":O>=.15?"good":O>=.07?"warn":"bad",W=c==null?"Disk: –":`Free: ${Uv(c)} / Total: ${Uv(f)} · Used: ${Xw(H)}`,K=s==="floating"?"fixed bottom-4 right-4 z-[80]":"flex items-center";return g.jsx("div",{className:`${K} ${e??""}`,children:g.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:[g.jsxs("div",{className:"flex items-center gap-2",title:W,children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Disk"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Bm(M)}`,style:{width:`${Math.round(D*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-11 tabular-nums text-gray-900 dark:text-gray-100",children:Uv(c)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Ping"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Bm(L)}`,style:{width:`${Math.round($*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:N$(n)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"FPS"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Bm(I)}`,style:{width:`${Math.round(P*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-8 tabular-nums text-gray-900 dark:text-gray-100",children:i??"–"})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"CPU"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Bm(R)}`,style:{width:`${Math.round(B*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:Xw(a)})]})]})})}function M$(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=>{a||(u(),t=window.setTimeout(()=>{f()},p))},f=async()=>{if(!a)try{const p=(s.getModels?.()??[]).map(W=>String(W||"").trim()).filter(Boolean),v=(s.getShow?.()??[]).map(W=>String(W||"").trim()).filter(Boolean).slice().sort(),b=p.slice().sort(),_=b.length===0&&!!s.fetchAllWhenNoModels;if(b.length===0&&!_){c();const W={enabled:r?.enabled??!1,rooms:[]};r=W,s.onData(W);const K=document.hidden?Math.max(15e3,e):e;d(K);return}const E=_?[]:b,L=`${v.join(",")}|${_?"__ALL__":E.join(",")}`,I=L;n=L,c();const R=new AbortController;i=R;const P=_?[[]]:M$(E,350);let B=[],O=!1,H=0,D=!1;for(const W of P){if(R.signal.aborted||I!==n||a)return;const K=await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:W,show:v,refresh:!1}),signal:R.signal,cache:"no-store"});if(!K.ok)continue;D=!0;const J=await K.json();O=O||!!J?.enabled,B.push(...Array.isArray(J?.rooms)?J.rooms:[]);const ue=Number(J?.total??0);Number.isFinite(ue)&&ue>H&&(H=ue)}if(!D){const W=document.hidden?Math.max(15e3,e):e;d(W);return}const M={enabled:O,rooms:P$(B),total:H};if(R.signal.aborted||I!==n||a)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(),()=>{a=!0,u(),c()}}async function jv(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 Jw(s,e,t,i){const n=`/api/generated/cover?category=${encodeURIComponent(s)}`,r=e?`&v=${e}`:"",a=t?"&refresh=1":"",u=i&&i.trim()?`&model=${encodeURIComponent(i.trim())}`:"";return`${n}${r}${a}${u}`}function eA(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(t=>t.trim()).filter(Boolean);return Array.from(new Set(e))}function fR(s){return String(s||"").replaceAll("\\","/").split("/").pop()||""}function mR(s){return s.toUpperCase().startsWith("HOT ")?s.slice(4).trim():s}function B$(s){const e=mR(fR(s||""));return e?e.replace(/\.[^.]+$/,""):""}const F$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function $v(s){const t=mR(fR(s)).replace(/\.[^.]+$/,""),i=t.match(F$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n).trim():t?t.trim():null}function U$(s){const e=B$(s);return e?`/generated/meta/${encodeURIComponent(e)}/thumbs.jpg`:null}async function j$(s,e,t,i){const n=(t||"").trim(),r=`/api/generated/cover?category=${encodeURIComponent(s)}&src=${encodeURIComponent(e)}`+(n?`&model=${encodeURIComponent(n)}`:"")+"&refresh=1";await fetch(r,{method:"GET",cache:"no-store"})}function $$(){const[s,e]=w.useState([]),[t,i]=w.useState(!1),[n,r]=w.useState(null),[a,u]=w.useState(()=>Date.now()),[c,d]=w.useState({}),[f,p]=w.useState(!1),[y,v]=w.useState(null),[b,_]=w.useState({}),E=w.useRef(null),L=w.useRef({}),I=w.useCallback((O,H)=>{const D={};for(const W of Array.isArray(O)?O:[]){const K=String(W?.modelKey??"").trim().toLowerCase();if(!K)continue;const J=eA(W?.tags).map(ue=>ue.toLowerCase());J.length&&(D[K]=J)}const M={};for(const W of Array.isArray(H)?H:[]){const K=String(W?.output??"");if(!K)continue;const J=($v(K)||"").trim().toLowerCase();if(!J)continue;const ue=D[J];if(!(!ue||ue.length===0))for(const se of ue)se&&(M[se]||(M[se]=[]),M[se].push(K))}for(const[W,K]of Object.entries(M))M[W]=Array.from(new Set(K));L.current=M},[]),R=w.useCallback(O=>{const H=String(O||"").trim();if(H){try{localStorage.setItem("finishedDownloads_pendingTags",JSON.stringify([H]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"finished"}})),window.dispatchEvent(new CustomEvent("finished-downloads:tag-filter",{detail:{tags:[H],mode:"replace"}}))}},[]),$=w.useCallback(O=>{const H=String(O||"").trim();if(H){try{localStorage.setItem("models_pendingTags",JSON.stringify([H]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"models"}})),window.dispatchEvent(new CustomEvent("models:set-tag-filter",{detail:{tags:[H]}}))}},[]),P=w.useCallback(async()=>{E.current?.abort();const O=new AbortController;E.current=O,i(!0),r(null);try{const[H,D]=await Promise.all([jv("/api/models/list",{cache:"no-store",signal:O.signal}),jv("/api/record/done?page=1&pageSize=2000&sort=completed_desc",{cache:"no-store",signal:O.signal})]),M=Array.isArray(D?.items)?D.items:Array.isArray(D)?D:[];I(Array.isArray(H)?H:[],M);const W=new Map;for(const q of Array.isArray(H)?H:[])for(const Y of eA(q?.tags)){const ie=Y.toLowerCase();W.set(ie,(W.get(ie)??0)+1)}const K=L.current||{},J=Array.from(W.entries()).map(([q,Y])=>({tag:q,modelsCount:Y,downloadsCount:(K[q]||[]).length})).sort((q,Y)=>q.tag.localeCompare(Y.tag,void 0,{sensitivity:"base"}));let ue=new Map;try{const q=await jv("/api/generated/coverinfo/list",{cache:"no-store",signal:O.signal});for(const Y of Array.isArray(q)?q:[]){const ie=String(Y?.category??"").trim().toLowerCase();ie&&ue.set(ie,Y)}}catch{}const se={};for(const q of J){const ie=(K[q.tag]||[])[0]||"";let Q=ie?$v(ie):null;if(!Q){const oe=ue.get(q.tag);oe?.hasCover&&oe.model?.trim()&&(Q=oe.model.trim())}Q&&(se[q.tag]=Q)}_(se),e(J),u(Date.now())}catch(H){if(H?.name==="AbortError")return;r(H?.message??String(H)),e([]),L.current={},_({})}finally{E.current===O&&(E.current=null,i(!1))}},[I]);w.useEffect(()=>(P(),()=>{E.current?.abort()}),[P]);const B=w.useCallback(async()=>{if(!f){p(!0),r(null),v({done:0,total:s.length});try{const O=L.current||{},H=await Promise.all(s.map(async M=>{try{const W=O[M.tag]||[],K=W.length?W[Math.floor(Math.random()*W.length)]:"",J=K?U$(K):null;if(J){const ie=K?$v(K):null;return await j$(M.tag,J,ie,!0),_(Q=>{const oe={...Q};return ie?.trim()?oe[M.tag]=ie.trim():delete oe[M.tag],oe}),{tag:M.tag,ok:!0,status:200,text:""}}const ue=b[M.tag]??"",se=await fetch(Jw(M.tag,Date.now(),!0,ue),{method:"GET",cache:"no-store"}),q=se.ok?"":await se.text().catch(()=>""),Y=se.ok||se.status===404;return{tag:M.tag,ok:Y,status:se.status,text:q}}catch(W){return{tag:M.tag,ok:!1,status:0,text:W?.message??String(W)}}finally{v(W=>W&&{...W,done:Math.min(W.total,W.done+1)})}})),D=H.filter(M=>!M.ok&&M.status!==404);if(D.length){console.warn("Cover renew failed:",D.slice(0,20));const M=D.slice(0,8).map(W=>`${W.tag} (${W.status||"ERR"})`).join(", ");r(`Covers fehlgeschlagen: ${D.length}/${H.length} — z.B.: ${M}`)}else r(null)}finally{u(Date.now()),p(!1),setTimeout(()=>v(null),400)}}},[s,f]);return g.jsxs(Ca,{header:g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Kategorien ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",s.length,")"]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[y?g.jsxs("div",{className:"hidden sm:flex items-center gap-2 mr-2",children:[g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300 tabular-nums",children:["Covers: ",y.done,"/",y.total]}),g.jsx("div",{className:"h-2 w-28 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:"h-full bg-indigo-500",style:{width:y.total>0?`${Math.round(y.done/y.total*100)}%`:"0%"}})})]}):null,g.jsx(Zt,{variant:"secondary",size:"md",onClick:B,disabled:t||f,children:"Cover erneuern"}),g.jsx(Zt,{variant:"secondary",size:"md",onClick:P,disabled:t||f,children:"Aktualisieren"})]})]}),grayBody:!0,children:[n?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null,s.length===0&&!t?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Kategorien/Tags gefunden."}):null,g.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:s.map(O=>{const H=b[O.tag]??null,D=Jw(O.tag,a,!1),M=c[O.tag]==="ok",W=c[O.tag]==="error";return g.jsxs("button",{type:"button",onClick:()=>R(O.tag),className:mi("group text-left rounded-2xl overflow-hidden transition","bg-white/70 dark:bg-white/[0.06]","border border-gray-200/70 dark:border-white/10","shadow-sm hover:shadow-md","hover:-translate-y-[1px]","hover:bg-white dark:hover:bg-white/[0.09]","focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-gray-950"),title:"In FinishedDownloads öffnen (Tag-Filter setzen)",children:[g.jsx("div",{className:"relative w-full overflow-hidden aspect-[16/9] bg-gray-100/70 dark:bg-white/5",children:W?g.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2",children:[g.jsx("div",{className:"absolute inset-0 opacity-70",style:{background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,0.25), transparent 55%),radial-gradient(circle at 70% 80%, rgba(14,165,233,0.18), transparent 55%)"}}),g.jsxs("div",{className:"relative z-10 rounded-xl bg-white/80 dark:bg-black/30 px-3 py-2.5 shadow-sm ring-1 ring-black/5 dark:ring-white/10 backdrop-blur-md",children:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Cover nicht verfügbar"}),H?g.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-700 dark:text-gray-300",children:["Model: ",g.jsx("span",{className:"font-semibold",children:H})]}):null,g.jsx("div",{className:"mt-1 flex justify-center",children:g.jsx("span",{className:`text-[11px] inline-flex items-center rounded-full bg-indigo-50 px-2 py-1 font-semibold text-indigo-700 ring-1 ring-indigo-100 hover:bg-indigo-100\r - dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20 dark:hover:bg-indigo-500/20`,onClick:K=>{K.preventDefault(),K.stopPropagation(),d(J=>{const ue={...J};return delete ue[O.tag],ue}),u(Date.now())},children:"Retry"})})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 z-[1] pointer-events-none",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.10), rgba(255,255,255,0) 35%),linear-gradient(to top, rgba(0,0,0,0.35), rgba(0,0,0,0) 45%)"}}),g.jsx("img",{src:D,alt:"","aria-hidden":"true",className:"absolute inset-0 z-0 h-full w-full object-cover blur-xl scale-110 opacity-60",loading:"lazy"}),g.jsx("img",{src:D,alt:O.tag,className:"absolute inset-0 z-0 h-full w-full object-contain",loading:"lazy",onLoad:()=>d(K=>({...K,[O.tag]:"ok"})),onError:()=>d(K=>({...K,[O.tag]:"error"}))}),M&&H?g.jsx("div",{className:"absolute left-3 bottom-3 z-10 max-w-[calc(100%-24px)]",children:g.jsx("div",{className:mi("truncate rounded-full px-2.5 py-1 text-[11px] font-semibold","bg-black/40 text-white backdrop-blur-md","ring-1 ring-white/15"),children:H})}):null]})}),g.jsx("div",{className:"px-4 py-3.5",children:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"font-semibold text-gray-900 dark:text-white truncate tracking-tight",children:O.tag}),g.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[g.jsxs("span",{role:"button",tabIndex:0,className:mi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap","overflow-hidden","bg-indigo-50 text-indigo-700 ring-1 ring-indigo-100","dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20","cursor-pointer"),title:"FinishedDownloads nach diesem Tag filtern",onClick:K=>{K.preventDefault(),K.stopPropagation(),R(O.tag)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),R(O.tag))},children:[g.jsx("span",{className:"shrink-0",children:O.downloadsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Downloads"})]}),g.jsxs("span",{role:"button",tabIndex:0,className:mi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap overflow-hidden","bg-gray-50 text-gray-700 ring-1 ring-gray-200","dark:bg-white/5 dark:text-gray-200 dark:ring-white/10","cursor-pointer"),title:"Models nach diesem Tag filtern",onClick:K=>{K.preventDefault(),K.stopPropagation(),$(O.tag)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),$(O.tag))},children:[g.jsx("span",{className:"shrink-0",children:O.modelsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Models"})]})]})]}),g.jsx("span",{"aria-hidden":"true",className:mi("shrink-0 mt-0.5 text-gray-400 dark:text-gray-500","transition-transform group-hover:translate-x-[1px]"),children:"→"})]})})]},O.tag)})})]})}async function eh(s,e){const t=await fetch(s,{credentials:"include",...e});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function H$(){try{const e=new URL(window.location.href).searchParams.get("next")||"/";return!e.startsWith("/")||e.startsWith("/login")?"/":e}catch{return"/"}}function G$({onLoggedIn:s}){const e=w.useMemo(()=>H$(),[]),[t,i]=w.useState(""),[n,r]=w.useState(""),[a,u]=w.useState(""),[c,d]=w.useState(!1),[f,p]=w.useState(null),[y,v]=w.useState("login"),[b,_]=w.useState(null),[E,L]=w.useState(null),[I,R]=w.useState(null);w.useEffect(()=>{let H=!1;return(async()=>{try{const M=await eh("/api/auth/me",{cache:"no-store"});if(H)return;if(M?.authenticated){M?.totpConfigured?window.location.assign(e||"/"):(v("setup"),B());return}if(M?.pending2fa){v("verify");return}v("login")}catch{}})(),()=>{H=!0}},[e]);const $=async()=>{d(!0),p(null);try{if((await eh("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})}))?.totpRequired){v("verify");return}const D=await eh("/api/auth/me",{cache:"no-store"});if(D?.authenticated&&!D?.totpConfigured){v("setup"),await B();return}s&&await s(),window.location.assign(e||"/")}catch(H){p(H?.message??String(H))}finally{d(!1)}},P=async()=>{d(!0),p(null);try{await eh("/api/auth/2fa/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:a})}),s&&await s(),window.location.assign(e||"/")}catch(H){p(H?.message??String(H))}finally{d(!1)}},B=async()=>{p(null),R(null);try{const H=await eh("/api/auth/2fa/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),D=(H?.otpauth??"").trim();if(!D)throw new Error("2FA Setup fehlgeschlagen (keine otpauth URL).");_(D),L((H?.secret??"").trim()||null),R("Scan den QR-Code in deiner Authenticator-App und bestätige danach mit dem 6-stelligen Code.")}catch(H){p(H?.message??String(H))}},O=H=>{H.key==="Enter"&&(H.preventDefault(),!c&&(y==="verify"||y==="setup"?P():$()))};return g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsx("div",{className:"relative grid min-h-[100dvh] place-items-center px-4",children:g.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-gray-200/70 bg-white/80 p-6 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Recorder Login"}),g.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Bitte melde dich an, um fortzufahren."})]}),g.jsxs("div",{className:"mt-5 space-y-3",children:[y==="login"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Username"}),g.jsx("input",{value:t,onChange:H=>i(H.target.value),onKeyDown:O,autoComplete:"username",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",placeholder:"admin",disabled:c})]}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Passwort"}),g.jsx("input",{type:"password",value:n,onChange:H=>r(H.target.value),onKeyDown:O,autoComplete:"current-password",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",placeholder:"••••••••••",disabled:c})]}),g.jsx(Zt,{variant:"primary",className:"w-full rounded-lg",disabled:c||!t.trim()||!n,onClick:()=>{$()},children:c?"Login…":"Login"})]}):y==="verify"?g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:"2FA ist aktiv – bitte gib den Code aus deiner Authenticator-App ein."}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{htmlFor:"totp",className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"2FA Code"}),g.jsx("input",{id:"totp",name:"totp","aria-label":"totp",type:"text",value:a,onChange:H=>u(H.target.value),onKeyDown:O,autoComplete:"one-time-code",inputMode:"numeric",pattern:"[0-9]*",maxLength:6,enterKeyHint:"done",autoCapitalize:"none",autoCorrect:"off",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",placeholder:"123456",disabled:c})]}),g.jsxs("div",{className:"flex gap-2",children:[g.jsx(Zt,{variant:"secondary",className:"flex-1 rounded-lg",disabled:c,onClick:()=>{_(null),L(null),R(null)},children:"Zurück"}),g.jsx(Zt,{variant:"primary",className:"flex-1 rounded-lg",disabled:c||a.trim().length<6,onClick:()=>{P()},children:c?"Prüfe…":"Bestätigen"})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2 text-sm text-indigo-900 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-200",children:"2FA ist noch nicht eingerichtet – bitte richte es jetzt ein (empfohlen)."}),g.jsxs("div",{className:"space-y-2 text-sm text-gray-700 dark:text-gray-200",children:[g.jsx("div",{children:"1) Öffne deine Authenticator-App und füge einen neuen Account hinzu."}),g.jsx("div",{children:"2) Scanne den QR-Code oder verwende den Secret-Key."})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white/70 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"QR / Setup"}),b?g.jsx("div",{className:"mt-2 flex items-center justify-center",children:g.jsx("img",{alt:"2FA QR Code",className:"h-44 w-44 rounded bg-white p-2",src:`https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(b)}`})}):g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-300",children:"QR wird geladen…"}),E?g.jsxs("div",{className:"mt-3",children:[g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Secret (manuell):"}),g.jsx("div",{className:"mt-1 select-all break-all rounded bg-gray-100 px-2 py-1 text-xs font-mono text-gray-900 dark:bg-white/10 dark:text-gray-100",children:E})]}):null,I?g.jsx("div",{className:"mt-3 text-xs text-gray-600 dark:text-gray-300",children:I}):null,g.jsx("div",{className:"mt-3",children:g.jsx(Zt,{variant:"secondary",className:"w-full rounded-lg",disabled:c,onClick:()=>{B()},title:"Setup-Infos neu laden",children:b?"QR/Setup erneut laden":"QR/Setup laden"})})]}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{htmlFor:"totp",className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"2FA Code (zum Aktivieren)"}),g.jsx("input",{id:"totp-setup",name:"totp","aria-label":"totp",type:"text",value:a,onChange:H=>u(H.target.value),onKeyDown:O,autoComplete:"one-time-code",inputMode:"numeric",pattern:"[0-9]*",maxLength:6,enterKeyHint:"done",autoCapitalize:"none",autoCorrect:"off",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",placeholder:"123456",disabled:c})]}),g.jsxs("div",{className:"flex gap-2",children:[g.jsx(Zt,{variant:"secondary",className:"flex-1 rounded-lg",disabled:c,onClick:()=>{s&&s(),window.location.assign(e||"/")},title:"Ohne 2FA fortfahren (nicht empfohlen)",children:"Später"}),g.jsx(Zt,{variant:"primary",className:"flex-1 rounded-lg",disabled:c||a.trim().length<6,onClick:()=>{P()},children:c?"Aktiviere…":"2FA aktivieren"})]})]}),f?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:f}),g.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:()=>p(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null]})]})})]})}const Hv="record_cookies";function Fm(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 $s(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 tA={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:3e3};function Xm(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 ql(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g)){const i=Xm(t);if(i)return i}return null}function iA(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 Xs=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function V$(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function z$(s){return s.startsWith("HOT ")?s.slice(4):s}const q$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function th(s){const t=z$(Xs(s)).replace(/\.[^.]+$/,""),i=t.match(q$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function K$(){const[s,e]=w.useState(!1),[t,i]=w.useState(!1),n=w.useCallback(async()=>{try{const X=await $s("/api/auth/me",{cache:"no-store"});i(!!X?.authenticated)}catch{i(!1)}finally{e(!0)}},[]),r=w.useCallback(async()=>{try{await fetch("/api/auth/logout",{method:"POST",cache:"no-store"})}catch{}finally{i(!1),e(!0),dt(null),nt(!1),ut("running"),Je(null),Qe(!1),Ze(null),I([]),$([]),H(0),B(1),F({}),M(0),_e({}),Oe.current={},Ut([]),vi({}),K(0),E("")}},[]);w.useEffect(()=>{n()},[n]);const a=UA(),[u,c]=w.useState(!1);w.useEffect(()=>{const X=window,ae=typeof X.requestIdleCallback=="function"?X.requestIdleCallback(()=>c(!0),{timeout:1500}):window.setTimeout(()=>c(!0),800);return()=>{typeof X.cancelIdleCallback=="function"?X.cancelIdleCallback(ae):window.clearTimeout(ae)}},[]);const d=8,f="finishedDownloads_sort",[p,y]=w.useState(()=>{try{return window.localStorage.getItem(f)||"completed_desc"}catch{return"completed_desc"}});w.useEffect(()=>{try{window.localStorage.setItem(f,p)}catch{}},[p]);const[v,b]=w.useState(null),[_,E]=w.useState(""),[L,I]=w.useState([]),[R,$]=w.useState([]),[P,B]=w.useState(1),[O,H]=w.useState(0),[D,M]=w.useState(0),[W,K]=w.useState(0),[J,ue]=w.useState(()=>Date.now()),[se,q]=w.useState(()=>Date.now());w.useEffect(()=>{const X=window.setInterval(()=>q(Date.now()),1e3);return()=>window.clearInterval(X)},[]);const Y=X=>(X||"").toLowerCase().trim(),ie=X=>{const ae=Math.max(0,Math.floor(X/1e3));if(ae<2)return"gerade eben";if(ae<60)return`vor ${ae} Sekunden`;const re=Math.floor(ae/60);if(re===1)return"vor 1 Minute";if(re<60)return`vor ${re} Minuten`;const xe=Math.floor(re/60);return xe===1?"vor 1 Stunde":`vor ${xe} Stunden`},Q=w.useMemo(()=>{const X=se-J;return`(zuletzt aktualisiert: ${ie(X)})`},[se,J]),[oe,F]=w.useState({}),ee=w.useCallback(X=>{const ae={};for(const re of Array.isArray(X)?X:[]){const xe=(re?.modelKey||"").trim().toLowerCase();if(!xe)continue;const we=st=>(st.favorite?4:0)+(st.liked===!0?2:0)+(st.watching?1:0),He=ae[xe];(!He||we(re)>=we(He))&&(ae[xe]=re)}return ae},[]),he=w.useCallback(async()=>{try{const X=await $s("/api/models/list",{cache:"no-store"});F(ee(Array.isArray(X)?X:[])),ue(Date.now())}catch{}},[ee]),[be,pe]=w.useState(null),Ce=w.useRef(null),[Re,Ze]=w.useState(null);w.useEffect(()=>{const X=ae=>{let we=(ae.detail?.modelKey??"").trim().replace(/^https?:\/\//i,"");we.includes("/")&&(we=we.split("/").filter(Boolean).pop()||we),we.includes(":")&&(we=we.split(":").pop()||we),we=we.trim().toLowerCase(),we&&Ze(we)};return window.addEventListener("open-model-details",X),()=>window.removeEventListener("open-model-details",X)},[]);const Ge=w.useCallback(X=>{const ae=Date.now(),re=Ce.current;if(!re){Ce.current={ts:ae,list:[X]};return}re.ts=ae;const xe=re.list.findIndex(we=>we.id===X.id);xe>=0?re.list[xe]=X:re.list.unshift(X)},[]);w.useEffect(()=>{he();const X=ae=>{const xe=ae?.detail??{},we=xe?.model;if(we&&typeof we=="object"){const He=String(we.modelKey??"").toLowerCase().trim();He&&F(st=>({...st,[He]:we}));try{Ge(we)}catch{}pe(st=>st?.id===we.id?we:st),ue(Date.now());return}if(xe?.removed){const He=String(xe?.id??"").trim(),st=String(xe?.modelKey??"").toLowerCase().trim();st&&F(Xe=>{const{[st]:kt,...Tt}=Xe;return Tt}),He&&pe(Xe=>Xe?.id===He?null:Xe),ue(Date.now());return}he()};return window.addEventListener("models-changed",X),()=>window.removeEventListener("models-changed",X)},[he,Ge]);const[it,dt]=w.useState(null),[ot,nt]=w.useState(!1),[ft,gt]=w.useState(!1),[je,bt]=w.useState({}),[vt,jt]=w.useState(!1),[We,ut]=w.useState("running"),[ge,Je]=w.useState(null),[Ye,Qe]=w.useState(!1),[mt,ct]=w.useState(0),et=w.useCallback(()=>ct(X=>X+1),[]),Gt=w.useRef(null),Jt=w.useCallback(()=>{et(),Gt.current&&window.clearTimeout(Gt.current),Gt.current=window.setTimeout(()=>et(),3500)},[et]),[It,Ft]=w.useState(tA),$t=w.useRef(It);w.useEffect(()=>{$t.current=It},[It]);const Ke=!!It.autoAddToDownloadList,Lt=!!It.autoStartAddedDownloads,[Qt,Ut]=w.useState([]),[ci,vi]=w.useState({}),ei=w.useRef(!1),Bi=w.useRef({}),yt=w.useRef([]);w.useEffect(()=>{ei.current=ot},[ot]),w.useEffect(()=>{Bi.current=je},[je]),w.useEffect(()=>{yt.current=L},[L]);const z=w.useRef(null),V=w.useRef(""),[te,_e]=w.useState({}),Oe=w.useRef({});w.useEffect(()=>{Oe.current=te},[te]);const tt=w.useCallback(X=>{const ae=String(X?.host??"").toLowerCase(),re=String(X?.input??"").toLowerCase();return ae.includes("chaturbate")||re.includes("chaturbate.com")},[]),Ot=w.useMemo(()=>{const X=new Set;for(const ae of Object.values(oe)){if(!tt(ae))continue;const re=Y(String(ae?.modelKey??""));re&&X.add(re)}return Array.from(X)},[oe,tt]),xi=w.useRef(oe);w.useEffect(()=>{xi.current=oe},[oe]);const Vi=w.useRef(ci);w.useEffect(()=>{Vi.current=ci},[ci]);const zi=w.useRef(Ot);w.useEffect(()=>{zi.current=Ot},[Ot]);const Oi=w.useRef(We);w.useEffect(()=>{Oi.current=We},[We]);const Ai=w.useCallback(async(X,ae)=>{const re=Xm(X);if(!re)return!1;const xe=!!ae?.silent;xe||dt(null);const we=iA(re);if(!we)return xe||dt("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;const He=Bi.current;if(we==="chaturbate"&&!ss(He))return xe||dt('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(yt.current.some(Xe=>String(Xe.status||"").toLowerCase()!=="running"||Xe.endedAt?!1:Xm(String(Xe.sourceUrl||""))===re))return!0;if(we==="chaturbate"&&$t.current.useChaturbateApi)try{const Xe=await $s("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:re})}),kt=String(Xe?.modelKey??"").trim().toLowerCase();if(kt){if(ei.current)return vi(lt=>({...lt||{},[kt]:re})),!0;const Tt=Oe.current[kt],Bt=String(Tt?.current_show??"");if(Tt&&Bt&&Bt!=="public")return vi(lt=>({...lt||{},[kt]:re})),!0}}catch{}else if(ei.current)return z.current=re,!0;if(ei.current)return!1;nt(!0),ei.current=!0;try{const Xe=Object.entries(He).map(([Tt,Bt])=>`${Tt}=${Bt}`).join("; "),kt=await $s("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:re,cookie:Xe})});return I(Tt=>[kt,...Tt]),yt.current=[kt,...yt.current],!0}catch(Xe){return xe||dt(Xe?.message??String(Xe)),!1}finally{nt(!1),ei.current=!1}},[]);w.useEffect(()=>{let X=!1;const ae=async()=>{try{const we=await $s("/api/settings",{cache:"no-store"});!X&&we&&Ft({...tA,...we})}catch{}},re=()=>{ae()},xe=()=>{ae()};return window.addEventListener("recorder-settings-updated",re),window.addEventListener("focus",xe),document.addEventListener("visibilitychange",xe),ae(),()=>{X=!0,window.removeEventListener("recorder-settings-updated",re),window.removeEventListener("focus",xe),document.removeEventListener("visibilitychange",xe)}},[]),w.useEffect(()=>{let X=!1;const ae=async()=>{try{const xe=await $s("/api/models/meta",{cache:"no-store"}),we=Number(xe?.count??0);!X&&Number.isFinite(we)&&(M(we),ue(Date.now()))}catch{}};ae();const re=window.setInterval(ae,document.hidden?6e4:3e4);return()=>{X=!0,window.clearInterval(re)}},[]);const Ci=w.useMemo(()=>Object.entries(je).map(([X,ae])=>({name:X,value:ae})),[je]),Fi=w.useCallback(X=>{Ce.current=null,pe(null),Je(X),Qe(!1)},[]),Mi=L.filter(X=>{const ae=String(X?.status??"").toLowerCase();return ae==="running"||ae==="postwork"}),Li=w.useMemo(()=>{let X=0;for(const ae of Object.values(oe)){if(!ae?.watching||!tt(ae))continue;const re=Y(String(ae?.modelKey??""));re&&te[re]&&X++}return X},[oe,te,tt]),{onlineFavCount:oi,onlineLikedCount:ti}=w.useMemo(()=>{let X=0,ae=0;for(const re of Object.values(oe)){const xe=Y(String(re?.modelKey??""));xe&&te[xe]&&(re?.favorite&&X++,re?.liked===!0&&ae++)}return{onlineFavCount:X,onlineLikedCount:ae}},[oe,te]),Kt=[{id:"running",label:"Laufende Downloads",count:Mi.length},{id:"finished",label:"Abgeschlossene Downloads",count:O},{id:"models",label:"Models",count:D},{id:"categories",label:"Kategorien"},{id:"settings",label:"Einstellungen"}],Gs=w.useMemo(()=>_.trim().length>0&&!ot,[_,ot]);w.useEffect(()=>{let X=!1;return(async()=>{try{const re=await $s("/api/cookies",{cache:"no-store"}),xe=Fm(re?.cookies);if(X||bt(xe),Object.keys(xe).length===0){const we=localStorage.getItem(Hv);if(we)try{const He=JSON.parse(we),st=Fm(He);Object.keys(st).length>0&&(X||bt(st),await $s("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:st})}))}catch{}}}catch{const re=localStorage.getItem(Hv);if(re)try{const xe=JSON.parse(re);X||bt(Fm(xe))}catch{}}finally{X||jt(!0)}})(),()=>{X=!0}},[]),w.useEffect(()=>{vt&&localStorage.setItem(Hv,JSON.stringify(je))},[je,vt]),w.useEffect(()=>{let X=!1,ae;const re=async()=>{try{const we=await fetch(`/api/record/done?page=1&pageSize=1&withCount=1&sort=${encodeURIComponent(p)}`,{cache:"no-store"});if(!we.ok)return;const He=await we.json().catch(()=>null),st=Number(He?.count??He?.totalCount??0),Xe=Number.isFinite(st)&&st>=0?st:0;X||(H(Xe),ue(Date.now()))}catch{}finally{if(!X){const we=document.hidden?6e4:3e4;ae=window.setTimeout(re,we)}}},xe=()=>{document.hidden||re()};return document.addEventListener("visibilitychange",xe),re(),()=>{X=!0,ae&&window.clearTimeout(ae),document.removeEventListener("visibilitychange",xe)}},[p]),w.useEffect(()=>{const X=Math.max(1,Math.ceil(O/d));P>X&&B(X)},[O,P]),w.useEffect(()=>{let X=!1,ae=null,re=null,xe=!1;const we=Tt=>{const Bt=Array.isArray(Tt)?Tt:[];if(X)return;const lt=yt.current,pt=new Map(lt.map(Dt=>[Dt.id,Dt.status])),Et=new Set(["finished","stopped","failed"]);let Nt=0;for(const Dt of Bt){const ce=pt.get(Dt.id);!ce||ce===Dt.status||Et.has(Dt.status)&&!Et.has(ce)&&Nt++}Nt>0&&(window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:Nt}})),Jt()),I(Bt),yt.current=Bt,Je(Dt=>{if(!Dt)return Dt;const ce=Bt.find(Se=>Se.id===Dt.id);return ce||(Dt.status==="running"?null:Dt)})},He=async()=>{if(!(X||xe)){xe=!0;try{const Tt=await $s("/api/record/list");we(Tt)}catch{}finally{xe=!1}}},st=()=>{re||(re=window.setInterval(He,document.hidden?15e3:5e3))};He(),ae=new EventSource("/api/record/stream");const Xe=Tt=>{try{we(JSON.parse(Tt.data))}catch{}};ae.addEventListener("jobs",Xe),ae.onerror=()=>st();const kt=()=>{document.hidden||He()};return document.addEventListener("visibilitychange",kt),window.addEventListener("hover",kt),()=>{X=!0,re&&window.clearInterval(re),document.removeEventListener("visibilitychange",kt),window.removeEventListener("hover",kt),ae?.removeEventListener("jobs",Xe),ae?.close(),ae=null}},[Jt]),w.useEffect(()=>{if(We!=="finished")return;let X=!1;const ae={current:!1},re=new AbortController,xe=async()=>{if(!(X||ae.current)){ae.current=!0;try{const Xe=await fetch(`/api/record/done?page=${P}&pageSize=${d}&sort=${encodeURIComponent(p)}&withCount=1`,{cache:"no-store",signal:re.signal});if(!Xe.ok)throw new Error(`HTTP ${Xe.status}`);const kt=await Xe.json().catch(()=>null),Tt=Array.isArray(kt?.items)?kt.items:Array.isArray(kt)?kt:[],Bt=typeof kt?.count=="number"?kt.count:typeof kt?.totalCount=="number"?kt.totalCount:Tt.length;X||($(Tt),H(Number.isFinite(Bt)?Bt:Tt.length))}catch{X||($([]),H(0))}finally{ae.current=!1}}};xe();const He=window.setInterval(()=>{document.hidden||xe()},2e4),st=()=>{document.hidden||xe()};return document.addEventListener("visibilitychange",st),()=>{X=!0,re.abort(),window.clearInterval(He),document.removeEventListener("visibilitychange",st)}},[We,P,p]);const qi=w.useCallback(async X=>{try{const ae=typeof X=="number"?X:P,re=await $s(`/api/record/done?page=${ae}&pageSize=${d}&sort=${encodeURIComponent(p)}&withCount=1`,{cache:"no-store"}),xe=Array.isArray(re?.items)?re.items:[],we=Number(re?.count??re?.totalCount??xe.length),He=Number.isFinite(we)&&we>=0?we:xe.length;H(He);const st=Math.max(1,Math.ceil(He/d)),Xe=Math.min(Math.max(1,ae),st);if(Xe!==P&&B(Xe),Xe===ae)$(xe);else{const kt=await $s(`/api/record/done?page=${Xe}&pageSize=${d}&sort=${encodeURIComponent(p)}&withCount=1`,{cache:"no-store"}),Tt=Array.isArray(kt?.items)?kt.items:[];$(Tt)}}catch{}},[P,p]);w.useEffect(()=>{let X=null;try{X=new EventSource("/api/record/done/stream")}catch{return}const ae=()=>{Oi.current==="finished"&&qi()};return X.addEventListener("doneChanged",ae),X.onerror=()=>{},()=>{X?.removeEventListener("doneChanged",ae),X?.close()}},[qi]);function fn(X){const ae=Xm(X);if(!ae)return!1;try{return new URL(ae).hostname.includes("chaturbate.com")}catch{return!1}}function tr(X,ae){const re=Object.fromEntries(Object.entries(X).map(([xe,we])=>[xe.trim().toLowerCase(),we]));for(const xe of ae){const we=re[xe.toLowerCase()];if(we)return we}}function ss(X){const ae=tr(X,["cf_clearance"]),re=tr(X,["sessionid","session_id","sessionId"]);return!!(ae&&re)}async function bi(X){try{await $s(`/api/record/stop?id=${encodeURIComponent(X)}`,{method:"POST"})}catch(ae){a.error("Stop fehlgeschlagen",ae?.message??String(ae))}}w.useEffect(()=>{const X=ae=>{const xe=Number(ae.detail?.delta??0);if(!Number.isFinite(xe)||xe===0){qi();return}H(we=>Math.max(0,we+xe)),qi()};return window.addEventListener("finished-downloads:count-hint",X),()=>window.removeEventListener("finished-downloads:count-hint",X)},[qi]),w.useEffect(()=>{const X=ae=>{const re=ae.detail||{};re.tab==="finished"&&ut("finished"),re.tab==="categories"&&ut("categories"),re.tab==="models"&&ut("models"),re.tab==="running"&&ut("running"),re.tab==="settings"&&ut("settings")};return window.addEventListener("app:navigate-tab",X),()=>window.removeEventListener("app:navigate-tab",X)},[]),w.useEffect(()=>{if(!ge){pe(null),b(null);return}const X=(th(ge.output||"")||"").trim().toLowerCase();b(X||null);const ae=X?oe[X]:void 0;pe(ae??null)},[ge,oe]);async function ks(){return Ai(_)}const Os=w.useCallback(async X=>{const ae=String(X?.sourceUrl??""),re=ql(ae);if(!re)return!1;const xe=await Ai(re,{silent:!0});return xe||a.error("Konnte URL nicht hinzufügen","Start fehlgeschlagen oder URL ungültig."),xe},[Ai,a]),Vs=w.useCallback(async X=>{const ae=Xs(X.output||"");if(ae){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"start"}}));try{const re=await $s(`/api/record/delete?file=${encodeURIComponent(ae)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"success"}})),window.setTimeout(()=>{$(we=>we.filter(He=>Xs(He.output||"")!==ae)),I(we=>we.filter(He=>Xs(He.output||"")!==ae)),Je(we=>we&&Xs(we.output||"")===ae?null:we)},320),window.setTimeout(()=>{qi()},350);const xe=typeof re?.undoToken=="string"?re.undoToken:"";return xe?{undoToken:xe}:{}}catch(re){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"error"}})),a.error("Löschen fehlgeschlagen",re?.message??String(re));return}}},[a,qi]),zs=w.useCallback(async X=>{await Vs(X)},[Vs]),ki=w.useCallback(async X=>{const ae=Xs(X.output||"");if(ae){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"start"}}));try{await $s(`/api/record/keep?file=${encodeURIComponent(ae)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"success"}})),window.setTimeout(()=>{$(re=>re.filter(xe=>Xs(xe.output||"")!==ae)),I(re=>re.filter(xe=>Xs(xe.output||"")!==ae)),Je(re=>re&&Xs(re.output||"")===ae?null:re)},320),qi()}catch(re){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:ae,phase:"error"}})),a.error("Keep fehlgeschlagen",re?.message??String(re));return}}},[We,qi,a]),qs=w.useCallback(async X=>{const ae=Xs(X.output||"");if(ae)try{const re=await $s(`/api/record/toggle-hot?file=${encodeURIComponent(ae)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:rename",{detail:{oldFile:re.oldFile,newFile:re.newFile}}));const xe=we=>V$(we||"",re.newFile);Je(we=>we&&{...we,output:xe(we.output||"")}),$(we=>we.map(He=>He.id===X.id||Xs(He.output||"")===ae?{...He,output:xe(He.output||"")}:He)),I(we=>we.map(He=>He.id===X.id||Xs(He.output||"")===ae?{...He,output:xe(He.output||"")}:He))}catch(re){a.error("Umbenennen fehlgeschlagen",re?.message??String(re))}},[a]);async function ls(X){const ae=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)});if(ae.status===204)return null;if(!ae.ok){const re=await ae.text().catch(()=>"");throw new Error(re||`HTTP ${ae.status}`)}return ae.json()}const ns=w.useCallback(X=>{const ae=Ce.current;!ae||!X||(ae.ts=Date.now(),ae.list=ae.list.filter(re=>re.id!==X))},[]),Di=w.useRef({}),Ms=w.useCallback(async X=>{const ae=Xs(X.output||""),re=!!(ge&&Xs(ge.output||"")===ae),xe=lt=>{try{const pt=String(lt.sourceUrl??lt.SourceURL??""),Et=ql(pt);return Et?new URL(Et).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},we=(th(X.output||"")||"").trim().toLowerCase();if(we){const lt=we;if(Di.current[lt])return;Di.current[lt]=!0;const pt=oe[we]??{id:"",input:"",host:xe(X)||void 0,modelKey:we,watching:!1,favorite:!1,liked:null,isUrl:!1},Et=!pt.favorite,Nt={...pt,modelKey:pt.modelKey||we,favorite:Et,liked:Et?!1:pt.liked};F(Dt=>({...Dt,[we]:Nt})),Ge(Nt),re&&pe(Nt);try{const Dt=await ls({...Nt.id?{id:Nt.id}:{},host:Nt.host||xe(X)||"",modelKey:we,favorite:Et,...Et?{liked:!1}:{}});if(!Dt){F(Se=>{const{[we]:rt,...wt}=Se;return wt}),pt.id&&ns(pt.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:pt.id,modelKey:we}}));return}const ce=Y(Dt.modelKey||we);ce&&F(Se=>({...Se,[ce]:Dt})),Ge(Dt),re&&pe(Dt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Dt}}))}catch(Dt){F(ce=>({...ce,[we]:pt})),Ge(pt),re&&pe(pt),a.error("Favorit umschalten fehlgeschlagen",Dt?.message??String(Dt))}finally{delete Di.current[lt]}return}let He=re?be:null;if(He||(He=await ye(X,{ensure:!0})),!He)return;const st=Y(He.modelKey||He.id||"");if(!st||Di.current[st])return;Di.current[st]=!0;const Xe=He,kt=!Xe.favorite,Tt={...Xe,favorite:kt,liked:kt?!1:Xe.liked},Bt=Y(Xe.modelKey||"");Bt&&F(lt=>({...lt,[Bt]:Tt})),Ge(Tt),re&&pe(Tt);try{const lt=await ls({id:Xe.id,favorite:kt,...kt?{liked:!1}:{}});if(!lt){F(Et=>{const Nt=Y(Xe.modelKey||"");if(!Nt)return Et;const{[Nt]:Dt,...ce}=Et;return ce}),ns(Xe.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Xe.id,modelKey:Xe.modelKey}}));return}const pt=Y(lt.modelKey||"");pt&&F(Et=>({...Et,[pt]:lt})),Ge(lt),re&&pe(lt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:lt}}))}catch(lt){const pt=Y(Xe.modelKey||"");pt&&F(Et=>({...Et,[pt]:Xe})),Ge(Xe),re&&pe(Xe),a.error("Favorit umschalten fehlgeschlagen",lt?.message??String(lt))}finally{delete Di.current[st]}},[a,ge,be,ye,ls,Ge,ns,oe]),mn=w.useCallback(async X=>{const ae=Xs(X.output||""),re=!!(ge&&Xs(ge.output||"")===ae),xe=lt=>{try{const pt=String(lt.sourceUrl??lt.SourceURL??""),Et=ql(pt);return Et?new URL(Et).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},we=(th(X.output||"")||"").trim().toLowerCase();if(we){const lt=we;if(Di.current[lt])return;Di.current[lt]=!0;const pt=oe[we]??{id:"",input:"",host:xe(X)||void 0,modelKey:we,watching:!1,favorite:!1,liked:null,isUrl:!1},Et=pt.liked!==!0,Nt={...pt,modelKey:pt.modelKey||we,liked:Et,favorite:Et?!1:pt.favorite};F(Dt=>({...Dt,[we]:Nt})),Ge(Nt),re&&pe(Nt);try{const Dt=await ls({...Nt.id?{id:Nt.id}:{},host:Nt.host||xe(X)||"",modelKey:we,liked:Et,...Et?{favorite:!1}:{}});if(!Dt){F(Se=>{const{[we]:rt,...wt}=Se;return wt}),pt.id&&ns(pt.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:pt.id,modelKey:we}}));return}const ce=Y(Dt.modelKey||we);ce&&F(Se=>({...Se,[ce]:Dt})),Ge(Dt),re&&pe(Dt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Dt}}))}catch(Dt){F(ce=>({...ce,[we]:pt})),Ge(pt),re&&pe(pt),a.error("Like umschalten fehlgeschlagen",Dt?.message??String(Dt))}finally{delete Di.current[lt]}return}let He=re?be:null;if(He||(He=await ye(X,{ensure:!0})),!He)return;const st=Y(He.modelKey||He.id||"");if(!st||Di.current[st])return;Di.current[st]=!0;const Xe=He,kt=Xe.liked!==!0,Tt={...Xe,liked:kt,favorite:kt?!1:Xe.favorite},Bt=Y(Xe.modelKey||"");Bt&&F(lt=>({...lt,[Bt]:Tt})),Ge(Tt),re&&pe(Tt);try{const lt=kt?await ls({id:Xe.id,liked:!0,favorite:!1}):await ls({id:Xe.id,liked:!1});if(!lt){F(Et=>{const Nt=Y(Xe.modelKey||"");if(!Nt)return Et;const{[Nt]:Dt,...ce}=Et;return ce}),ns(Xe.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Xe.id,modelKey:Xe.modelKey}}));return}const pt=Y(lt.modelKey||"");pt&&F(Et=>({...Et,[pt]:lt})),Ge(lt),re&&pe(lt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:lt}}))}catch(lt){const pt=Y(Xe.modelKey||"");pt&&F(Et=>({...Et,[pt]:Xe})),Ge(Xe),re&&pe(Xe),a.error("Like umschalten fehlgeschlagen",lt?.message??String(lt))}finally{delete Di.current[st]}},[a,ge,be,ye,ls,Ge,ns,oe]),rs=w.useCallback(async X=>{const ae=Xs(X.output||""),re=!!(ge&&Xs(ge.output||"")===ae),xe=lt=>{try{const pt=String(lt.sourceUrl??lt.SourceURL??""),Et=ql(pt);return Et?new URL(Et).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},we=(th(X.output||"")||"").trim().toLowerCase();if(we){const lt=we;if(Di.current[lt])return;Di.current[lt]=!0;const pt=oe[we]??{id:"",input:"",host:xe(X)||void 0,modelKey:we,watching:!1,favorite:!1,liked:null,isUrl:!1},Et=!pt.watching,Nt={...pt,modelKey:pt.modelKey||we,watching:Et};F(Dt=>({...Dt,[we]:Nt})),Ge(Nt),re&&pe(Nt);try{const Dt=await ls({...Nt.id?{id:Nt.id}:{},host:Nt.host||xe(X)||"",modelKey:we,watched:Et});if(!Dt){F(Se=>{const{[we]:rt,...wt}=Se;return wt}),pt.id&&ns(pt.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:pt.id,modelKey:we}}));return}const ce=Y(Dt.modelKey||we);ce&&F(Se=>({...Se,[ce]:Dt})),Ge(Dt),re&&pe(Dt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Dt}}))}catch(Dt){F(ce=>({...ce,[we]:pt})),Ge(pt),re&&pe(pt),a.error("Watched umschalten fehlgeschlagen",Dt?.message??String(Dt))}finally{delete Di.current[lt]}return}let He=re?be:null;if(He||(He=await ye(X,{ensure:!0})),!He)return;const st=Y(He.modelKey||He.id||"");if(!st||Di.current[st])return;Di.current[st]=!0;const Xe=He,kt=!Xe.watching,Tt={...Xe,watching:kt},Bt=Y(Xe.modelKey||"");Bt&&F(lt=>({...lt,[Bt]:Tt})),Ge(Tt),re&&pe(Tt);try{const lt=await ls({id:Xe.id,watched:kt});if(!lt){F(Et=>{const Nt=Y(Xe.modelKey||"");if(!Nt)return Et;const{[Nt]:Dt,...ce}=Et;return ce}),ns(Xe.id),re&&pe(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Xe.id,modelKey:Xe.modelKey}}));return}const pt=Y(lt.modelKey||"");pt&&F(Et=>({...Et,[pt]:lt})),Ge(lt),re&&pe(lt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:lt}}))}catch(lt){const pt=Y(Xe.modelKey||"");pt&&F(Et=>({...Et,[pt]:Xe})),Ge(Xe),re&&pe(Xe),a.error("Watched umschalten fehlgeschlagen",lt?.message??String(lt))}finally{delete Di.current[st]}},[a,ge,be,ye,ls,Ge,ns,oe]);async function ye(X,ae){const re=!!ae?.ensure,xe=Tt=>{const Bt=Date.now(),lt=Ce.current;if(!lt){Ce.current={ts:Bt,list:[Tt]};return}lt.ts=Bt;const pt=lt.list.findIndex(Et=>Et.id===Tt.id);pt>=0?lt.list[pt]=Tt:lt.list.unshift(Tt)},we=async Tt=>{if(!Tt)return null;const Bt=Tt.trim().toLowerCase();if(!Bt)return null;const lt=oe[Bt];if(lt)return xe(lt),lt;if(re){let ce;try{const rt=X.sourceUrl??X.SourceURL??"",wt=ql(rt);wt&&(ce=new URL(wt).hostname.replace(/^www\./i,"").toLowerCase())}catch{}const Se=await $s("/api/models/ensure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({modelKey:Tt,...ce?{host:ce}:{}})});return Ge(Se),Se}const pt=Date.now(),Et=Ce.current;if(!Et||pt-Et.ts>3e4){const ce=Object.values(oe);if(ce.length)Ce.current={ts:pt,list:ce};else{const Se=await $s("/api/models/list",{cache:"no-store"});Ce.current={ts:pt,list:Array.isArray(Se)?Se:[]}}}const Dt=(Ce.current?.list??[]).find(ce=>(ce.modelKey||"").trim().toLowerCase()===Bt);return Dt||null},He=th(X.output||"");if(He)return we(He);const st=X.status==="running",Xe=X.sourceUrl??X.SourceURL??"",kt=ql(Xe);if(st&&kt){const Tt=await $s("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:kt})}),Bt=await $s("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Tt)});return Ge(Bt),Bt}return null}return w.useEffect(()=>{if(!Ke&&!Lt||!navigator.clipboard?.readText)return;let X=!1,ae=!1,re=null;const xe=async()=>{if(!(X||ae)){ae=!0;try{const st=await navigator.clipboard.readText(),Xe=ql(st);if(!Xe||!iA(Xe)||Xe===V.current)return;V.current=Xe,Ke&&E(Xe),Lt&&(ei.current?z.current=Xe:(z.current=null,await Ai(Xe)))}catch{}finally{ae=!1}}},we=st=>{X||(re=window.setTimeout(async()=>{await xe(),we(document.hidden?5e3:1500)},st))},He=()=>{xe()};return window.addEventListener("hover",He),document.addEventListener("visibilitychange",He),we(0),()=>{X=!0,re&&window.clearTimeout(re),window.removeEventListener("hover",He),document.removeEventListener("visibilitychange",He)}},[Ke,Lt,Ai]),w.useEffect(()=>{if(ot||!Lt)return;const X=z.current;X&&(z.current=null,Ai(X))},[ot,Lt,Ai]),w.useEffect(()=>{const X=Zw({getModels:()=>{if(!$t.current.useChaturbateApi)return[];const ae=xi.current,re=Vi.current,xe=Object.values(ae).filter(He=>!!He?.watching&&String(He?.host??"").toLowerCase().includes("chaturbate")).map(He=>String(He?.modelKey??"").trim().toLowerCase()).filter(Boolean),we=Object.keys(re||{}).map(He=>String(He||"").trim().toLowerCase()).filter(Boolean);return Array.from(new Set([...xe,...we]))},getShow:()=>["public","private","hidden","away"],intervalMs:12e3,onData:ae=>{(async()=>{if(!ae?.enabled){_e({}),Oe.current={},Ut([]),ue(Date.now());return}const re={};for(const st of Array.isArray(ae.rooms)?ae.rooms:[]){const Xe=String(st?.username??"").trim().toLowerCase();Xe&&(re[Xe]=st)}_e(re),Oe.current=re;const xe=zi.current;for(const st of xe||[]){const Xe=String(st||"").trim().toLowerCase();Xe&&re[Xe]}if(!$t.current.useChaturbateApi)Ut([]);else if(Oi.current==="running"){const st=xi.current,Xe=Vi.current,kt=Array.from(new Set(Object.values(st).filter(pt=>!!pt?.watching&&String(pt?.host??"").toLowerCase().includes("chaturbate")).map(pt=>String(pt?.modelKey??"").trim().toLowerCase()).filter(Boolean))),Tt=Object.keys(Xe||{}).map(pt=>String(pt||"").trim().toLowerCase()).filter(Boolean),Bt=new Set(Tt),lt=Array.from(new Set([...kt,...Tt]));if(lt.length===0)Ut([]);else{const pt=[];for(const Et of lt){const Nt=re[Et];if(!Nt)continue;const Dt=String(Nt?.username??"").trim(),ce=String(Nt?.current_show??"unknown");if(ce==="public"&&!Bt.has(Et))continue;const Se=`https://chaturbate.com/${(Dt||Et).trim()}/`;pt.push({id:Et,modelKey:Dt||Et,url:Se,currentShow:ce,imageUrl:String(Nt?.image_url??"")})}pt.sort((Et,Nt)=>Et.modelKey.localeCompare(Nt.modelKey,void 0,{sensitivity:"base"})),Ut(pt)}}if(!$t.current.useChaturbateApi||ei.current)return;const we=Vi.current,He=Object.keys(we||{}).map(st=>String(st||"").toLowerCase()).filter(Boolean);for(const st of He){const Xe=re[st];if(!Xe||String(Xe.current_show??"")!=="public")continue;const kt=we[st];if(!kt)continue;await Ai(kt,{silent:!0})&&vi(Bt=>{const lt={...Bt||{}};return delete lt[st],Vi.current=lt,lt})}ue(Date.now())})()}});return()=>X()},[]),w.useEffect(()=>{if(!It.useChaturbateApi){K(0);return}const X=Zw({getModels:()=>[],getShow:()=>["public","private","hidden","away"],intervalMs:3e4,fetchAllWhenNoModels:!0,onData:ae=>{if(!ae?.enabled){K(0);return}const re=Number(ae?.total??0);K(Number.isFinite(re)?re:0),ue(Date.now())},onError:ae=>{console.error("[ALL-online poller] error",ae)}});return()=>X()},[It.useChaturbateApi]),s?t?g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsxs("div",{className:"relative",children:[g.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:g.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:[g.jsxs("div",{className:"flex items-center sm:items-start justify-between gap-3 sm:gap-4",children:[g.jsx("div",{className:"min-w-0",children:g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight text-gray-900 dark:text-white",children:"Recorder"}),g.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.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:[g.jsx(xM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:W})]}),g.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:"Watched online",children:[g.jsx(Ac,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:Li})]}),g.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:[g.jsx(Cc,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:oi})]}),g.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:[g.jsx(hM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:ti})]})]}),g.jsx("div",{className:"hidden sm:block text-[11px] text-gray-500 dark:text-gray-400",children:Q})]}),g.jsxs("div",{className:"sm:hidden mt-1 w-full",children:[g.jsx("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:Q}),g.jsxs("div",{className:"mt-2 flex items-stretch gap-2",children:[u?g.jsx(Qw,{mode:"inline",className:"flex-1"}):g.jsx("div",{className:"flex-1"}),g.jsx(Zt,{variant:"secondary",onClick:()=>gt(!0),className:"px-3 shrink-0",children:"Cookies"}),g.jsx(Zt,{variant:"secondary",onClick:r,className:"px-3 shrink-0",children:"Abmelden"})]})]})]})}),g.jsxs("div",{className:"hidden sm:flex items-center gap-2 h-full",children:[u?g.jsx(Qw,{mode:"inline"}):null,g.jsx(Zt,{variant:"secondary",onClick:()=>gt(!0),className:"h-9 px-3",children:"Cookies"}),g.jsx(Zt,{variant:"secondary",onClick:r,className:"h-9 px-3",children:"Abmelden"})]})]}),g.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-stretch",children:[g.jsxs("div",{className:"relative",children:[g.jsx("label",{className:"sr-only",children:"Source URL"}),g.jsx("input",{value:_,onChange:X=>E(X.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"})]}),g.jsx(Zt,{variant:"primary",onClick:ks,disabled:!Gs,className:"w-full sm:w-auto rounded-lg",children:"Start"})]}),it?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:it}),g.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:()=>dt(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null,fn(_)&&!ss(je)?g.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:["⚠️ Für Chaturbate werden die Cookies ",g.jsx("code",{children:"cf_clearance"})," und ",g.jsx("code",{children:"sessionId"})," benötigt."]}):null,ot?g.jsx("div",{className:"pt-1",children:g.jsx(wc,{label:"Starte Download…",indeterminate:!0})}):null,g.jsx("div",{className:"hidden sm:block pt-2",children:g.jsx(OS,{tabs:Kt,value:We,onChange:ut,ariaLabel:"Tabs",variant:"barUnderline"})})]})}),g.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:g.jsx("div",{className:"mx-auto max-w-7xl px-4 py-2",children:g.jsx(OS,{tabs:Kt,value:We,onChange:ut,ariaLabel:"Tabs",variant:"barUnderline"})})}),g.jsxs("main",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-6 space-y-6",children:[We==="running"?g.jsx(m$,{jobs:Mi,modelsByKey:oe,pending:Qt,onOpenPlayer:Fi,onStopJob:bi,onToggleFavorite:Ms,onToggleLike:mn,onToggleWatch:rs,onAddToDownloads:Os,blurPreviews:!!It.blurPreviews}):null,We==="finished"?g.jsx(jM,{jobs:L,modelsByKey:oe,doneJobs:R,doneTotal:O,page:P,pageSize:d,onPageChange:B,onOpenPlayer:Fi,onDeleteJob:Vs,onToggleHot:qs,onToggleFavorite:Ms,onToggleLike:mn,onToggleWatch:rs,blurPreviews:!!It.blurPreviews,teaserPlayback:It.teaserPlayback??"hover",teaserAudio:!!It.teaserAudio,assetNonce:mt,sortMode:p,onSortModeChange:X=>{y(X),B(1)}}):null,We==="models"?g.jsx(b$,{}):null,We==="categories"?g.jsx($$,{}):null,We==="settings"?g.jsx(tO,{onAssetsGenerated:et}):null]}),g.jsx(Q5,{open:ft,onClose:()=>gt(!1),initialCookies:Ci,onApply:X=>{const ae=Fm(Object.fromEntries(X.map(re=>[re.name,re.value])));bt(ae),$s("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:ae})}).catch(()=>{})}}),g.jsx(I$,{open:!!Re,modelKey:Re,onClose:()=>Ze(null),onOpenPlayer:Fi,runningJobs:Mi,cookies:je,blurPreviews:It.blurPreviews,onToggleHot:qs,onDelete:zs,onToggleFavorite:Ms,onToggleLike:mn,onToggleWatch:rs}),ge?g.jsx(o$,{job:ge,modelKey:v??void 0,modelsByKey:oe,expanded:Ye,onToggleExpand:()=>Qe(X=>!X),onClose:()=>Je(null),isHot:Xs(ge.output||"").startsWith("HOT "),isFavorite:!!be?.favorite,isLiked:be?.liked===!0,isWatching:!!be?.watching,onKeep:ki,onDelete:zs,onToggleHot:qs,onToggleFavorite:Ms,onToggleLike:mn,onStopJob:bi,onToggleWatch:rs}):null]})]}):g.jsx(G$,{onLoggedIn:n}):g.jsx("div",{className:"min-h-[100dvh] grid place-items-center",children:"Lade…"})}FI.createRoot(document.getElementById("root")).render(g.jsx(w.StrictMode,{children:g.jsx(PM,{position:"top-right",maxToasts:3,defaultDurationMs:3500,children:g.jsx(K$,{})})})); diff --git a/backend/web/dist/assets/index-DlgYo3oN.js b/backend/web/dist/assets/index-DlgYo3oN.js new file mode 100644 index 0000000..b76cbe1 --- /dev/null +++ b/backend/web/dist/assets/index-DlgYo3oN.js @@ -0,0 +1,419 @@ +function LI(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 a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).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 ep=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Vc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function RI(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 dy={exports:{}},Kd={};var uS;function II(){if(uS)return Kd;uS=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var a=null;if(r!==void 0&&(a=""+r),n.key!==void 0&&(a=""+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:a,ref:n!==void 0?n:null,props:r}}return Kd.Fragment=e,Kd.jsx=t,Kd.jsxs=t,Kd}var cS;function NI(){return cS||(cS=1,dy.exports=II()),dy.exports}var g=NI(),hy={exports:{}},oi={};var dS;function OI(){if(dS)return oi;dS=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"),a=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"),y=Symbol.iterator;function v(P){return P===null||typeof P!="object"?null:(P=y&&P[y]||P["@@iterator"],typeof P=="function"?P:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,S={};function L(P,Q,ue){this.props=P,this.context=Q,this.refs=S,this.updater=ue||b}L.prototype.isReactComponent={},L.prototype.setState=function(P,Q){if(typeof P!="object"&&typeof P!="function"&&P!=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,P,Q,"setState")},L.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function I(){}I.prototype=L.prototype;function R(P,Q,ue){this.props=P,this.context=Q,this.refs=S,this.updater=ue||b}var $=R.prototype=new I;$.constructor=R,_($,L.prototype),$.isPureReactComponent=!0;var B=Array.isArray;function F(){}var M={H:null,A:null,T:null,S:null},G=Object.prototype.hasOwnProperty;function D(P,Q,ue){var he=ue.ref;return{$$typeof:s,type:P,key:Q,ref:he!==void 0?he:null,props:ue}}function O(P,Q){return D(P.type,Q,P.props)}function W(P){return typeof P=="object"&&P!==null&&P.$$typeof===s}function Y(P){var Q={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(ue){return Q[ue]})}var J=/\/+/g;function ae(P,Q){return typeof P=="object"&&P!==null&&P.key!=null?Y(""+P.key):Q.toString(36)}function se(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(F,F):(P.status="pending",P.then(function(Q){P.status==="pending"&&(P.status="fulfilled",P.value=Q)},function(Q){P.status==="pending"&&(P.status="rejected",P.reason=Q)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function K(P,Q,ue,he,re){var Pe=typeof P;(Pe==="undefined"||Pe==="boolean")&&(P=null);var Ee=!1;if(P===null)Ee=!0;else switch(Pe){case"bigint":case"string":case"number":Ee=!0;break;case"object":switch(P.$$typeof){case s:case e:Ee=!0;break;case f:return Ee=P._init,K(Ee(P._payload),Q,ue,he,re)}}if(Ee)return re=re(P),Ee=he===""?"."+ae(P,0):he,B(re)?(ue="",Ee!=null&&(ue=Ee.replace(J,"$&/")+"/"),K(re,Q,ue,"",function(lt){return lt})):re!=null&&(W(re)&&(re=O(re,ue+(re.key==null||P&&P.key===re.key?"":(""+re.key).replace(J,"$&/")+"/")+Ee)),Q.push(re)),1;Ee=0;var Ge=he===""?".":he+":";if(B(P))for(var Ve=0;Ve>>1,pe=K[le];if(0>>1;len(ue,ee))hen(re,ue)?(K[le]=re,K[he]=ee,le=he):(K[le]=ue,K[Q]=ee,le=Q);else if(hen(re,ee))K[le]=re,K[he]=ee,le=he;else break e}}return X}function n(K,X){var ee=K.sortIndex-X.sortIndex;return ee!==0?ee:K.id-X.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 a=Date,u=a.now();s.unstable_now=function(){return a.now()-u}}var c=[],d=[],f=1,p=null,y=3,v=!1,b=!1,_=!1,S=!1,L=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function $(K){for(var X=t(d);X!==null;){if(X.callback===null)i(d);else if(X.startTime<=K)i(d),X.sortIndex=X.expirationTime,e(c,X);else break;X=t(d)}}function B(K){if(_=!1,$(K),!b)if(t(c)!==null)b=!0,F||(F=!0,Y());else{var X=t(d);X!==null&&se(B,X.startTime-K)}}var F=!1,M=-1,G=5,D=-1;function O(){return S?!0:!(s.unstable_now()-DK&&O());){var le=p.callback;if(typeof le=="function"){p.callback=null,y=p.priorityLevel;var pe=le(p.expirationTime<=K);if(K=s.unstable_now(),typeof pe=="function"){p.callback=pe,$(K),X=!0;break t}p===t(c)&&i(c),$(K)}else i(c);p=t(c)}if(p!==null)X=!0;else{var P=t(d);P!==null&&se(B,P.startTime-K),X=!1}}break e}finally{p=null,y=ee,v=!1}X=void 0}}finally{X?Y():F=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var J=new MessageChannel,ae=J.port2;J.port1.onmessage=W,Y=function(){ae.postMessage(null)}}else Y=function(){L(W,0)};function se(K,X){M=L(function(){K(s.unstable_now())},X)}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(K){K.callback=null},s.unstable_forceFrameRate=function(K){0>K||125le?(K.sortIndex=ee,e(d,K),t(c)===null&&K===t(d)&&(_?(I(M),M=-1):_=!0,se(B,ee-le))):(K.sortIndex=pe,e(c,K),b||v||(b=!0,F||(F=!0,Y()))),K},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(K){var X=y;return function(){var ee=y;y=X;try{return K.apply(this,arguments)}finally{y=ee}}}})(py)),py}var pS;function PI(){return pS||(pS=1,my.exports=MI()),my.exports}var gy={exports:{}},Ln={};var gS;function BI(){if(gS)return Ln;gS=1;var s=Up();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(),gy.exports=BI(),gy.exports}var vS;function FI(){if(vS)return Wd;vS=1;var s=PI(),e=Up(),t=sA();function i(o){var l="https://react.dev/errors/"+o;if(1pe||(o.current=le[pe],le[pe]=null,pe--)}function ue(o,l){pe++,le[pe]=o.current,o.current=l}var he=P(null),re=P(null),Pe=P(null),Ee=P(null);function Ge(o,l){switch(ue(Pe,l),ue(re,o),ue(he,null),l.nodeType){case 9:case 11:o=(o=l.documentElement)&&(o=o.namespaceURI)?I_(o):0;break;default:if(o=l.tagName,l=l.namespaceURI)l=I_(l),o=N_(l,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}Q(he),ue(he,o)}function Ve(){Q(he),Q(re),Q(Pe)}function lt(o){o.memoizedState!==null&&ue(Ee,o);var l=he.current,h=N_(l,o.type);l!==h&&(ue(re,o),ue(he,h))}function _t(o){re.current===o&&(Q(he),Q(re)),Ee.current===o&&(Q(Ee),Gd._currentValue=ee)}var mt,Ze;function bt(o){if(mt===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);mt=l&&l[1]||"",Ze=-1)":-1T||ge[m]!==Oe[T]){var We=` +`+ge[m].replace(" at new "," at ");return o.displayName&&We.includes("")&&(We=We.replace("",o.displayName)),We}while(1<=m&&0<=T);break}}}finally{gt=!1,Error.prepareStackTrace=h}return(h=o?o.displayName||o.name:"")?bt(h):""}function wt(o,l){switch(o.tag){case 26:case 27:case 5:return bt(o.type);case 16:return bt("Lazy");case 13:return o.child!==l&&l!==null?bt("Suspense Fallback"):bt("Suspense");case 19:return bt("SuspenseList");case 0:case 15:return at(o.type,!1);case 11:return at(o.type.render,!1);case 1:return at(o.type,!0);case 31:return bt("Activity");default:return""}}function Et(o){try{var l="",h=null;do l+=wt(o,h),h=o,o=o.return;while(o);return l}catch(m){return` +Error generating stack: `+m.message+` +`+m.stack}}var Ot=Object.prototype.hasOwnProperty,ot=s.unstable_scheduleCallback,ht=s.unstable_cancelCallback,ve=s.unstable_shouldYield,dt=s.unstable_requestPaint,qe=s.unstable_now,st=s.unstable_getCurrentPriorityLevel,ft=s.unstable_ImmediatePriority,yt=s.unstable_UserBlockingPriority,nt=s.unstable_NormalPriority,jt=s.unstable_LowPriority,qt=s.unstable_IdlePriority,Yt=s.log,Ut=s.unstable_setDisableYieldValue,Ni=null,rt=null;function Dt(o){if(typeof Yt=="function"&&Ut(o),rt&&typeof rt.setStrictMode=="function")try{rt.setStrictMode(Ni,o)}catch{}}var ii=Math.clz32?Math.clz32:Ht,ci=Math.log,mi=Math.LN2;function Ht(o){return o>>>=0,o===0?32:31-(ci(o)/mi|0)|0}var Oi=256,Ki=262144,Lt=4194304;function z(o){var l=o&42;if(l!==0)return l;switch(o&-o){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 o&261888;case 262144:case 524288:case 1048576:case 2097152:return o&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return o&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return o}}function V(o,l,h){var m=o.pendingLanes;if(m===0)return 0;var T=0,w=o.suspendedLanes,j=o.pingedLanes;o=o.warmLanes;var Z=m&134217727;return Z!==0?(m=Z&~w,m!==0?T=z(m):(j&=Z,j!==0?T=z(j):h||(h=Z&~o,h!==0&&(T=z(h))))):(Z=m&~w,Z!==0?T=z(Z):j!==0?T=z(j):h||(h=m&~o,h!==0&&(T=z(h)))),T===0?0:l!==0&&l!==T&&(l&w)===0&&(w=T&-T,h=l&-l,w>=h||w===32&&(h&4194048)!==0)?l:T}function te(o,l){return(o.pendingLanes&~(o.suspendedLanes&~o.pingedLanes)&l)===0}function xe(o,l){switch(o){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 Me(){var o=Lt;return Lt<<=1,(Lt&62914560)===0&&(Lt=4194304),o}function ut(o){for(var l=[],h=0;31>h;h++)l.push(o);return l}function Pt(o,l){o.pendingLanes|=l,l!==268435456&&(o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0)}function Ii(o,l,h,m,T,w){var j=o.pendingLanes;o.pendingLanes=h,o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0,o.expiredLanes&=h,o.entangledLanes&=h,o.errorRecoveryDisabledLanes&=h,o.shellSuspendCounter=0;var Z=o.entanglements,ge=o.expirationTimes,Oe=o.hiddenUpdates;for(h=j&~h;0"u")return null;try{return o.activeElement||o.body}catch{return o.body}}var hi=/[\n"\\]/g;function Hi(o){return o.replace(hi,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function nn(o,l,h,m,T,w,j,Z){o.name="",j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?o.type=j:o.removeAttribute("type"),l!=null?j==="number"?(l===0&&o.value===""||o.value!=l)&&(o.value=""+ye(l)):o.value!==""+ye(l)&&(o.value=""+ye(l)):j!=="submit"&&j!=="reset"||o.removeAttribute("value"),l!=null?Ns(o,j,ye(l)):h!=null?Ns(o,j,ye(h)):m!=null&&o.removeAttribute("value"),T==null&&w!=null&&(o.defaultChecked=!!w),T!=null&&(o.checked=T&&typeof T!="function"&&typeof T!="symbol"),Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"?o.name=""+ye(Z):o.removeAttribute("name")}function Gi(o,l,h,m,T,w,j,Z){if(w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(o.type=w),l!=null||h!=null){if(!(w!=="submit"&&w!=="reset"||l!=null)){Qe(o);return}h=h!=null?""+ye(h):"",l=l!=null?""+ye(l):h,Z||l===o.value||(o.value=l),o.defaultValue=l}m=m??T,m=typeof m!="function"&&typeof m!="symbol"&&!!m,o.checked=Z?o.checked:!!m,o.defaultChecked=!!m,j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"&&(o.name=j),Qe(o)}function Ns(o,l,h){l==="number"&&Zt(o.ownerDocument)===o||o.defaultValue===""+h||(o.defaultValue=""+h)}function li(o,l,h,m){if(o=o.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Rt=!1;if(St)try{var gi={};Object.defineProperty(gi,"passive",{get:function(){Rt=!0}}),window.addEventListener("test",gi,gi),window.removeEventListener("test",gi,gi)}catch{Rt=!1}var Jt=null,Vt=null,wi=null;function Ys(){if(wi)return wi;var o,l=Vt,h=l.length,m,T="value"in Jt?Jt.value:Jt.textContent,w=T.length;for(o=0;o=Il),nf=" ",Jc=!1;function wu(o,l){switch(o){case"keyup":return D0.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function rf(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var Ro=!1;function L0(o,l){switch(o){case"compositionend":return rf(l);case"keypress":return l.which!==32?null:(Jc=!0,nf);case"textInput":return o=l.data,o===nf&&Jc?null:o;default:return null}}function ed(o,l){if(Ro)return o==="compositionend"||!Lo&&wu(o,l)?(o=Ys(),wi=Vt=Jt=null,Ro=!1,o):null;switch(o){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-o};o=m}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=No(h)}}function Wa(o,l){return o&&l?o===l?!0:o&&o.nodeType===3?!1:l&&l.nodeType===3?Wa(o,l.parentNode):"contains"in o?o.contains(l):o.compareDocumentPosition?!!(o.compareDocumentPosition(l)&16):!1:!1}function Au(o){o=o!=null&&o.ownerDocument!=null&&o.ownerDocument.defaultView!=null?o.ownerDocument.defaultView:window;for(var l=Zt(o.document);l instanceof o.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)o=l.contentWindow;else break;l=Zt(o.document)}return l}function ad(o){var l=o&&o.nodeName&&o.nodeName.toLowerCase();return l&&(l==="input"&&(o.type==="text"||o.type==="search"||o.type==="tel"||o.type==="url"||o.type==="password")||l==="textarea"||o.contentEditable==="true")}var P0=St&&"documentMode"in document&&11>=document.documentMode,Oo=null,od=null,Mo=null,Cu=!1;function ld(o,l,h){var m=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Cu||Oo==null||Oo!==Zt(m)||(m=Oo,"selectionStart"in m&&ad(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}),Mo&&fa(Mo,m)||(Mo=m,m=Zf(od,"onSelect"),0>=j,T-=j,vr=1<<32-ii(l)+T|h<fi?(Ri=Bt,Bt=null):Ri=Bt.sibling;var $i=Fe(we,Bt,Ne[fi],Je);if($i===null){Bt===null&&(Bt=Ri);break}o&&Bt&&$i.alternate===null&&l(we,Bt),Te=w($i,Te,fi),ji===null?$t=$i:ji.sibling=$i,ji=$i,Bt=Ri}if(fi===Ne.length)return h(we,Bt),Ci&&yi(we,fi),$t;if(Bt===null){for(;fifi?(Ri=Bt,Bt=null):Ri=Bt.sibling;var al=Fe(we,Bt,$i.value,Je);if(al===null){Bt===null&&(Bt=Ri);break}o&&Bt&&al.alternate===null&&l(we,Bt),Te=w(al,Te,fi),ji===null?$t=al:ji.sibling=al,ji=al,Bt=Ri}if($i.done)return h(we,Bt),Ci&&yi(we,fi),$t;if(Bt===null){for(;!$i.done;fi++,$i=Ne.next())$i=tt(we,$i.value,Je),$i!==null&&(Te=w($i,Te,fi),ji===null?$t=$i:ji.sibling=$i,ji=$i);return Ci&&yi(we,fi),$t}for(Bt=m(Bt);!$i.done;fi++,$i=Ne.next())$i=He(Bt,we,fi,$i.value,Je),$i!==null&&(o&&$i.alternate!==null&&Bt.delete($i.key===null?fi:$i.key),Te=w($i,Te,fi),ji===null?$t=$i:ji.sibling=$i,ji=$i);return o&&Bt.forEach(function(DI){return l(we,DI)}),Ci&&yi(we,fi),$t}function ns(we,Te,Ne,Je){if(typeof Ne=="object"&&Ne!==null&&Ne.type===_&&Ne.key===null&&(Ne=Ne.props.children),typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case v:e:{for(var $t=Ne.key;Te!==null;){if(Te.key===$t){if($t=Ne.type,$t===_){if(Te.tag===7){h(we,Te.sibling),Je=T(Te,Ne.props.children),Je.return=we,we=Je;break e}}else if(Te.elementType===$t||typeof $t=="object"&&$t!==null&&$t.$$typeof===G&&Gl($t)===Te.type){h(we,Te.sibling),Je=T(Te,Ne.props),bd(Je,Ne),Je.return=we,we=Je;break e}h(we,Te);break}else l(we,Te);Te=Te.sibling}Ne.type===_?(Je=pa(Ne.props.children,we.mode,Je,Ne.key),Je.return=we,we=Je):(Je=pd(Ne.type,Ne.key,Ne.props,null,we.mode,Je),bd(Je,Ne),Je.return=we,we=Je)}return j(we);case b:e:{for($t=Ne.key;Te!==null;){if(Te.key===$t)if(Te.tag===4&&Te.stateNode.containerInfo===Ne.containerInfo&&Te.stateNode.implementation===Ne.implementation){h(we,Te.sibling),Je=T(Te,Ne.children||[]),Je.return=we,we=Je;break e}else{h(we,Te);break}else l(we,Te);Te=Te.sibling}Je=jo(Ne,we.mode,Je),Je.return=we,we=Je}return j(we);case G:return Ne=Gl(Ne),ns(we,Te,Ne,Je)}if(se(Ne))return Nt(we,Te,Ne,Je);if(Y(Ne)){if($t=Y(Ne),typeof $t!="function")throw Error(i(150));return Ne=$t.call(Ne),Qt(we,Te,Ne,Je)}if(typeof Ne.then=="function")return ns(we,Te,_f(Ne),Je);if(Ne.$$typeof===R)return ns(we,Te,ri(we,Ne),Je);Sf(we,Ne)}return typeof Ne=="string"&&Ne!==""||typeof Ne=="number"||typeof Ne=="bigint"?(Ne=""+Ne,Te!==null&&Te.tag===6?(h(we,Te.sibling),Je=T(Te,Ne),Je.return=we,we=Je):(h(we,Te),Je=Fl(Ne,we.mode,Je),Je.return=we,we=Je),j(we)):h(we,Te)}return function(we,Te,Ne,Je){try{xd=0;var $t=ns(we,Te,Ne,Je);return Nu=null,$t}catch(Bt){if(Bt===Iu||Bt===bf)throw Bt;var ji=Os(29,Bt,null,we.mode);return ji.lanes=Je,ji.return=we,ji}}}var zl=ST(!0),ET=ST(!1),Go=!1;function $0(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function H0(o,l){o=o.updateQueue,l.updateQueue===o&&(l.updateQueue={baseState:o.baseState,firstBaseUpdate:o.firstBaseUpdate,lastBaseUpdate:o.lastBaseUpdate,shared:o.shared,callbacks:null})}function Vo(o){return{lane:o,tag:0,payload:null,callback:null,next:null}}function zo(o,l,h){var m=o.updateQueue;if(m===null)return null;if(m=m.shared,(Vi&2)!==0){var T=m.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),m.pending=l,l=Lu(o),pf(o,null,h),l}return Du(o,m,l,h),Lu(o)}function Td(o,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,Fi(o,h)}}function G0(o,l){var h=o.updateQueue,m=o.alternate;if(m!==null&&(m=m.updateQueue,h===m)){var T=null,w=null;if(h=h.firstBaseUpdate,h!==null){do{var j={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};w===null?T=w=j:w=w.next=j,h=h.next}while(h!==null);w===null?T=w=l:w=w.next=l}else T=w=l;h={baseState:m.baseState,firstBaseUpdate:T,lastBaseUpdate:w,shared:m.shared,callbacks:m.callbacks},o.updateQueue=h;return}o=h.lastBaseUpdate,o===null?h.firstBaseUpdate=l:o.next=l,h.lastBaseUpdate=l}var V0=!1;function _d(){if(V0){var o=dn;if(o!==null)throw o}}function Sd(o,l,h,m){V0=!1;var T=o.updateQueue;Go=!1;var w=T.firstBaseUpdate,j=T.lastBaseUpdate,Z=T.shared.pending;if(Z!==null){T.shared.pending=null;var ge=Z,Oe=ge.next;ge.next=null,j===null?w=Oe:j.next=Oe,j=ge;var We=o.alternate;We!==null&&(We=We.updateQueue,Z=We.lastBaseUpdate,Z!==j&&(Z===null?We.firstBaseUpdate=Oe:Z.next=Oe,We.lastBaseUpdate=ge))}if(w!==null){var tt=T.baseState;j=0,We=Oe=ge=null,Z=w;do{var Fe=Z.lane&-536870913,He=Fe!==Z.lane;if(He?(Li&Fe)===Fe:(m&Fe)===Fe){Fe!==0&&Fe===Br&&(V0=!0),We!==null&&(We=We.next={lane:0,tag:Z.tag,payload:Z.payload,callback:null,next:null});e:{var Nt=o,Qt=Z;Fe=l;var ns=h;switch(Qt.tag){case 1:if(Nt=Qt.payload,typeof Nt=="function"){tt=Nt.call(ns,tt,Fe);break e}tt=Nt;break e;case 3:Nt.flags=Nt.flags&-65537|128;case 0:if(Nt=Qt.payload,Fe=typeof Nt=="function"?Nt.call(ns,tt,Fe):Nt,Fe==null)break e;tt=p({},tt,Fe);break e;case 2:Go=!0}}Fe=Z.callback,Fe!==null&&(o.flags|=64,He&&(o.flags|=8192),He=T.callbacks,He===null?T.callbacks=[Fe]:He.push(Fe))}else He={lane:Fe,tag:Z.tag,payload:Z.payload,callback:Z.callback,next:null},We===null?(Oe=We=He,ge=tt):We=We.next=He,j|=Fe;if(Z=Z.next,Z===null){if(Z=T.shared.pending,Z===null)break;He=Z,Z=He.next,He.next=null,T.lastBaseUpdate=He,T.shared.pending=null}}while(!0);We===null&&(ge=tt),T.baseState=ge,T.firstBaseUpdate=Oe,T.lastBaseUpdate=We,w===null&&(T.shared.lanes=0),Xo|=j,o.lanes=j,o.memoizedState=tt}}function wT(o,l){if(typeof o!="function")throw Error(i(191,o));o.call(l)}function AT(o,l){var h=o.callbacks;if(h!==null)for(o.callbacks=null,o=0;ow?w:8;var j=K.T,Z={};K.T=Z,ug(o,!1,l,h);try{var ge=T(),Oe=K.S;if(Oe!==null&&Oe(Z,ge),ge!==null&&typeof ge=="object"&&typeof ge.then=="function"){var We=vR(ge,m);Ad(o,l,We,Sr(o))}else Ad(o,l,m,Sr(o))}catch(tt){Ad(o,l,{then:function(){},status:"rejected",reason:tt},Sr())}finally{X.p=w,j!==null&&Z.types!==null&&(j.types=Z.types),K.T=j}}function ER(){}function og(o,l,h,m){if(o.tag!==5)throw Error(i(476));var T=n1(o).queue;s1(o,T,l,ee,h===null?ER:function(){return r1(o),h(m)})}function n1(o){var l=o.memoizedState;if(l!==null)return l;l={memoizedState:ee,baseState:ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ja,lastRenderedState:ee},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ja,lastRenderedState:h},next:null},o.memoizedState=l,o=o.alternate,o!==null&&(o.memoizedState=l),l}function r1(o){var l=n1(o);l.next===null&&(l=o.alternate.memoizedState),Ad(o,l.next.queue,{},Sr())}function lg(){return Ct(Gd)}function a1(){return Gs().memoizedState}function o1(){return Gs().memoizedState}function wR(o){for(var l=o.return;l!==null;){switch(l.tag){case 24:case 3:var h=Sr();o=Vo(h);var m=zo(l,o,h);m!==null&&(nr(m,l,h),Td(m,l,h)),l={cache:Qa()},o.payload=l;return}l=l.return}}function AR(o,l,h){var m=Sr();h={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},Nf(o)?u1(l,h):(h=fd(o,l,h,m),h!==null&&(nr(h,o,m),c1(h,l,m)))}function l1(o,l,h){var m=Sr();Ad(o,l,h,m)}function Ad(o,l,h,m){var T={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(Nf(o))u1(l,T);else{var w=o.alternate;if(o.lanes===0&&(w===null||w.lanes===0)&&(w=l.lastRenderedReducer,w!==null))try{var j=l.lastRenderedState,Z=w(j,h);if(T.hasEagerState=!0,T.eagerState=Z,kn(Z,j))return Du(o,l,T,0),cs===null&&ku(),!1}catch{}if(h=fd(o,l,T,m),h!==null)return nr(h,o,m),c1(h,l,m),!0}return!1}function ug(o,l,h,m){if(m={lane:2,revertLane:$g(),gesture:null,action:m,hasEagerState:!1,eagerState:null,next:null},Nf(o)){if(l)throw Error(i(479))}else l=fd(o,h,m,2),l!==null&&nr(l,o,2)}function Nf(o){var l=o.alternate;return o===di||l!==null&&l===di}function u1(o,l){Mu=Af=!0;var h=o.pending;h===null?l.next=l:(l.next=h.next,h.next=l),o.pending=l}function c1(o,l,h){if((h&4194048)!==0){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,Fi(o,h)}}var Cd={readContext:Ct,use:Df,useCallback:Ms,useContext:Ms,useEffect:Ms,useImperativeHandle:Ms,useLayoutEffect:Ms,useInsertionEffect:Ms,useMemo:Ms,useReducer:Ms,useRef:Ms,useState:Ms,useDebugValue:Ms,useDeferredValue:Ms,useTransition:Ms,useSyncExternalStore:Ms,useId:Ms,useHostTransitionStatus:Ms,useFormState:Ms,useActionState:Ms,useOptimistic:Ms,useMemoCache:Ms,useCacheRefresh:Ms};Cd.useEffectEvent=Ms;var d1={readContext:Ct,use:Df,useCallback:function(o,l){return Un().memoizedState=[o,l===void 0?null:l],o},useContext:Ct,useEffect:WT,useImperativeHandle:function(o,l,h){h=h!=null?h.concat([o]):null,Rf(4194308,4,ZT.bind(null,l,o),h)},useLayoutEffect:function(o,l){return Rf(4194308,4,o,l)},useInsertionEffect:function(o,l){Rf(4,2,o,l)},useMemo:function(o,l){var h=Un();l=l===void 0?null:l;var m=o();if(ql){Dt(!0);try{o()}finally{Dt(!1)}}return h.memoizedState=[m,l],m},useReducer:function(o,l,h){var m=Un();if(h!==void 0){var T=h(l);if(ql){Dt(!0);try{h(l)}finally{Dt(!1)}}}else T=l;return m.memoizedState=m.baseState=T,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:o,lastRenderedState:T},m.queue=o,o=o.dispatch=AR.bind(null,di,o),[m.memoizedState,o]},useRef:function(o){var l=Un();return o={current:o},l.memoizedState=o},useState:function(o){o=ig(o);var l=o.queue,h=l1.bind(null,di,l);return l.dispatch=h,[o.memoizedState,h]},useDebugValue:rg,useDeferredValue:function(o,l){var h=Un();return ag(h,o,l)},useTransition:function(){var o=ig(!1);return o=s1.bind(null,di,o.queue,!0,!1),Un().memoizedState=o,[!1,o]},useSyncExternalStore:function(o,l,h){var m=di,T=Un();if(Ci){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),cs===null)throw Error(i(349));(Li&127)!==0||IT(m,l,h)}T.memoizedState=h;var w={value:h,getSnapshot:l};return T.queue=w,WT(OT.bind(null,m,w,o),[o]),m.flags|=2048,Bu(9,{destroy:void 0},NT.bind(null,m,w,h,l),null),h},useId:function(){var o=Un(),l=cs.identifierPrefix;if(Ci){var h=Tn,m=vr;h=(m&~(1<<32-ii(m)-1)).toString(32)+h,l="_"+l+"R_"+h,h=Cf++,0<\/script>",w=w.removeChild(w.firstChild);break;case"select":w=typeof m.is=="string"?j.createElement("select",{is:m.is}):j.createElement("select"),m.multiple?w.multiple=!0:m.size&&(w.size=m.size);break;default:w=typeof m.is=="string"?j.createElement(T,{is:m.is}):j.createElement(T)}}w[si]=l,w[Gt]=m;e:for(j=l.child;j!==null;){if(j.tag===5||j.tag===6)w.appendChild(j.stateNode);else if(j.tag!==4&&j.tag!==27&&j.child!==null){j.child.return=j,j=j.child;continue}if(j===l)break e;for(;j.sibling===null;){if(j.return===null||j.return===l)break e;j=j.return}j.sibling.return=j.return,j=j.sibling}l.stateNode=w;e:switch(Sn(w,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&&to(l)}}return xs(l),Sg(l,l.type,o===null?null:o.memoizedProps,l.pendingProps,h),null;case 6:if(o&&l.stateNode!=null)o.memoizedProps!==m&&to(l);else{if(typeof m!="string"&&l.stateNode===null)throw Error(i(166));if(o=Pe.current,x(l)){if(o=l.stateNode,h=l.memoizedProps,m=null,T=Xs,T!==null)switch(T.tag){case 27:case 5:m=T.memoizedProps}o[si]=l,o=!!(o.nodeValue===h||m!==null&&m.suppressHydrationWarning===!0||L_(o.nodeValue,h)),o||xa(l,!0)}else o=Jf(o).createTextNode(m),o[si]=l,l.stateNode=o}return xs(l),null;case 31:if(h=l.memoizedState,o===null||o.memoizedState!==null){if(m=x(l),h!==null){if(o===null){if(!m)throw Error(i(318));if(o=l.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(i(557));o[si]=l}else A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xs(l),o=!1}else h=k(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=h),o=!0;if(!o)return l.flags&256?(br(l),l):(br(l),null);if((l.flags&128)!==0)throw Error(i(558))}return xs(l),null;case 13:if(m=l.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(T=x(l),m!==null&&m.dehydrated!==null){if(o===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[si]=l}else A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xs(l),T=!1}else T=k(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(br(l),l):(br(l),null)}return br(l),(l.flags&128)!==0?(l.lanes=h,l):(h=m!==null,o=o!==null&&o.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),w=null,m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),w!==T&&(m.flags|=2048)),h!==o&&h&&(l.child.flags|=8192),Ff(l,l.updateQueue),xs(l),null);case 4:return Ve(),o===null&&zg(l.stateNode.containerInfo),xs(l),null;case 10:return oe(l.type),xs(l),null;case 19:if(Q(Hs),m=l.memoizedState,m===null)return xs(l),null;if(T=(l.flags&128)!==0,w=m.rendering,w===null)if(T)Dd(m,!1);else{if(Ps!==0||o!==null&&(o.flags&128)!==0)for(o=l.child;o!==null;){if(w=wf(o),w!==null){for(l.flags|=128,Dd(m,!1),o=w.updateQueue,l.updateQueue=o,Ff(l,o),l.subtreeFlags=0,o=h,h=l.child;h!==null;)gf(h,o),h=h.sibling;return ue(Hs,Hs.current&1|2),Ci&&yi(l,m.treeForkCount),l.child}o=o.sibling}m.tail!==null&&qe()>Gf&&(l.flags|=128,T=!0,Dd(m,!1),l.lanes=4194304)}else{if(!T)if(o=wf(w),o!==null){if(l.flags|=128,T=!0,o=o.updateQueue,l.updateQueue=o,Ff(l,o),Dd(m,!0),m.tail===null&&m.tailMode==="hidden"&&!w.alternate&&!Ci)return xs(l),null}else 2*qe()-m.renderingStartTime>Gf&&h!==536870912&&(l.flags|=128,T=!0,Dd(m,!1),l.lanes=4194304);m.isBackwards?(w.sibling=l.child,l.child=w):(o=m.last,o!==null?o.sibling=w:l.child=w,m.last=w)}return m.tail!==null?(o=m.tail,m.rendering=o,m.tail=o.sibling,m.renderingStartTime=qe(),o.sibling=null,h=Hs.current,ue(Hs,T?h&1|2:h&1),Ci&&yi(l,m.treeForkCount),o):(xs(l),null);case 22:case 23:return br(l),q0(),m=l.memoizedState!==null,o!==null?o.memoizedState!==null!==m&&(l.flags|=8192):m&&(l.flags|=8192),m?(h&536870912)!==0&&(l.flags&128)===0&&(xs(l),l.subtreeFlags&6&&(l.flags|=8192)):xs(l),h=l.updateQueue,h!==null&&Ff(l,h.retryQueue),h=null,o!==null&&o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==h&&(l.flags|=2048),o!==null&&Q(Hl),null;case 24:return h=null,o!==null&&(h=o.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),oe(ps),xs(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function RR(o,l){switch(Zn(l),l.tag){case 1:return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 3:return oe(ps),Ve(),o=l.flags,(o&65536)!==0&&(o&128)===0?(l.flags=o&-65537|128,l):null;case 26:case 27:case 5:return _t(l),null;case 31:if(l.memoizedState!==null){if(br(l),l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 13:if(br(l),o=l.memoizedState,o!==null&&o.dehydrated!==null){if(l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 19:return Q(Hs),null;case 4:return Ve(),null;case 10:return oe(l.type),null;case 22:case 23:return br(l),q0(),o!==null&&Q(Hl),o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 24:return oe(ps),null;case 25:return null;default:return null}}function M1(o,l){switch(Zn(l),l.tag){case 3:oe(ps),Ve();break;case 26:case 27:case 5:_t(l);break;case 4:Ve();break;case 31:l.memoizedState!==null&&br(l);break;case 13:br(l);break;case 19:Q(Hs);break;case 10:oe(l.type);break;case 22:case 23:br(l),q0(),o!==null&&Q(Hl);break;case 24:oe(ps)}}function Ld(o,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&o)===o){m=void 0;var w=h.create,j=h.inst;m=w(),j.destroy=m}h=h.next}while(h!==T)}}catch(Z){Zi(l,l.return,Z)}}function Wo(o,l,h){try{var m=l.updateQueue,T=m!==null?m.lastEffect:null;if(T!==null){var w=T.next;m=w;do{if((m.tag&o)===o){var j=m.inst,Z=j.destroy;if(Z!==void 0){j.destroy=void 0,T=l;var ge=h,Oe=Z;try{Oe()}catch(We){Zi(T,ge,We)}}}m=m.next}while(m!==w)}}catch(We){Zi(l,l.return,We)}}function P1(o){var l=o.updateQueue;if(l!==null){var h=o.stateNode;try{AT(l,h)}catch(m){Zi(o,o.return,m)}}}function B1(o,l,h){h.props=Kl(o.type,o.memoizedProps),h.state=o.memoizedState;try{h.componentWillUnmount()}catch(m){Zi(o,l,m)}}function Rd(o,l){try{var h=o.ref;if(h!==null){switch(o.tag){case 26:case 27:case 5:var m=o.stateNode;break;case 30:m=o.stateNode;break;default:m=o.stateNode}typeof h=="function"?o.refCleanup=h(m):h.current=m}}catch(T){Zi(o,l,T)}}function _a(o,l){var h=o.ref,m=o.refCleanup;if(h!==null)if(typeof m=="function")try{m()}catch(T){Zi(o,l,T)}finally{o.refCleanup=null,o=o.alternate,o!=null&&(o.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){Zi(o,l,T)}else h.current=null}function F1(o){var l=o.type,h=o.memoizedProps,m=o.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){Zi(o,o.return,T)}}function Eg(o,l,h){try{var m=o.stateNode;JR(m,o.type,h,l),m[Gt]=l}catch(T){Zi(o,o.return,T)}}function U1(o){return o.tag===5||o.tag===3||o.tag===26||o.tag===27&&tl(o.type)||o.tag===4}function wg(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||U1(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.tag===27&&tl(o.type)||o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function Ag(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(o,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(o),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=ke));else if(m!==4&&(m===27&&tl(o.type)&&(h=o.stateNode,l=null),o=o.child,o!==null))for(Ag(o,l,h),o=o.sibling;o!==null;)Ag(o,l,h),o=o.sibling}function Uf(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?h.insertBefore(o,l):h.appendChild(o);else if(m!==4&&(m===27&&tl(o.type)&&(h=o.stateNode),o=o.child,o!==null))for(Uf(o,l,h),o=o.sibling;o!==null;)Uf(o,l,h),o=o.sibling}function j1(o){var l=o.stateNode,h=o.memoizedProps;try{for(var m=o.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);Sn(l,m,h),l[si]=o,l[Gt]=h}catch(w){Zi(o,o.return,w)}}var io=!1,Js=!1,Cg=!1,$1=typeof WeakSet=="function"?WeakSet:Set,hn=null;function IR(o,l){if(o=o.containerInfo,Wg=am,o=Au(o),ad(o)){if("selectionStart"in o)var h={start:o.selectionStart,end:o.selectionEnd};else e:{h=(h=o.ownerDocument)&&h.defaultView||window;var m=h.getSelection&&h.getSelection();if(m&&m.rangeCount!==0){h=m.anchorNode;var T=m.anchorOffset,w=m.focusNode;m=m.focusOffset;try{h.nodeType,w.nodeType}catch{h=null;break e}var j=0,Z=-1,ge=-1,Oe=0,We=0,tt=o,Fe=null;t:for(;;){for(var He;tt!==h||T!==0&&tt.nodeType!==3||(Z=j+T),tt!==w||m!==0&&tt.nodeType!==3||(ge=j+m),tt.nodeType===3&&(j+=tt.nodeValue.length),(He=tt.firstChild)!==null;)Fe=tt,tt=He;for(;;){if(tt===o)break t;if(Fe===h&&++Oe===T&&(Z=j),Fe===w&&++We===m&&(ge=j),(He=tt.nextSibling)!==null)break;tt=Fe,Fe=tt.parentNode}tt=He}h=Z===-1||ge===-1?null:{start:Z,end:ge}}else h=null}h=h||{start:0,end:0}}else h=null;for(Yg={focusedElem:o,selectionRange:h},am=!1,hn=l;hn!==null;)if(l=hn,o=l.child,(l.subtreeFlags&1028)!==0&&o!==null)o.return=l,hn=o;else for(;hn!==null;){switch(l=hn,w=l.alternate,o=l.flags,l.tag){case 0:if((o&4)!==0&&(o=l.updateQueue,o=o!==null?o.events:null,o!==null))for(h=0;h title"))),Sn(w,m,h),w[si]=o,Pi(w),m=w;break e;case"link":var j=K_("link","href",T).get(m+(h.href||""));if(j){for(var Z=0;Zns&&(j=ns,ns=Qt,Qt=j);var we=_s(Z,Qt),Te=_s(Z,ns);if(we&&Te&&(He.rangeCount!==1||He.anchorNode!==we.node||He.anchorOffset!==we.offset||He.focusNode!==Te.node||He.focusOffset!==Te.offset)){var Ne=tt.createRange();Ne.setStart(we.node,we.offset),He.removeAllRanges(),Qt>ns?(He.addRange(Ne),He.extend(Te.node,Te.offset)):(Ne.setEnd(Te.node,Te.offset),He.addRange(Ne))}}}}for(tt=[],He=Z;He=He.parentNode;)He.nodeType===1&&tt.push({element:He,left:He.scrollLeft,top:He.scrollTop});for(typeof Z.focus=="function"&&Z.focus(),Z=0;Zh?32:h,K.T=null,h=Og,Og=null;var w=Zo,j=oo;if(on=0,Hu=Zo=null,oo=0,(Vi&6)!==0)throw Error(i(331));var Z=Vi;if(Vi|=4,Z1(w.current),Y1(w,w.current,j,h),Vi=Z,Bd(0,!1),rt&&typeof rt.onPostCommitFiberRoot=="function")try{rt.onPostCommitFiberRoot(Ni,w)}catch{}return!0}finally{X.p=T,K.T=m,g_(o,l)}}function v_(o,l,h){l=Xn(h,l),l=fg(o.stateNode,l,2),o=zo(o,l,2),o!==null&&(Pt(o,2),Sa(o))}function Zi(o,l,h){if(o.tag===3)v_(o,o,h);else for(;l!==null;){if(l.tag===3){v_(l,o,h);break}else if(l.tag===1){var m=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&(Qo===null||!Qo.has(m))){o=Xn(h,o),h=x1(2),m=zo(l,h,2),m!==null&&(b1(h,m,l,o),Pt(m,2),Sa(m));break}}l=l.return}}function Fg(o,l,h){var m=o.pingCache;if(m===null){m=o.pingCache=new MR;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)||(Lg=!0,T.add(h),o=jR.bind(null,o,l,h),l.then(o,o))}function jR(o,l,h){var m=o.pingCache;m!==null&&m.delete(l),o.pingedLanes|=o.suspendedLanes&h,o.warmLanes&=~h,cs===o&&(Li&h)===h&&(Ps===4||Ps===3&&(Li&62914560)===Li&&300>qe()-Hf?(Vi&2)===0&&Gu(o,0):Rg|=h,$u===Li&&($u=0)),Sa(o)}function x_(o,l){l===0&&(l=Me()),o=Xa(o,l),o!==null&&(Pt(o,l),Sa(o))}function $R(o){var l=o.memoizedState,h=0;l!==null&&(h=l.retryLane),x_(o,h)}function HR(o,l){var h=0;switch(o.tag){case 31:case 13:var m=o.stateNode,T=o.memoizedState;T!==null&&(h=T.retryLane);break;case 19:m=o.stateNode;break;case 22:m=o.stateNode._retryCache;break;default:throw Error(i(314))}m!==null&&m.delete(l),x_(o,h)}function GR(o,l){return ot(o,l)}var Yf=null,zu=null,Ug=!1,Xf=!1,jg=!1,el=0;function Sa(o){o!==zu&&o.next===null&&(zu===null?Yf=zu=o:zu=zu.next=o),Xf=!0,Ug||(Ug=!0,zR())}function Bd(o,l){if(!jg&&Xf){jg=!0;do for(var h=!1,m=Yf;m!==null;){if(o!==0){var T=m.pendingLanes;if(T===0)var w=0;else{var j=m.suspendedLanes,Z=m.pingedLanes;w=(1<<31-ii(42|o)+1)-1,w&=T&~(j&~Z),w=w&201326741?w&201326741|1:w?w|2:0}w!==0&&(h=!0,S_(m,w))}else w=Li,w=V(m,m===cs?w:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),(w&3)===0||te(m,w)||(h=!0,S_(m,w));m=m.next}while(h);jg=!1}}function VR(){b_()}function b_(){Xf=Ug=!1;var o=0;el!==0&&tI()&&(o=el);for(var l=qe(),h=null,m=Yf;m!==null;){var T=m.next,w=T_(m,l);w===0?(m.next=null,h===null?Yf=T:h.next=T,T===null&&(zu=h)):(h=m,(o!==0||(w&3)!==0)&&(Xf=!0)),m=T}on!==0&&on!==5||Bd(o),el!==0&&(el=0)}function T_(o,l){for(var h=o.suspendedLanes,m=o.pingedLanes,T=o.expirationTimes,w=o.pendingLanes&-62914561;0Z)break;var We=ge.transferSize,tt=ge.initiatorType;We&&R_(tt)&&(ge=ge.responseEnd,j+=We*(ge"u"?null:document;function G_(o,l,h){var m=qu;if(m&&typeof l=="string"&&l){var T=Hi(l);T='link[rel="'+o+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),H_.has(T)||(H_.add(T),o={rel:o,crossOrigin:h,href:l},m.querySelector(T)===null&&(l=m.createElement("link"),Sn(l,"link",o),Pi(l),m.head.appendChild(l)))}}function cI(o){lo.D(o),G_("dns-prefetch",o,null)}function dI(o,l){lo.C(o,l),G_("preconnect",o,l)}function hI(o,l,h){lo.L(o,l,h);var m=qu;if(m&&o&&l){var T='link[rel="preload"][as="'+Hi(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+Hi(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+Hi(h.imageSizes)+'"]')):T+='[href="'+Hi(o)+'"]';var w=T;switch(l){case"style":w=Ku(o);break;case"script":w=Wu(o)}jr.has(w)||(o=p({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:o,as:l},h),jr.set(w,o),m.querySelector(T)!==null||l==="style"&&m.querySelector($d(w))||l==="script"&&m.querySelector(Hd(w))||(l=m.createElement("link"),Sn(l,"link",o),Pi(l),m.head.appendChild(l)))}}function fI(o,l){lo.m(o,l);var h=qu;if(h&&o){var m=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+Hi(m)+'"][href="'+Hi(o)+'"]',w=T;switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":w=Wu(o)}if(!jr.has(w)&&(o=p({rel:"modulepreload",href:o},l),jr.set(w,o),h.querySelector(T)===null)){switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(Hd(w)))return}m=h.createElement("link"),Sn(m,"link",o),Pi(m),h.head.appendChild(m)}}}function mI(o,l,h){lo.S(o,l,h);var m=qu;if(m&&o){var T=bs(m).hoistableStyles,w=Ku(o);l=l||"default";var j=T.get(w);if(!j){var Z={loading:0,preload:null};if(j=m.querySelector($d(w)))Z.loading=5;else{o=p({rel:"stylesheet",href:o,"data-precedence":l},h),(h=jr.get(w))&&iy(o,h);var ge=j=m.createElement("link");Pi(ge),Sn(ge,"link",o),ge._p=new Promise(function(Oe,We){ge.onload=Oe,ge.onerror=We}),ge.addEventListener("load",function(){Z.loading|=1}),ge.addEventListener("error",function(){Z.loading|=2}),Z.loading|=4,tm(j,l,m)}j={type:"stylesheet",instance:j,count:1,state:Z},T.set(w,j)}}}function pI(o,l){lo.X(o,l);var h=qu;if(h&&o){var m=bs(h).hoistableScripts,T=Wu(o),w=m.get(T);w||(w=h.querySelector(Hd(T)),w||(o=p({src:o,async:!0},l),(l=jr.get(T))&&sy(o,l),w=h.createElement("script"),Pi(w),Sn(w,"link",o),h.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},m.set(T,w))}}function gI(o,l){lo.M(o,l);var h=qu;if(h&&o){var m=bs(h).hoistableScripts,T=Wu(o),w=m.get(T);w||(w=h.querySelector(Hd(T)),w||(o=p({src:o,async:!0,type:"module"},l),(l=jr.get(T))&&sy(o,l),w=h.createElement("script"),Pi(w),Sn(w,"link",o),h.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},m.set(T,w))}}function V_(o,l,h,m){var T=(T=Pe.current)?em(T):null;if(!T)throw Error(i(446));switch(o){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=Ku(h.href),h=bs(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"){o=Ku(h.href);var w=bs(T).hoistableStyles,j=w.get(o);if(j||(T=T.ownerDocument||T,j={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},w.set(o,j),(w=T.querySelector($d(o)))&&!w._p&&(j.instance=w,j.state.loading=5),jr.has(o)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},jr.set(o,h),w||yI(T,o,h,j.state))),l&&m===null)throw Error(i(528,""));return j}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=Wu(h),h=bs(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,o))}}function Ku(o){return'href="'+Hi(o)+'"'}function $d(o){return'link[rel="stylesheet"]['+o+"]"}function z_(o){return p({},o,{"data-precedence":o.precedence,precedence:null})}function yI(o,l,h,m){o.querySelector('link[rel="preload"][as="style"]['+l+"]")?m.loading=1:(l=o.createElement("link"),m.preload=l,l.addEventListener("load",function(){return m.loading|=1}),l.addEventListener("error",function(){return m.loading|=2}),Sn(l,"link",h),Pi(l),o.head.appendChild(l))}function Wu(o){return'[src="'+Hi(o)+'"]'}function Hd(o){return"script[async]"+o}function q_(o,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var m=o.querySelector('style[data-href~="'+Hi(h.href)+'"]');if(m)return l.instance=m,Pi(m),m;var T=p({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return m=(o.ownerDocument||o).createElement("style"),Pi(m),Sn(m,"style",T),tm(m,h.precedence,o),l.instance=m;case"stylesheet":T=Ku(h.href);var w=o.querySelector($d(T));if(w)return l.state.loading|=4,l.instance=w,Pi(w),w;m=z_(h),(T=jr.get(T))&&iy(m,T),w=(o.ownerDocument||o).createElement("link"),Pi(w);var j=w;return j._p=new Promise(function(Z,ge){j.onload=Z,j.onerror=ge}),Sn(w,"link",m),l.state.loading|=4,tm(w,h.precedence,o),l.instance=w;case"script":return w=Wu(h.src),(T=o.querySelector(Hd(w)))?(l.instance=T,Pi(T),T):(m=h,(T=jr.get(w))&&(m=p({},h),sy(m,T)),o=o.ownerDocument||o,T=o.createElement("script"),Pi(T),Sn(T,"link",m),o.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,tm(m,h.precedence,o));return l.instance}function tm(o,l,h){for(var m=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=m.length?m[m.length-1]:null,w=T,j=0;j title"):null)}function vI(o,l,h){if(h===1||l.itemProp!=null)return!1;switch(o){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"?(o=l.disabled,typeof l.precedence=="string"&&o==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 Y_(o){return!(o.type==="stylesheet"&&(o.state.loading&3)===0)}function xI(o,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=Ku(m.href),w=l.querySelector($d(T));if(w){l=w._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(o.count++,o=sm.bind(o),l.then(o,o)),h.state.loading|=4,h.instance=w,Pi(w);return}w=l.ownerDocument||l,m=z_(m),(T=jr.get(T))&&iy(m,T),w=w.createElement("link"),Pi(w);var j=w;j._p=new Promise(function(Z,ge){j.onload=Z,j.onerror=ge}),Sn(w,"link",m),h.instance=w}o.stylesheets===null&&(o.stylesheets=new Map),o.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(o.count++,h=sm.bind(o),l.addEventListener("load",h),l.addEventListener("error",h))}}var ny=0;function bI(o,l){return o.stylesheets&&o.count===0&&rm(o,o.stylesheets),0ny?50:800)+l);return o.unsuspend=h,function(){o.unsuspend=null,clearTimeout(m),clearTimeout(T)}}:null}function sm(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rm(this,this.stylesheets);else if(this.unsuspend){var o=this.unsuspend;this.unsuspend=null,o()}}}var nm=null;function rm(o,l){o.stylesheets=null,o.unsuspend!==null&&(o.count++,nm=new Map,l.forEach(TI,o),nm=null,sm.call(o))}function TI(o,l){if(!(l.state.loading&4)){var h=nm.get(o);if(h)var m=h.get(null);else{h=new Map,nm.set(o,h);for(var T=o.querySelectorAll("link[data-precedence],style[data-precedence]"),w=0;w"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),fy.exports=FI(),fy.exports}var jI=UI();function $I(...s){return s.filter(Boolean).join(" ")}const HI="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",GI={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},VI={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"},zI={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 qI(){return g.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[g.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),g.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function ti({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:a,isLoading:u=!1,disabled:c,className:d,type:f="button",...p}){const y=r||a||u?"gap-x-1.5":"";return g.jsxs("button",{type:f,disabled:c||u,className:$I(HI,GI[n],VI[i],zI[t][e],y,d),...p,children:[u?g.jsx("span",{className:"-ml-0.5",children:g.jsx(qI,{})}):r&&g.jsx("span",{className:"-ml-0.5",children:r}),g.jsx("span",{children:s}),a&&!u&&g.jsx("span",{className:"-mr-0.5",children:a})]})}function nA(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?KI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,yy=(s,e,t)=>(WI(s,typeof e!="symbol"?e+"":e,t),t);let YI=class{constructor(){yy(this,"current",this.detect()),yy(this,"handoffState","pending"),yy(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"}},Fa=new YI;function Uh(s){var e;return Fa.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function Vv(s){var e,t;return Fa.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function rA(s){var e,t;return(t=(e=Vv(s))==null?void 0:e.activeElement)!=null?t:null}function XI(s){return rA(s)===s}function jp(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function Co(){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 jp(()=>{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=Co();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 $p(){let[s]=E.useState(Co);return E.useEffect(()=>()=>s.dispose(),[s]),s}let hr=(s,e)=>{Fa.isServer?E.useEffect(s,e):E.useLayoutEffect(s,e)};function bu(s){let e=E.useRef(s);return hr(()=>{e.current=s},[s]),e}let hs=function(s){let e=bu(s);return zt.useCallback((...t)=>e.current(...t),[e])};function jh(s){return E.useMemo(()=>s,Object.values(s))}let QI=E.createContext(void 0);function ZI(){return E.useContext(QI)}function zv(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function wo(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,wo),i}var tp=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(tp||{}),bl=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(bl||{});function Wr(){let s=eN();return E.useCallback(e=>JI({mergeRefs:s,...e}),[s])}function JI({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:a,mergeRefs:u}){u=u??tN;let c=aA(e,s);if(r)return fm(c,t,i,a,u);let d=n??0;if(d&2){let{static:f=!1,...p}=c;if(f)return fm(p,t,i,a,u)}if(d&1){let{unmount:f=!0,...p}=c;return wo(f?0:1,{0(){return null},1(){return fm({...p,hidden:!0,style:{display:"none"}},t,i,a,u)}})}return fm(c,t,i,a,u)}function fm(s,e={},t,i,n){let{as:r=t,children:a,refName:u="ref",...c}=vy(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof a=="function"?a(e):a;"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 y=!1,v=[];for(let[b,_]of Object.entries(e))typeof _=="boolean"&&(y=!0),_===!0&&v.push(b.replace(/([A-Z])/g,S=>`-${S.toLowerCase()}`));if(y){p["data-headlessui-state"]=v.join(" ");for(let b of v)p[`data-${b}`]=""}}if(dh(r)&&(Object.keys(tu(c)).length>0||Object.keys(tu(p)).length>0))if(!E.isValidElement(f)||Array.isArray(f)&&f.length>1||sN(f)){if(Object.keys(tu(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(tu(c)).concat(Object.keys(tu(p))).map(y=>` - ${y}`).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(y=>` - ${y}`).join(` +`)].join(` +`))}else{let y=f.props,v=y?.className,b=typeof v=="function"?(...L)=>zv(v(...L),c.className):zv(v,c.className),_=b?{className:b}:{},S=aA(f.props,tu(vy(c,["ref"])));for(let L in p)L in S&&delete p[L];return E.cloneElement(f,Object.assign({},S,p,d,{ref:n(iN(f),d.ref)},_))}return E.createElement(r,Object.assign({},vy(c,["ref"]),!dh(r)&&d,!dh(r)&&p),f)}function eN(){let s=E.useRef([]),e=E.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 tN(...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 aA(...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 a=t[i];for(let u of a){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function mr(s){var e;return Object.assign(E.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function tu(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function vy(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function iN(s){return zt.version.split(".")[0]>="19"?s.props.ref:s.ref}function dh(s){return s===E.Fragment||s===Symbol.for("react.fragment")}function sN(s){return dh(s.type)}let nN="span";var ip=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(ip||{});function rN(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 Wr()({ourProps:r,theirProps:n,slot:{},defaultTag:nN,name:"Hidden"})}let qv=mr(rN);function aN(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function _l(s){return aN(s)&&"tagName"in s}function gu(s){return _l(s)&&"accessKey"in s}function Tl(s){return _l(s)&&"tabIndex"in s}function oN(s){return _l(s)&&"style"in s}function lN(s){return gu(s)&&s.nodeName==="IFRAME"}function uN(s){return gu(s)&&s.nodeName==="INPUT"}let oA=Symbol();function cN(s,e=!0){return Object.assign(s,{[oA]:e})}function qa(...s){let e=E.useRef(s);E.useEffect(()=>{e.current=s},[s]);let t=hs(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[oA])?void 0:t}let Xx=E.createContext(null);Xx.displayName="DescriptionContext";function lA(){let s=E.useContext(Xx);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,lA),e}return s}function dN(){let[s,e]=E.useState([]);return[s.length>0?s.join(" "):void 0,E.useMemo(()=>function(t){let i=hs(r=>(e(a=>[...a,r]),()=>e(a=>{let u=a.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=E.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 zt.createElement(Xx.Provider,{value:n},t.children)},[e])]}let hN="p";function fN(s,e){let t=E.useId(),i=ZI(),{id:n=`headlessui-description-${t}`,...r}=s,a=lA(),u=qa(e);hr(()=>a.register(n),[n,a.register]);let c=jh({...a.slot,disabled:i||!1}),d={ref:u,...a.props,id:n};return Wr()({ourProps:d,theirProps:r,slot:c,defaultTag:hN,name:a.name||"Description"})}let mN=mr(fN),pN=Object.assign(mN,{});var uA=(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))(uA||{});let gN=E.createContext(()=>{});function yN({value:s,children:e}){return zt.createElement(gN.Provider,{value:s},e)}let cA=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 vN=Object.defineProperty,xN=(s,e,t)=>e in s?vN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,bN=(s,e,t)=>(xN(s,e+"",t),t),dA=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},$r=(s,e,t)=>(dA(s,e,"read from private field"),t?t.call(s):e.get(s)),xy=(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)},bS=(s,e,t,i)=>(dA(s,e,"write to private field"),e.set(s,t),t),Ca,nh,rh;let TN=class{constructor(e){xy(this,Ca,{}),xy(this,nh,new cA(()=>new Set)),xy(this,rh,new Set),bN(this,"disposables",Co()),bS(this,Ca,e),Fa.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return $r(this,Ca)}subscribe(e,t){if(Fa.isServer)return()=>{};let i={selector:e,callback:t,current:e($r(this,Ca))};return $r(this,rh).add(i),this.disposables.add(()=>{$r(this,rh).delete(i)})}on(e,t){return Fa.isServer?()=>{}:($r(this,nh).get(e).add(t),this.disposables.add(()=>{$r(this,nh).get(e).delete(t)}))}send(e){let t=this.reduce($r(this,Ca),e);if(t!==$r(this,Ca)){bS(this,Ca,t);for(let i of $r(this,rh)){let n=i.selector($r(this,Ca));hA(i.current,n)||(i.current=n,i.callback(n))}for(let i of $r(this,nh).get(e.type))i($r(this,Ca),e)}}};Ca=new WeakMap,nh=new WeakMap,rh=new WeakMap;function hA(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:by(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:by(s.entries(),e.entries()):TS(s)&&TS(e)?by(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function by(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 TS(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var _N=Object.defineProperty,SN=(s,e,t)=>e in s?_N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_S=(s,e,t)=>(SN(s,typeof e!="symbol"?e+"":e,t),t),EN=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(EN||{});let wN={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}}},AN=class fA extends TN{constructor(){super(...arguments),_S(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),_S(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new fA({stack:[]})}reduce(e,t){return wo(t.type,wN,e,t)}};const mA=new cA(()=>AN.new());var Ty={exports:{}},_y={};var SS;function CN(){if(SS)return _y;SS=1;var s=Up();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,a=s.useMemo,u=s.useDebugValue;return _y.useSyncExternalStoreWithSelector=function(c,d,f,p,y){var v=n(null);if(v.current===null){var b={hasValue:!1,value:null};v.current=b}else b=v.current;v=a(function(){function S(B){if(!L){if(L=!0,I=B,B=p(B),y!==void 0&&b.hasValue){var F=b.value;if(y(F,B))return R=F}return R=B}if(F=R,t(I,B))return F;var M=p(B);return y!==void 0&&y(F,M)?(I=B,F):(I=B,R=M)}var L=!1,I,R,$=f===void 0?null:f;return[function(){return S(d())},$===null?void 0:function(){return S($())}]},[d,f,p,y]);var _=i(c,v[0],v[1]);return r(function(){b.hasValue=!0,b.value=_},[_]),u(_),_},_y}var ES;function kN(){return ES||(ES=1,Ty.exports=CN()),Ty.exports}var DN=kN();function pA(s,e,t=hA){return DN.useSyncExternalStoreWithSelector(hs(i=>s.subscribe(LN,i)),hs(()=>s.state),hs(()=>s.state),hs(e),t)}function LN(s){return s}function $h(s,e){let t=E.useId(),i=mA.get(e),[n,r]=pA(i,E.useCallback(a=>[i.selectors.isTop(a,t),i.selectors.inStack(a,t)],[i,t]));return hr(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let Kv=new Map,hh=new Map;function wS(s){var e;let t=(e=hh.get(s))!=null?e:0;return hh.set(s,t+1),t!==0?()=>AS(s):(Kv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>AS(s))}function AS(s){var e;let t=(e=hh.get(s))!=null?e:1;if(t===1?hh.delete(s):hh.set(s,t-1),t!==1)return;let i=Kv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,Kv.delete(s))}function RN(s,{allowed:e,disallowed:t}={}){let i=$h(s,"inert-others");hr(()=>{var n,r;if(!i)return;let a=Co();for(let c of(n=t?.())!=null?n:[])c&&a.add(wS(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=Uh(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let p of f.children)u.some(y=>p.contains(y))||a.add(wS(p));f=f.parentElement}}return a.dispose},[i,e,t])}function IN(s,e,t){let i=bu(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});E.useEffect(()=>{if(!s)return;let n=e===null?null:gu(e)?e:e.current;if(!n)return;let r=Co();if(typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}if(typeof IntersectionObserver<"u"){let a=new IntersectionObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}return()=>r.dispose()},[e,i,s])}let sp=["[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(","),NN=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var xo=(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))(xo||{}),Wv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(Wv||{}),ON=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(ON||{});function MN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(sp)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function PN(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(NN)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var gA=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(gA||{});function BN(s,e=0){var t;return s===((t=Uh(s))==null?void 0:t.body)?!1:wo(e,{0(){return s.matches(sp)},1(){let i=s;for(;i!==null;){if(i.matches(sp))return!0;i=i.parentElement}return!1}})}var FN=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(FN||{});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 So(s){s?.focus({preventScroll:!0})}let UN=["textarea","input"].join(",");function jN(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,UN))!=null?t:!1}function $N(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 a=n.compareDocumentPosition(r);return a&Node.DOCUMENT_POSITION_FOLLOWING?-1:a&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function fh(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?Vv(s[0]):document:Vv(s),a=Array.isArray(s)?t?$N(s):s:e&64?PN(s):MN(s);n.length>0&&a.length>1&&(a=a.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,a.indexOf(i))-1;if(e&4)return Math.max(0,a.indexOf(i))+1;if(e&8)return a.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,p=a.length,y;do{if(f>=p||f+p<=0)return 0;let v=c+f;if(e&16)v=(v+p)%p;else{if(v<0)return 3;if(v>=p)return 1}y=a[v],y?.focus(d),f+=u}while(y!==rA(y));return e&6&&jN(y)&&y.select(),2}function yA(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function HN(){return/Android/gi.test(window.navigator.userAgent)}function CS(){return yA()||HN()}function mm(s,e,t,i){let n=bu(t);E.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function vA(s,e,t,i){let n=bu(t);E.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const kS=30;function GN(s,e,t){let i=bu(t),n=E.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(y){return typeof y=="function"?p(y()):Array.isArray(y)||y instanceof Set?y:[y]})(e);for(let p of f)if(p!==null&&(p.contains(d)||u.composed&&u.composedPath().includes(p)))return;return!BN(d,gA.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=E.useRef(null);mm(s,"pointerdown",u=>{var c,d;CS()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),mm(s,"pointerup",u=>{if(CS()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let a=E.useRef({x:0,y:0});mm(s,"touchstart",u=>{a.current.x=u.touches[0].clientX,a.current.y=u.touches[0].clientY},!0),mm(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-a.current.x)>=kS||Math.abs(c.y-a.current.y)>=kS))return n(u,()=>Tl(u.target)?u.target:null)},!0),vA(s,"blur",u=>n(u,()=>lN(window.document.activeElement)?window.document.activeElement:null),!0)}function Qx(...s){return E.useMemo(()=>Uh(...s),[...s])}function xA(s,e,t,i){let n=bu(t);E.useEffect(()=>{s=s??window;function r(a){n.current(a)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function VN(s){return E.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function zN(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 a=e[n].call(t,...r);a&&(t=a,i.forEach(u=>u()))}}}function qN(){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 KN(){return yA()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let a of r())if(a.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=Co();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,a=null;e.addEventListener(s,"click",u=>{if(Tl(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);Tl(f)&&!i(f)&&(a=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),Tl(c.target)&&oN(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(Tl(u.target)){if(uN(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),a&&a.isConnected&&(a.scrollIntoView({block:"nearest"}),a=null)})})}}:{}}function WN(){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 ou=zN(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:Co(),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=[KN(),qN(),WN()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});ou.subscribe(()=>{let s=ou.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)&&ou.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&ou.dispatch("TEARDOWN",t)}});function YN(s,e,t=()=>({containers:[]})){let i=VN(ou),n=e?i.get(e):void 0,r=n?n.count>0:!1;return hr(()=>{if(!(!e||!s))return ou.dispatch("PUSH",e,t),()=>ou.dispatch("POP",e,t)},[s,e]),r}function XN(s,e,t=()=>[document.body]){let i=$h(s,"scroll-lock");YN(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function QN(s=0){let[e,t]=E.useState(s),i=E.useCallback(c=>t(c),[]),n=E.useCallback(c=>t(d=>d|c),[]),r=E.useCallback(c=>(e&c)===c,[e]),a=E.useCallback(c=>t(d=>d&~c),[]),u=E.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:a,toggleFlag:u}}var ZN={},LS,RS;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((LS=process==null?void 0:ZN)==null?void 0:LS.NODE_ENV)==="test"&&typeof((RS=Element?.prototype)==null?void 0:RS.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 JN=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(JN||{});function e5(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function t5(s,e,t,i){let[n,r]=E.useState(t),{hasFlag:a,addFlag:u,removeFlag:c}=QN(s&&n?3:0),d=E.useRef(!1),f=E.useRef(!1),p=$p();return hr(()=>{var y;if(s){if(t&&r(!0),!e){t&&u(3);return}return(y=i?.start)==null||y.call(i,t),i5(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&&r5(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,p]),s?[n,{closed:a(1),enter:a(2),leave:a(4),transition:a(2)||a(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function i5(s,{prepare:e,run:t,done:i,inFlight:n}){let r=Co();return n5(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(s5(s,i))})}),r.dispose}function s5(s,e){var t,i;let n=Co();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let a=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return a.length===0?(e(),n.dispose):(Promise.allSettled(a.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function n5(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 r5(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 Zx(s,e){let t=E.useRef([]),i=hs(s);E.useEffect(()=>{let n=[...t.current];for(let[r,a]of e.entries())if(t.current[r]!==a){let u=i(e,n);return t.current=e,u}},[i,...e])}let Hp=E.createContext(null);Hp.displayName="OpenClosedContext";var ra=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(ra||{});function Gp(){return E.useContext(Hp)}function a5({value:s,children:e}){return zt.createElement(Hp.Provider,{value:s},e)}function o5({children:s}){return zt.createElement(Hp.Provider,{value:null},s)}function l5(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let xl=[];l5(()=>{function s(e){if(!Tl(e.target)||e.target===document.body||xl[0]===e.target)return;let t=e.target;t=t.closest(sp),xl.unshift(t??e.target),xl=xl.filter(i=>i!=null&&i.isConnected),xl.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 bA(s){let e=hs(s),t=E.useRef(!1);E.useEffect(()=>(t.current=!1,()=>{t.current=!0,jp(()=>{t.current&&e()})}),[e])}let TA=E.createContext(!1);function u5(){return E.useContext(TA)}function IS(s){return zt.createElement(TA.Provider,{value:s.force},s.children)}function c5(s){let e=u5(),t=E.useContext(SA),[i,n]=E.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(Fa.isServer)return null;let a=s?.getElementById("headlessui-portal-root");if(a)return a;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return E.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),E.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let _A=E.Fragment,d5=mr(function(s,e){let{ownerDocument:t=null,...i}=s,n=E.useRef(null),r=qa(cN(y=>{n.current=y}),e),a=Qx(n.current),u=t??a,c=c5(u),d=E.useContext(Yv),f=$p(),p=Wr();return bA(()=>{var y;c&&c.childNodes.length<=0&&((y=c.parentElement)==null||y.removeChild(c))}),c?kc.createPortal(zt.createElement("div",{"data-headlessui-portal":"",ref:y=>{f.dispose(),d&&y&&f.add(d.register(y))}},p({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:_A,name:"Portal"})),c):null});function h5(s,e){let t=qa(e),{enabled:i=!0,ownerDocument:n,...r}=s,a=Wr();return i?zt.createElement(d5,{...r,ownerDocument:n,ref:t}):a({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:_A,name:"Portal"})}let f5=E.Fragment,SA=E.createContext(null);function m5(s,e){let{target:t,...i}=s,n={ref:qa(e)},r=Wr();return zt.createElement(SA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:f5,name:"Popover.Group"}))}let Yv=E.createContext(null);function p5(){let s=E.useContext(Yv),e=E.useRef([]),t=hs(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=hs(r=>{let a=e.current.indexOf(r);a!==-1&&e.current.splice(a,1),s&&s.unregister(r)}),n=E.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,E.useMemo(()=>function({children:r}){return zt.createElement(Yv.Provider,{value:n},r)},[n])]}let g5=mr(h5),EA=mr(m5),y5=Object.assign(g5,{Group:EA});function v5(s,e=typeof document<"u"?document.defaultView:null,t){let i=$h(s,"escape");xA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===uA.Escape&&t(n))})}function x5(){var s;let[e]=E.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=E.useState((s=e?.matches)!=null?s:!1);return hr(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function b5({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=hs(()=>{var n,r;let a=Uh(t),u=[];for(let c of s)c!==null&&(_l(c)?u.push(c):"current"in c&&_l(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=a?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&_l(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:hs(n=>i().some(r=>r.contains(n)))}}let wA=E.createContext(null);function NS({children:s,node:e}){let[t,i]=E.useState(null),n=AA(e??t);return zt.createElement(wA.Provider,{value:n},s,n===null&&zt.createElement(qv,{features:ip.Hidden,ref:r=>{var a,u;if(r){for(let c of(u=(a=Uh(r))==null?void 0:a.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&_l(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function AA(s=null){var e;return(e=E.useContext(wA))!=null?e:s}function T5(){let s=typeof document>"u";return"useSyncExternalStore"in fS?(e=>e.useSyncExternalStore)(fS)(()=>()=>{},()=>!1,()=>!s):!1}function Vp(){let s=T5(),[e,t]=E.useState(Fa.isHandoffComplete);return e&&Fa.isHandoffComplete===!1&&t(!1),E.useEffect(()=>{e!==!0&&t(!0)},[e]),E.useEffect(()=>Fa.handoff(),[]),s?!1:e}function Jx(){let s=E.useRef(!1);return hr(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var ah=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(ah||{});function _5(){let s=E.useRef(0);return vA(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function CA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)_l(t.current)&&e.add(t.current);return e}let S5="div";var ru=(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))(ru||{});function E5(s,e){let t=E.useRef(null),i=qa(t,e),{initialFocus:n,initialFocusFallback:r,containers:a,features:u=15,...c}=s;Vp()||(u=0);let d=Qx(t.current);k5(u,{ownerDocument:d});let f=D5(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});L5(u,{ownerDocument:d,container:t,containers:a,previousActiveElement:f});let p=_5(),y=hs(I=>{if(!gu(t.current))return;let R=t.current;($=>$())(()=>{wo(p.current,{[ah.Forwards]:()=>{fh(R,xo.First,{skipElements:[I.relatedTarget,r]})},[ah.Backwards]:()=>{fh(R,xo.Last,{skipElements:[I.relatedTarget,r]})}})})}),v=$h(!!(u&2),"focus-trap#tab-lock"),b=$p(),_=E.useRef(!1),S={ref:i,onKeyDown(I){I.key=="Tab"&&(_.current=!0,b.requestAnimationFrame(()=>{_.current=!1}))},onBlur(I){if(!(u&4))return;let R=CA(a);gu(t.current)&&R.add(t.current);let $=I.relatedTarget;Tl($)&&$.dataset.headlessuiFocusGuard!=="true"&&(kA(R,$)||(_.current?fh(t.current,wo(p.current,{[ah.Forwards]:()=>xo.Next,[ah.Backwards]:()=>xo.Previous})|xo.WrapAround,{relativeTo:I.target}):Tl(I.target)&&So(I.target)))}},L=Wr();return zt.createElement(zt.Fragment,null,v&&zt.createElement(qv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:ip.Focusable}),L({ourProps:S,theirProps:c,defaultTag:S5,name:"FocusTrap"}),v&&zt.createElement(qv,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:ip.Focusable}))}let w5=mr(E5),A5=Object.assign(w5,{features:ru});function C5(s=!0){let e=E.useRef(xl.slice());return Zx(([t],[i])=>{i===!0&&t===!1&&jp(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=xl.slice())},[s,xl,e]),hs(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function k5(s,{ownerDocument:e}){let t=!!(s&8),i=C5(t);Zx(()=>{t||XI(e?.body)&&So(i())},[t]),bA(()=>{t&&So(i())})}function D5(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=E.useRef(null),a=$h(!!(s&1),"focus-trap#initial-focus"),u=Jx();return Zx(()=>{if(s===0)return;if(!a){n!=null&&n.current&&So(n.current);return}let c=t.current;c&&jp(()=>{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)So(i.current);else{if(s&16){if(fh(c,xo.First|xo.AutoFocus)!==Wv.Error)return}else if(fh(c,xo.First)!==Wv.Error)return;if(n!=null&&n.current&&(So(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,a,s]),r}function L5(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=Jx(),a=!!(s&4);xA(e?.defaultView,"focus",u=>{if(!a||!r.current)return;let c=CA(i);gu(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;gu(f)?kA(c,f)?(n.current=f,So(f)):(u.preventDefault(),u.stopPropagation(),So(d)):So(n.current)},!0)}function kA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function DA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!dh((e=s.as)!=null?e:RA)||zt.Children.count(s.children)===1}let zp=E.createContext(null);zp.displayName="TransitionContext";var R5=(s=>(s.Visible="visible",s.Hidden="hidden",s))(R5||{});function I5(){let s=E.useContext(zp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function N5(){let s=E.useContext(qp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let qp=E.createContext(null);qp.displayName="NestingContext";function Kp(s){return"children"in s?Kp(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function LA(s,e){let t=bu(s),i=E.useRef([]),n=Jx(),r=$p(),a=hs((v,b=bl.Hidden)=>{let _=i.current.findIndex(({el:S})=>S===v);_!==-1&&(wo(b,{[bl.Unmount](){i.current.splice(_,1)},[bl.Hidden](){i.current[_].state="hidden"}}),r.microTask(()=>{var S;!Kp(i)&&n.current&&((S=t.current)==null||S.call(t))}))}),u=hs(v=>{let b=i.current.find(({el:_})=>_===v);return b?b.state!=="visible"&&(b.state="visible"):i.current.push({el:v,state:"visible"}),()=>a(v,bl.Unmount)}),c=E.useRef([]),d=E.useRef(Promise.resolve()),f=E.useRef({enter:[],leave:[]}),p=hs((v,b,_)=>{c.current.splice(0),e&&(e.chains.current[b]=e.chains.current[b].filter(([S])=>S!==v)),e?.chains.current[b].push([v,new Promise(S=>{c.current.push(S)})]),e?.chains.current[b].push([v,new Promise(S=>{Promise.all(f.current[b].map(([L,I])=>I)).then(()=>S())})]),b==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>_(b)):_(b)}),y=hs((v,b,_)=>{Promise.all(f.current[b].splice(0).map(([S,L])=>L)).then(()=>{var S;(S=c.current.shift())==null||S()}).then(()=>_(b))});return E.useMemo(()=>({children:i,register:u,unregister:a,onStart:p,onStop:y,wait:d,chains:f}),[u,a,i,p,y,f,d])}let RA=E.Fragment,IA=tp.RenderStrategy;function O5(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:a,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:p,entered:y,leave:v,leaveFrom:b,leaveTo:_,...S}=s,[L,I]=E.useState(null),R=E.useRef(null),$=DA(s),B=qa(...$?[R,e,I]:e===null?[]:[e]),F=(t=S.unmount)==null||t?bl.Unmount:bl.Hidden,{show:M,appear:G,initial:D}=I5(),[O,W]=E.useState(M?"visible":"hidden"),Y=N5(),{register:J,unregister:ae}=Y;hr(()=>J(R),[J,R]),hr(()=>{if(F===bl.Hidden&&R.current){if(M&&O!=="visible"){W("visible");return}return wo(O,{hidden:()=>ae(R),visible:()=>J(R)})}},[O,R,J,ae,M,F]);let se=Vp();hr(()=>{if($&&se&&O==="visible"&&R.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[R,O,se,$]);let K=D&&!G,X=G&&M&&D,ee=E.useRef(!1),le=LA(()=>{ee.current||(W("hidden"),ae(R))},Y),pe=hs(Ee=>{ee.current=!0;let Ge=Ee?"enter":"leave";le.onStart(R,Ge,Ve=>{Ve==="enter"?r?.():Ve==="leave"&&u?.()})}),P=hs(Ee=>{let Ge=Ee?"enter":"leave";ee.current=!1,le.onStop(R,Ge,Ve=>{Ve==="enter"?a?.():Ve==="leave"&&c?.()}),Ge==="leave"&&!Kp(le)&&(W("hidden"),ae(R))});E.useEffect(()=>{$&&n||(pe(M),P(M))},[M,$,n]);let Q=!(!n||!$||!se||K),[,ue]=t5(Q,L,M,{start:pe,end:P}),he=tu({ref:B,className:((i=zv(S.className,X&&d,X&&f,ue.enter&&d,ue.enter&&ue.closed&&f,ue.enter&&!ue.closed&&p,ue.leave&&v,ue.leave&&!ue.closed&&b,ue.leave&&ue.closed&&_,!ue.transition&&M&&y))==null?void 0:i.trim())||void 0,...e5(ue)}),re=0;O==="visible"&&(re|=ra.Open),O==="hidden"&&(re|=ra.Closed),M&&O==="hidden"&&(re|=ra.Opening),!M&&O==="visible"&&(re|=ra.Closing);let Pe=Wr();return zt.createElement(qp.Provider,{value:le},zt.createElement(a5,{value:re},Pe({ourProps:he,theirProps:S,defaultTag:RA,features:IA,visible:O==="visible",name:"Transition.Child"})))}function M5(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,a=E.useRef(null),u=DA(s),c=qa(...u?[a,e]:e===null?[]:[e]);Vp();let d=Gp();if(t===void 0&&d!==null&&(t=(d&ra.Open)===ra.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,p]=E.useState(t?"visible":"hidden"),y=LA(()=>{t||p("hidden")}),[v,b]=E.useState(!0),_=E.useRef([t]);hr(()=>{v!==!1&&_.current[_.current.length-1]!==t&&(_.current.push(t),b(!1))},[_,t]);let S=E.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);hr(()=>{t?p("visible"):!Kp(y)&&a.current!==null&&p("hidden")},[t,y]);let L={unmount:n},I=hs(()=>{var B;v&&b(!1),(B=s.beforeEnter)==null||B.call(s)}),R=hs(()=>{var B;v&&b(!1),(B=s.beforeLeave)==null||B.call(s)}),$=Wr();return zt.createElement(qp.Provider,{value:y},zt.createElement(zp.Provider,{value:S},$({ourProps:{...L,as:E.Fragment,children:zt.createElement(NA,{ref:c,...L,...r,beforeEnter:I,beforeLeave:R})},theirProps:{},defaultTag:E.Fragment,features:IA,visible:f==="visible",name:"Transition"})))}function P5(s,e){let t=E.useContext(zp)!==null,i=Gp()!==null;return zt.createElement(zt.Fragment,null,!t&&i?zt.createElement(Xv,{ref:e,...s}):zt.createElement(NA,{ref:e,...s}))}let Xv=mr(M5),NA=mr(O5),eb=mr(P5),mh=Object.assign(Xv,{Child:eb,Root:Xv});var B5=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(B5||{}),F5=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(F5||{});let U5={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},tb=E.createContext(null);tb.displayName="DialogContext";function Wp(s){let e=E.useContext(tb);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,Wp),t}return e}function j5(s,e){return wo(e.type,U5,s,e)}let OS=mr(function(s,e){let t=E.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:a,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...p}=s,y=E.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(y.current||(y.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=Gp();n===void 0&&v!==null&&(n=(v&ra.Open)===ra.Open);let b=E.useRef(null),_=qa(b,e),S=Qx(b.current),L=n?0:1,[I,R]=E.useReducer(j5,{titleId:null,descriptionId:null,panelRef:E.createRef()}),$=hs(()=>r(!1)),B=hs(ue=>R({type:0,id:ue})),F=Vp()?L===0:!1,[M,G]=p5(),D={get current(){var ue;return(ue=I.panelRef.current)!=null?ue:b.current}},O=AA(),{resolveContainers:W}=b5({mainTreeNode:O,portals:M,defaultContainers:[D]}),Y=v!==null?(v&ra.Closing)===ra.Closing:!1;RN(d||Y?!1:F,{allowed:hs(()=>{var ue,he;return[(he=(ue=b.current)==null?void 0:ue.closest("[data-headlessui-portal]"))!=null?he:null]}),disallowed:hs(()=>{var ue;return[(ue=O?.closest("body > *:not(#headlessui-portal-root)"))!=null?ue:null]})});let J=mA.get(null);hr(()=>{if(F)return J.actions.push(i),()=>J.actions.pop(i)},[J,i,F]);let ae=pA(J,E.useCallback(ue=>J.selectors.isTop(ue,i),[J,i]));GN(ae,W,ue=>{ue.preventDefault(),$()}),v5(ae,S?.defaultView,ue=>{ue.preventDefault(),ue.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),$()}),XN(d||Y?!1:F,S,W),IN(F,b,$);let[se,K]=dN(),X=E.useMemo(()=>[{dialogState:L,close:$,setTitleId:B,unmount:f},I],[L,$,B,f,I]),ee=jh({open:L===0}),le={ref:_,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:L===0?!0:void 0,"aria-labelledby":I.titleId,"aria-describedby":se,unmount:f},pe=!x5(),P=ru.None;F&&!d&&(P|=ru.RestoreFocus,P|=ru.TabLock,c&&(P|=ru.AutoFocus),pe&&(P|=ru.InitialFocus));let Q=Wr();return zt.createElement(o5,null,zt.createElement(IS,{force:!0},zt.createElement(y5,null,zt.createElement(tb.Provider,{value:X},zt.createElement(EA,{target:b},zt.createElement(IS,{force:!1},zt.createElement(K,{slot:ee},zt.createElement(G,null,zt.createElement(A5,{initialFocus:a,initialFocusFallback:b,containers:W,features:P},zt.createElement(yN,{value:$},Q({ourProps:le,theirProps:p,slot:ee,defaultTag:$5,features:H5,visible:L===0,name:"Dialog"})))))))))))}),$5="div",H5=tp.RenderStrategy|tp.Static;function G5(s,e){let{transition:t=!1,open:i,...n}=s,r=Gp(),a=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!a&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!a)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?zt.createElement(NS,null,zt.createElement(mh,{show:i,transition:t,unmount:n.unmount},zt.createElement(OS,{ref:e,...n}))):zt.createElement(NS,null,zt.createElement(OS,{ref:e,open:i,...n}))}let V5="div";function z5(s,e){let t=E.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:a,unmount:u},c]=Wp("Dialog.Panel"),d=qa(e,c.panelRef),f=jh({open:a===0}),p=hs(S=>{S.stopPropagation()}),y={ref:d,id:i,onClick:p},v=n?eb:E.Fragment,b=n?{unmount:u}:{},_=Wr();return zt.createElement(v,{...b},_({ourProps:y,theirProps:r,slot:f,defaultTag:V5,name:"Dialog.Panel"}))}let q5="div";function K5(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=Wp("Dialog.Backdrop"),a=jh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?eb:E.Fragment,d=t?{unmount:r}:{},f=Wr();return zt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:a,defaultTag:q5,name:"Dialog.Backdrop"}))}let W5="h2";function Y5(s,e){let t=E.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:a}]=Wp("Dialog.Title"),u=qa(e);E.useEffect(()=>(a(i),()=>a(null)),[i,a]);let c=jh({open:r===0}),d={ref:u,id:i};return Wr()({ourProps:d,theirProps:n,slot:c,defaultTag:W5,name:"Dialog.Title"})}let X5=mr(G5),Q5=mr(z5);mr(K5);let Z5=mr(Y5),mc=Object.assign(X5,{Panel:Q5,Title:Z5,Description:pN});function J5({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=E.useState(""),[a,u]=E.useState(""),[c,d]=E.useState([]),f=E.useRef(!1);E.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function p(){const b=n.trim(),_=a.trim();!b||!_||(d(S=>[...S.filter(I=>I.name!==b),{name:b,value:_}]),r(""),u(""))}function y(b){d(_=>_.filter(S=>S.name!==b))}function v(){t(c),e()}return g.jsxs(mc,{open:s,onClose:e,className:"relative z-50",children:[g.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),g.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:g.jsxs(mc.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:[g.jsx(mc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),g.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[g.jsx("input",{value:n,onChange:b=>r(b.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"}),g.jsx("input",{value:a,onChange:b=>u(b.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"})]}),g.jsx("div",{className:"mt-2",children:g.jsx(ti,{size:"sm",variant:"secondary",onClick:p,disabled:!n.trim()||!a.trim(),children:"Hinzufügen"})}),g.jsx("div",{className:"mt-4",children:c.length===0?g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):g.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[g.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:g.jsxs("tr",{children:[g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),g.jsx("th",{className:"px-3 py-2"})]})}),g.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(b=>g.jsxs("tr",{children:[g.jsx("td",{className:"px-3 py-2 font-mono",children:b.name}),g.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:b.value}),g.jsx("td",{className:"px-3 py-2 text-right",children:g.jsx("button",{onClick:()=>y(b.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},b.name))})]})}),g.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[g.jsx(ti,{variant:"secondary",onClick:e,children:"Abbrechen"}),g.jsx(ti,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function eO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 tO=E.forwardRef(eO);function MS({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:a=!1}){if(!s?.length)return null;const u=s.find(y=>y.id===e)??s[0],c=xi("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=y=>xi(y?"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",a?"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=(y,v)=>v.count===void 0?null:g.jsx("span",{className:d(y),children:v.count}),p=()=>{switch(r){case"underline":case"underlineIcons":return g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:xi(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"&&y.icon?g.jsx(y.icon,{"aria-hidden":"true",className:xi(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,g.jsx("span",{children:y.label}),f(v,y)]},y.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const y=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 g.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(b=>{const _=b.id===u.id,S=!!b.disabled;return g.jsxs("button",{type:"button",onClick:()=>!S&&t(b.id),disabled:S,"aria-current":_?"page":void 0,className:xi(_?y:v,"inline-flex items-center rounded-md px-3 py-2 text-sm font-medium",S&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:[g.jsx("span",{children:b.label}),b.count!==void 0?g.jsx("span",{className:xi(_?"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 g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:xi(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:y.label},y.id)})})});case"barUnderline":return g.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((y,v)=>{const b=y.id===u.id,_=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!_&&t(y.id),disabled:_,"aria-current":b?"page":void 0,className:xi(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:[g.jsxs("span",{className:"inline-flex items-center justify-center",children:[y.label,y.count!==void 0?g.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:y.count}):null]}),g.jsx("span",{"aria-hidden":"true",className:xi(b?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},y.id)})});case"simple":return g.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:g.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(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("li",{children:g.jsx("button",{type:"button",onClick:()=>!b&&t(y.id),disabled:b,"aria-current":v?"page":void 0,className:xi(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:y.label})},y.id)})})});default:return null}};return g.jsxs("div",{className:i,children:[g.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[g.jsx("select",{value:u.id,onChange:y=>t(y.target.value),"aria-label":n,className:c,children:s.map(y=>g.jsx("option",{value:y.id,children:y.label},y.id))}),g.jsx(tO,{"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"})]}),g.jsx("div",{className:"hidden sm:block",children:p()})]})}function ja({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:a=!1,className:u,bodyClassName:c,children:d}){const f=r;return g.jsxs("div",{className:xi("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&&g.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),g.jsx("div",{className:xi("min-h-0",a?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&g.jsx("div",{className:xi("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 Qv({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:a,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:p}){const y=b=>{n||e(b.target.checked)},v=xi("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?g.jsxs("div",{className:xi("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:[g.jsx("span",{className:xi("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")}),g.jsx("span",{className:xi("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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]}):g.jsxs("div",{className:xi("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"?g.jsxs("span",{className:xi("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:[g.jsx("span",{"aria-hidden":"true",className:xi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:g.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:g.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx("span",{"aria-hidden":"true",className:xi("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:g.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:g.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"})})})]}):g.jsx("span",{className:xi("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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function po({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const a=E.useId(),u=i??`sw-${a}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?g.jsxs("div",{className:xi("flex items-center justify-between gap-3",n),children:[g.jsx(Qv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),g.jsxs("div",{className:"text-sm",children:[g.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?g.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):g.jsxs("div",{className:xi("flex items-center justify-between",n),children:[g.jsxs("span",{className:"flex grow flex-col",children:[g.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?g.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),g.jsx(Qv,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}function Dc({label:s,value:e=0,indeterminate:t=!1,showPercent:i=!1,rightLabel:n,steps:r,currentStep:a,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,y=p?r.length:0,v=S=>S===0?"text-left":S===y-1?"text-right":"text-center",b=S=>typeof a!="number"||!Number.isFinite(a)?!1:S<=a,_=i&&!t;return g.jsxs("div",{className:c,children:[s||_?g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s?g.jsx("p",{className:"flex-1 min-w-0 truncate text-xs font-medium text-gray-900 dark:text-white",children:s}):g.jsx("span",{className:"flex-1"}),_?g.jsxs("span",{className:"shrink-0 text-xs font-medium text-gray-700 dark:text-gray-300",children:[Math.round(d),"%"]}):null]}):null,g.jsxs("div",{"aria-hidden":"true",className:s||_?"mt-2":"",children:[g.jsx("div",{className:"overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:t?g.jsx("div",{className:`${f} w-full rounded-full bg-indigo-600/70 dark:bg-indigo-500/70 animate-pulse`}):g.jsx("div",{className:`${f} rounded-full bg-indigo-600 dark:bg-indigo-500 transition-[width] duration-200`,style:{width:`${d}%`}})}),n?g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:n}):null,p?g.jsx("div",{className:"mt-3 hidden text-sm font-medium text-gray-600 sm:grid dark:text-gray-400",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:r.map((S,L)=>g.jsx("div",{className:[v(L),b(L)?"text-indigo-600 dark:text-indigo-400":""].join(" "),children:S},`${L}-${S}`))}):null]})]})}async function PS(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 iO({onFinished:s}){const[e,t]=E.useState(null),[i,n]=E.useState(null),[r,a]=E.useState(!1),[u,c]=E.useState(!1),d=E.useCallback(async()=>{try{const $=await PS("/api/tasks/generate-assets");t($)}catch($){n($?.message??String($))}},[]),f=E.useRef(!1);E.useEffect(()=>{const $=f.current,B=!!e?.running;f.current=B,$&&!B&&s?.()},[e?.running,s]),E.useEffect(()=>{d()},[d]),E.useEffect(()=>{if(!e?.running)return;const $=window.setInterval(d,1200);return()=>window.clearInterval($)},[e?.running,d]);async function p(){n(null),a(!0);try{const $=await PS("/api/tasks/generate-assets",{method:"POST"});t($)}catch($){n($?.message??String($))}finally{a(!1)}}async function y(){n(null),c(!0);try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}finally{await d(),c(!1)}}const v=!!e?.running,b=e?.total??0,_=e?.done??0,S=b>0?Math.min(100,Math.round(_/b*100)):0,L=$=>{const B=String($??"").trim();if(!B)return null;const F=new Date(B);return Number.isFinite(F.getTime())?F.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):null},I=L(e?.startedAt),R=L(e?.finishedAt);return g.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:[g.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Assets-Generator"}),v?g.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"}):g.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"})]}),g.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-white/70",children:["Erzeugt pro fertiger Datei unter ",g.jsx("span",{className:"font-mono",children:"/generated//"})," ",g.jsx("span",{className:"font-mono",children:"thumbs.jpg"}),", ",g.jsx("span",{className:"font-mono",children:"preview.mp4"})," ","und ",g.jsx("span",{className:"font-mono",children:"meta.json"})," für schnelle Listen & zuverlässige Duration."]})]}),g.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[v?g.jsx(ti,{variant:"secondary",color:"red",onClick:y,disabled:u,className:"w-full sm:w-auto",children:u?"Stoppe…":"Stop"}):null,g.jsx(ti,{variant:"primary",onClick:p,disabled:r||v,className:"w-full sm:w-auto",children:r?"Starte…":v?"Läuft…":"Generieren"})]})]}),i?g.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?g.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?g.jsxs("div",{className:"mt-4 space-y-3",children:[g.jsx(Dc,{value:S,showPercent:!0,rightLabel:b?`${_}/${b} Dateien`:"—"}),g.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Thumbs"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedThumbs??0})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Previews"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.generatedPreviews??0})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-[11px] font-medium text-gray-600 dark:text-white/70",children:"Übersprungen"}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold tabular-nums text-gray-900 dark:text-white",children:e.skipped??0})]})]}),g.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:[g.jsx("span",{children:I?g.jsxs(g.Fragment,{children:["Start: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:I})]}):"Start: —"}),g.jsx("span",{children:R?g.jsxs(g.Fragment,{children:["Ende: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R})]}):"Ende: —"})]})]}):g.jsx("div",{className:"mt-4 text-xs text-gray-600 dark:text-white/70",children:"Status wird geladen…"})]})}const Vs={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!0,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:5,enableNotifications:!0};function sO({onAssetsGenerated:s}){const[e,t]=E.useState(Vs),[i,n]=E.useState(!1),[r,a]=E.useState(!1),[u,c]=E.useState(null),[d,f]=E.useState(null),[p,y]=E.useState(null),[v,b]=E.useState(null),_=Number(e.lowDiskPauseBelowGB??Vs.lowDiskPauseBelowGB??5),S=v?.pauseGB??_,L=v?.resumeGB??_+3;E.useEffect(()=>{let B=!0;return fetch("/api/settings",{cache:"no-store"}).then(async F=>{if(!F.ok)throw new Error(await F.text());return F.json()}).then(F=>{B&&t({recordDir:(F.recordDir||Vs.recordDir).toString(),doneDir:(F.doneDir||Vs.doneDir).toString(),ffmpegPath:String(F.ffmpegPath??Vs.ffmpegPath??""),autoAddToDownloadList:F.autoAddToDownloadList??Vs.autoAddToDownloadList,autoStartAddedDownloads:F.autoStartAddedDownloads??Vs.autoStartAddedDownloads,useChaturbateApi:F.useChaturbateApi??Vs.useChaturbateApi,useMyFreeCamsWatcher:F.useMyFreeCamsWatcher??Vs.useMyFreeCamsWatcher,autoDeleteSmallDownloads:F.autoDeleteSmallDownloads??Vs.autoDeleteSmallDownloads,autoDeleteSmallDownloadsBelowMB:F.autoDeleteSmallDownloadsBelowMB??Vs.autoDeleteSmallDownloadsBelowMB,blurPreviews:F.blurPreviews??Vs.blurPreviews,teaserPlayback:F.teaserPlayback??Vs.teaserPlayback,teaserAudio:F.teaserAudio??Vs.teaserAudio,lowDiskPauseBelowGB:F.lowDiskPauseBelowGB??Vs.lowDiskPauseBelowGB,enableNotifications:F.enableNotifications??Vs.enableNotifications})}).catch(()=>{}),()=>{B=!1}},[]),E.useEffect(()=>{let B=!0;const F=async()=>{try{const G=await fetch("/api/status/disk",{cache:"no-store"});if(!G.ok)return;const D=await G.json();B&&b(D)}catch{}};F();const M=window.setInterval(F,5e3);return()=>{B=!1,window.clearInterval(M)}},[]);async function I(B){y(null),f(null),c(B);try{window.focus();const F=await fetch(`/api/settings/browse?target=${B}`,{cache:"no-store"});if(F.status===204)return;if(!F.ok){const D=await F.text().catch(()=>"");throw new Error(D||`HTTP ${F.status}`)}const G=((await F.json()).path??"").trim();if(!G)return;t(D=>B==="record"?{...D,recordDir:G}:B==="done"?{...D,doneDir:G}:{...D,ffmpegPath:G})}catch(F){y(F?.message??String(F))}finally{c(null)}}async function R(){y(null),f(null);const B=e.recordDir.trim(),F=e.doneDir.trim(),M=(e.ffmpegPath??"").trim();if(!B||!F){y("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const G=!!e.autoAddToDownloadList,D=G?!!e.autoStartAddedDownloads:!1,O=!!e.useChaturbateApi,W=!!e.useMyFreeCamsWatcher,Y=!!e.autoDeleteSmallDownloads,J=Math.max(0,Math.min(1e5,Math.floor(Number(e.autoDeleteSmallDownloadsBelowMB??Vs.autoDeleteSmallDownloadsBelowMB)))),ae=!!e.blurPreviews,se=e.teaserPlayback==="still"||e.teaserPlayback==="all"||e.teaserPlayback==="hover"?e.teaserPlayback:Vs.teaserPlayback,K=!!e.teaserAudio,X=Math.max(1,Math.floor(Number(e.lowDiskPauseBelowGB??Vs.lowDiskPauseBelowGB))),ee=!!e.enableNotifications;n(!0);try{const le=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:B,doneDir:F,ffmpegPath:M,autoAddToDownloadList:G,autoStartAddedDownloads:D,useChaturbateApi:O,useMyFreeCamsWatcher:W,autoDeleteSmallDownloads:Y,autoDeleteSmallDownloadsBelowMB:J,blurPreviews:ae,teaserPlayback:se,teaserAudio:K,lowDiskPauseBelowGB:X,enableNotifications:ee})});if(!le.ok){const pe=await le.text().catch(()=>"");throw new Error(pe||`HTTP ${le.status}`)}f("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(le){y(le?.message??String(le))}finally{n(!1)}}async function $(){y(null),f(null);const B=Number(e.autoDeleteSmallDownloadsBelowMB??Vs.autoDeleteSmallDownloadsBelowMB??0),F=(e.doneDir||Vs.doneDir).trim();if(!F){y("doneDir ist leer.");return}if(!B||B<=0){y("Mindestgröße ist 0 – es würde nichts gelöscht.");return}if(window.confirm(`Aufräumen: +• Löscht Dateien in "${F}" < ${B} MB (Ordner "keep" wird übersprungen) +• Entfernt verwaiste Previews/Thumbs/Generated-Assets ohne passende Datei + +Fortfahren?`)){a(!0);try{const G=await fetch("/api/settings/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store"});if(!G.ok){const O=await G.text().catch(()=>"");throw new Error(O||`HTTP ${G.status}`)}const D=await G.json();f(`🧹 Aufräumen fertig: +• Gelöscht: ${D.deletedFiles} Datei(en) (${D.deletedBytesHuman}) +• Geprüft: ${D.scannedFiles} · Übersprungen: ${D.skippedFiles} · Fehler: ${D.errorCount} +• Orphans: ${D.orphanIdsRemoved}/${D.orphanIdsScanned} entfernt (Previews/Thumbs/Generated)`)}catch(G){y(G?.message??String(G))}finally{a(!1)}}}return g.jsx(ja,{header:g.jsxs("div",{className:"flex items-center justify-between gap-4",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"}),g.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Recorder-Konfiguration, Automatisierung und Tasks."})]}),g.jsx(ti,{variant:"primary",onClick:R,disabled:i,children:"Speichern"})]}),grayBody:!0,children:g.jsxs("div",{className:"space-y-4",children:[p&&g.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:p}),d&&g.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:d}),g.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:[g.jsxs("div",{className:"flex items-start justify-between gap-4",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tasks"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Generiere fehlende Vorschauen/Metadaten für schnelle Listenansichten."})]}),g.jsx("div",{className:"shrink-0",children:g.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"})})]}),g.jsx("div",{className:"mt-3",children:g.jsx(iO,{onFinished:s})})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Pfad-Einstellungen"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aufnahme- und Zielverzeichnisse sowie optionaler ffmpeg-Pfad."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.recordDir,onChange:B=>t(F=>({...F,recordDir:B.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`}),g.jsx(ti,{variant:"secondary",onClick:()=>I("record"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.doneDir,onChange:B=>t(F=>({...F,doneDir:B.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`}),g.jsx(ti,{variant:"secondary",onClick:()=>I("done"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.ffmpegPath??"",onChange:B=>t(F=>({...F,ffmpegPath:B.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`}),g.jsx(ti,{variant:"secondary",onClick:()=>I("ffmpeg"),disabled:i||u!==null,children:"Durchsuchen..."})]})]})]})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Automatisierung & Anzeige"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Verhalten beim Hinzufügen/Starten sowie Anzeigeoptionen."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsx(po,{checked:!!e.autoAddToDownloadList,onChange:B=>t(F=>({...F,autoAddToDownloadList:B,autoStartAddedDownloads:B?F.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),g.jsx(po,{checked:!!e.autoStartAddedDownloads,onChange:B=>t(F=>({...F,autoStartAddedDownloads:B})),disabled:!e.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),g.jsx(po,{checked:!!e.useChaturbateApi,onChange:B=>t(F=>({...F,useChaturbateApi:B})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),g.jsx(po,{checked:!!e.useMyFreeCamsWatcher,onChange:B=>t(F=>({...F,useMyFreeCamsWatcher:B})),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."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx(po,{checked:!!e.autoDeleteSmallDownloads,onChange:B=>t(F=>({...F,autoDeleteSmallDownloads:B,autoDeleteSmallDownloadsBelowMB:F.autoDeleteSmallDownloadsBelowMB??50})),label:"Kleine Downloads automatisch löschen",description:"Löscht fertige Downloads automatisch, wenn die Datei kleiner als die eingestellte Mindestgröße ist."}),g.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:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Mindestgröße"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Alles darunter wird gelöscht."})]}),g.jsx("div",{className:"sm:col-span-8",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("input",{type:"number",min:0,step:1,value:e.autoDeleteSmallDownloadsBelowMB??50,onChange:B=>t(F=>({...F,autoDeleteSmallDownloadsBelowMB:Number(B.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`}),g.jsx("span",{className:"shrink-0 text-xs text-gray-600 dark:text-gray-300",children:"MB"}),g.jsx(ti,{variant:"secondary",onClick:$,disabled:i||r||!e.autoDeleteSmallDownloads,className:"h-9 shrink-0 px-3",title:"Löscht Dateien im doneDir kleiner als die Mindestgröße (keep wird übersprungen)",children:r?"…":"Aufräumen"})]})})]})]}),g.jsx(po,{checked:!!e.blurPreviews,onChange:B=>t(F=>({...F,blurPreviews:B})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Teaser abspielen"}),g.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."})]}),g.jsxs("div",{className:"sm:col-span-8",children:[g.jsx("label",{className:"sr-only",htmlFor:"teaserPlayback",children:"Teaser abspielen"}),g.jsxs("select",{id:"teaserPlayback",value:e.teaserPlayback??"hover",onChange:B=>t(F=>({...F,teaserPlayback:B.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:[g.jsx("option",{value:"still",children:"Standbild"}),g.jsx("option",{value:"hover",children:"Bei Hover (Standard)"}),g.jsx("option",{value:"all",children:"Alle"})]})]})]}),g.jsx(po,{checked:!!e.teaserAudio,onChange:B=>t(F=>({...F,teaserAudio:B})),label:"Teaser mit Ton",description:"Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet."}),g.jsx(po,{checked:!!e.enableNotifications,onChange:B=>t(F=>({...F,enableNotifications:B})),label:"Benachrichtigungen",description:"Wenn aktiv, zeigt das Frontend Toasts (z.B. wenn watched Models online/live gehen oder wenn ein queued Model wieder public wird)."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Speicherplatz-Notbremse"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aktiviert automatisch Stop + Autostart-Block bei wenig freiem Speicher (Resume bei +3 GB)."})]}),g.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium "+(v?.emergency?"bg-red-100 text-red-800 dark:bg-red-500/20 dark:text-red-200":"bg-green-100 text-green-800 dark:bg-green-500/20 dark:text-green-200"),title:v?.emergency?"Notfallbremse greift gerade":"OK",children:v?.emergency?"AKTIV":"OK"})]}),g.jsxs("div",{className:"mt-3 text-sm text-gray-900 dark:text-gray-200",children:[g.jsxs("div",{children:[g.jsx("span",{className:"font-medium",children:"Schwelle:"})," ","Pause unter ",g.jsx("span",{className:"tabular-nums",children:S})," GB"," · ","Resume ab"," ",g.jsx("span",{className:"tabular-nums",children:L})," ","GB"]}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:v?`Frei: ${v.freeBytesHuman}${v.recordPath?` (Pfad: ${v.recordPath})`:""}`:"Status wird geladen…"}),v?.emergency&&g.jsx("div",{className:"mt-2 text-xs text-red-700 dark:text-red-200",children:"Notfallbremse greift: laufende Downloads werden gestoppt und Autostart bleibt gesperrt, bis wieder genug frei ist."})]})]})]})]})]})})}function nO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 rO=E.forwardRef(nO);function aO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 oO=E.forwardRef(aO);function lO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 uO=E.forwardRef(lO);function cO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 dO=E.forwardRef(cO);function rr(...s){return s.filter(Boolean).join(" ")}function BS(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 FS(s,e){const t=s===0,i=s===e-1;return t||i?"pl-2 pr-2":"px-2"}function US(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 ph({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:a=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:p=!1,emptyLabel:y="Keine Daten vorhanden.",className:v,rowClassName:b,onRowClick:_,onRowContextMenu:S,sort:L,onSortChange:I,defaultSort:R=null}){const $=f?"py-2":"py-4",B=f?"py-3":"py-3.5",F=L!==void 0,[M,G]=E.useState(R),D=F?L:M,O=E.useCallback(Y=>{F||G(Y),I?.(Y)},[F,I]),W=E.useMemo(()=>{if(!D)return e;const Y=s.find(se=>se.key===D.key);if(!Y)return e;const J=D.direction==="asc"?1:-1,ae=e.map((se,K)=>({r:se,i:K}));return ae.sort((se,K)=>{let X=0;if(Y.sortFn)X=Y.sortFn(se.r,K.r);else{const ee=Y.sortValue?Y.sortValue(se.r):se.r?.[Y.key],le=Y.sortValue?Y.sortValue(K.r):K.r?.[Y.key],pe=US(ee),P=US(le);pe.isNull&&!P.isNull?X=1:!pe.isNull&&P.isNull?X=-1:pe.kind==="number"&&P.kind==="number"?X=pe.valueP.value?1:0:X=String(pe.value).localeCompare(String(P.value),void 0,{numeric:!0})}return X===0?se.i-K.i:X*J}),ae.map(se=>se.r)},[e,s,D]);return g.jsxs("div",{className:rr(a?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&g.jsxs("div",{className:"sm:flex sm:items-center",children:[g.jsxs("div",{className:"sm:flex-auto",children:[i&&g.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&g.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&g.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),g.jsx("div",{className:rr(i||n||r?"mt-8":""),children:g.jsx("div",{className:"flow-root",children:g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:rr("inline-block min-w-full align-middle",a?"":"sm:px-6 lg:px-8"),children:g.jsx("div",{className:rr(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:g.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[g.jsx("thead",{className:rr(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:g.jsx("tr",{children:s.map((Y,J)=>{const ae=FS(J,s.length),se=!!D&&D.key===Y.key,K=se?D.direction:void 0,X=Y.sortable&&!Y.srOnlyHeader?se?K==="asc"?"ascending":"descending":"none":void 0,ee=()=>{if(!(!Y.sortable||Y.srOnlyHeader))return O(se?K==="asc"?{key:Y.key,direction:"desc"}:null:{key:Y.key,direction:"asc"})};return g.jsx("th",{scope:"col","aria-sort":X,className:rr(B,ae,"text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",BS(Y.align),Y.widthClassName,Y.headerClassName),children:Y.srOnlyHeader?g.jsx("span",{className:"sr-only",children:Y.header}):Y.sortable?g.jsxs("button",{type:"button",onClick:ee,className:rr("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(Y.align)),children:[g.jsx("span",{children:Y.header}),g.jsx("span",{className:rr("flex-none rounded-sm text-gray-400 dark:text-gray-500",se?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:g.jsx(rO,{"aria-hidden":"true",className:rr("size-5 transition-transform",se&&K==="asc"&&"rotate-180")})})]}):Y.header},Y.key)})})}),g.jsx("tbody",{className:rr("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?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:rr($,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):W.length===0?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:rr($,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:y})}):W.map((Y,J)=>{const ae=t?t(Y,J):String(J);return g.jsx("tr",{className:rr(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?.(Y,J)),onClick:()=>_?.(Y),onContextMenu:S?se=>{se.preventDefault(),S(Y,se)}:void 0,children:s.map((se,K)=>{const X=FS(K,s.length),ee=se.cell?.(Y,J)??se.accessor?.(Y)??Y?.[se.key];return g.jsx("td",{className:rr($,X,"text-sm whitespace-nowrap",BS(se.align),se.className,se.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:ee},se.key)})},ae)})})]})})})})})})]})}function OA({children:s,content:e}){const t=E.useRef(null),i=E.useRef(null),[n,r]=E.useState(!1),[a,u]=E.useState(null),c=E.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)},y=()=>{f()},v=()=>{d(),r(!1)},b=()=>{const S=t.current,L=i.current;if(!S||!L)return;const I=8,R=8,$=S.getBoundingClientRect(),B=L.getBoundingClientRect();let F=$.bottom+I;if(F+B.height>window.innerHeight-R){const D=$.top-B.height-I;D>=R?F=D:F=Math.max(R,window.innerHeight-B.height-R)}let G=$.left;G+B.width>window.innerWidth-R&&(G=window.innerWidth-B.width-R),G=Math.max(R,G),u({left:G,top:F})};E.useLayoutEffect(()=>{if(!n)return;const S=requestAnimationFrame(()=>b());return()=>cancelAnimationFrame(S)},[n]),E.useEffect(()=>{if(!n)return;const S=()=>requestAnimationFrame(()=>b());return window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),()=>{window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0)}},[n]),E.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n,{close:v}):e;return g.jsxs(g.Fragment,{children:[g.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:p,onMouseLeave:y,children:s}),n&&kc.createPortal(g.jsx("div",{ref:i,className:"fixed z-50",style:{left:a?.left??-9999,top:a?.top??-9999,visibility:a?"visible":"hidden"},onMouseEnter:p,onMouseLeave:y,children:g.jsx(ja,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:_()})}),document.body)]})}const np=!0,fO=!1;function rp(s,e){if(!s)return;const t=e?.muted??np;s.muted=t,s.defaultMuted=t,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","")}function ib({job:s,getFileName:e,durationSeconds:t,onDuration:i,animated:n=!1,animatedMode:r="frames",animatedTrigger:a="always",autoTickMs:u=15e3,thumbStepSec:c,thumbSpread:d,thumbSamples:f,clipSeconds:p=1,variant:y="thumb",className:v,showPopover:b=!0,blur:_=!1,inlineVideo:S=!1,inlineNonce:L=0,inlineControls:I=!1,inlineLoop:R=!0,assetNonce:$=0,muted:B=np,popoverMuted:F=np,noGenerateTeaser:M}){const G=e(s.output||""),D=_?"blur-md":"",O={muted:B,playsInline:!0,preload:"metadata"},[W,Y]=E.useState(!0),[J,ae]=E.useState(!0),[se,K]=E.useState(!1),[X,ee]=E.useState(!1),[le,pe]=E.useState(!0),P=E.useRef(null),[Q,ue]=E.useState(!1),[he,re]=E.useState(!1),[Pe,Ee]=E.useState(0),[Ge,Ve]=E.useState(!1),lt=S===!0||S==="always"?"always":S==="hover"?"hover":"never",_t=rt=>rt.startsWith("HOT ")?rt.slice(4):rt,mt=E.useMemo(()=>{const rt=e(s.output||"");if(!rt)return"";const Dt=rt.replace(/\.[^.]+$/,"");return _t(Dt).trim()},[s.output,e]),Ze=E.useMemo(()=>G?`/api/record/video?file=${encodeURIComponent(G)}`:"",[G]),bt=typeof t=="number"&&Number.isFinite(t)&&t>0,gt=y==="fill"?"w-full h-full":"w-20 h-16",at=E.useRef(null),wt=E.useRef(null),Et=E.useRef(null),Ot=rt=>{if(rt){try{rt.pause()}catch{}try{rt.removeAttribute("src"),rt.src="",rt.load()}catch{}}};E.useEffect(()=>{ee(!1),pe(!0)},[mt,$,M]),E.useEffect(()=>{const rt=Dt=>{const ii=String(Dt?.detail?.file??"");!ii||ii!==G||(Ot(at.current),Ot(wt.current),Ot(Et.current))};return window.addEventListener("player:release",rt),window.addEventListener("player:close",rt),()=>{window.removeEventListener("player:release",rt),window.removeEventListener("player:close",rt)}},[G]),E.useEffect(()=>{const rt=P.current;if(!rt)return;const Dt=new IntersectionObserver(ii=>{const ci=!!ii[0]?.isIntersecting;ue(ci),ci&&re(!0)},{threshold:.01,rootMargin:"350px 0px"});return Dt.observe(rt),()=>Dt.disconnect()},[]),E.useEffect(()=>{if(!n||r!=="frames"||!Q||document.hidden)return;const rt=window.setInterval(()=>Ee(Dt=>Dt+1),u);return()=>window.clearInterval(rt)},[n,r,Q,u]);const ot=E.useMemo(()=>{if(!n||r!=="frames"||!bt)return null;const rt=t,Dt=Math.max(.25,c??3);if(d){const mi=Math.max(4,Math.min(f??16,Math.floor(rt))),Ht=Pe%mi,Oi=Math.max(.1,rt-Dt),Ki=Math.min(.25,Oi*.02),Lt=Ht/mi*Oi+Ki;return Math.min(rt-.05,Math.max(.05,Lt))}const ii=Math.max(rt-.1,Dt),ci=Pe*Dt%ii;return Math.min(rt-.05,Math.max(.05,ci))},[n,r,bt,t,Pe,c,d,f]),ht=$??0,ve=E.useMemo(()=>mt?ot==null?`/api/record/preview?id=${encodeURIComponent(mt)}&v=${ht}`:`/api/record/preview?id=${encodeURIComponent(mt)}&t=${ot}&v=${ht}-${Pe}`:"",[mt,ot,Pe,ht]),dt=E.useMemo(()=>{if(!mt)return"";const rt=M?"&noGenerate=1":"";return`/api/generated/teaser?id=${encodeURIComponent(mt)}${rt}&v=${ht}`},[mt,ht,M]),qe=rt=>{if(K(!0),!i)return;const Dt=rt.currentTarget.duration;Number.isFinite(Dt)&&Dt>0&&i(s,Dt)};if(E.useEffect(()=>{Y(!0),ae(!0)},[mt,$]),!Ze)return g.jsx("div",{className:[gt,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});const st=lt!=="never"&&Q&&J&&(lt==="always"||lt==="hover"&&Ge),ft=n&&Q&&!document.hidden&&J&&!st&&(a==="always"||Ge)&&(r==="teaser"&&le&&!!dt||r==="clips"&&bt),yt=lt==="hover"||n&&(r==="clips"||r==="teaser")&&a==="hover",nt=he||yt&&Ge,jt=E.useMemo(()=>{if(!n)return[];if(r!=="clips")return[];if(!bt)return[];const rt=t,Dt=Math.max(.25,p),ii=Math.max(8,Math.min(f??18,Math.floor(rt))),ci=Math.max(.1,rt-Dt),mi=Math.min(.25,ci*.02),Ht=[];for(let Oi=0;Oijt.map(rt=>rt.toFixed(2)).join(","),[jt]),Yt=E.useRef(0),Ut=E.useRef(0);E.useEffect(()=>{const rt=wt.current;if(!rt)return;if(!(ft&&r==="teaser")){try{rt.pause()}catch{}return}rp(rt,{muted:B});const ii=rt.play?.();ii&&typeof ii.catch=="function"&&ii.catch(()=>{})},[ft,r,dt,B]),E.useEffect(()=>{st&&rp(at.current,{muted:B})},[st,B]),E.useEffect(()=>{const rt=Et.current;if(!rt)return;if(!(ft&&r==="clips")){ft||rt.pause();return}if(!jt.length)return;Yt.current=Yt.current%jt.length,Ut.current=jt[Yt.current];const Dt=()=>{try{rt.currentTime=Ut.current}catch{}const mi=rt.play();mi&&typeof mi.catch=="function"&&mi.catch(()=>{})},ii=()=>Dt(),ci=()=>{if(jt.length&&rt.currentTime-Ut.current>=p){Yt.current=(Yt.current+1)%jt.length,Ut.current=jt[Yt.current];try{rt.currentTime=Ut.current+.01}catch{}}};return rt.addEventListener("loadedmetadata",ii),rt.addEventListener("timeupdate",ci),rt.readyState>=1&&Dt(),()=>{rt.removeEventListener("loadedmetadata",ii),rt.removeEventListener("timeupdate",ci),rt.pause()}},[ft,r,qt,p,jt]);const Ni=g.jsxs("div",{ref:P,className:["rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",gt,v??""].join(" "),onMouseEnter:yt?()=>Ve(!0):void 0,onMouseLeave:yt?()=>Ve(!1):void 0,onFocus:yt?()=>Ve(!0):void 0,onBlur:yt?()=>Ve(!1):void 0,children:[nt&&ve&&W?g.jsx("img",{src:ve,loading:"lazy",decoding:"async",alt:G,className:["absolute inset-0 w-full h-full object-cover",D].filter(Boolean).join(" "),onError:()=>Y(!1)}):g.jsx("div",{className:"absolute inset-0 bg-black/10 dark:bg-white/10"}),st?E.createElement("video",{...O,ref:at,key:`inline-${mt}-${L}`,src:Ze,className:["absolute inset-0 w-full h-full object-cover",D,I?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),autoPlay:!0,muted:B,controls:I,loop:R,poster:nt&&ve||void 0,onLoadedMetadata:qe,onError:()=>ae(!1)}):null,!st&&ft&&r==="teaser"?g.jsx("video",{ref:wt,src:dt,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",D,X?"opacity-100":"opacity-0","transition-opacity duration-150"].filter(Boolean).join(" "),muted:B,playsInline:!0,autoPlay:!0,loop:!0,preload:"metadata",poster:nt&&ve||void 0,onLoadedData:()=>ee(!0),onPlaying:()=>ee(!0),onError:()=>{pe(!1),ee(!1)}},`teaser-mp4-${mt}`):null,!st&&ft&&r==="clips"?g.jsx("video",{ref:Et,src:Ze,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",D].filter(Boolean).join(" "),muted:B,playsInline:!0,preload:"metadata",poster:nt&&ve||void 0,onError:()=>ae(!1)},`clips-${mt}-${qt}`):null,Q&&i&&!bt&&!se&&!st&&g.jsx("video",{src:Ze,preload:"metadata",muted:B,playsInline:!0,className:"hidden",onLoadedMetadata:qe})]});return b?g.jsx(OA,{content:rt=>rt&&g.jsx("div",{className:"w-[420px]",children:g.jsx("div",{className:"aspect-video",children:g.jsx("video",{src:Ze,className:["w-full h-full bg-black",D].filter(Boolean).join(" "),muted:F,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:Dt=>Dt.stopPropagation(),onMouseDown:Dt=>Dt.stopPropagation()})})}),children:Ni}):Ni}function Sy(...s){return s.filter(Boolean).join(" ")}const mO={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 pO({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const a=mO[i];return g.jsx("span",{className:Sy("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,y=!u.label&&!!u.icon;return g.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:Sy("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",y?"px-2 py-2":a.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[y&&u.srLabel?g.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?g.jsx("span",{className:Sy("shrink-0",y?"":"-ml-0.5",d?"text-indigo-600 dark:text-indigo-200":"text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?g.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function gO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75"}))}const yO=E.forwardRef(gO);function vO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const jS=E.forwardRef(vO);function xO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 Ey=E.forwardRef(xO);function bO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 TO=E.forwardRef(bO);function _O({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 SO=E.forwardRef(_O);function EO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 Zv=E.forwardRef(EO);function wO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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=E.forwardRef(wO);function AO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 CO=E.forwardRef(AO);function kO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 DO=E.forwardRef(kO);function LO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 RO=E.forwardRef(LO);function IO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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"}),E.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const Jv=E.forwardRef(IO);function NO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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"}),E.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 HS=E.forwardRef(NO);function OO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 ap=E.forwardRef(OO);function MO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 PO=E.forwardRef(MO);function BO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 FO=E.forwardRef(BO);function UO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 jO=E.forwardRef(UO);function $O({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 HO=E.forwardRef($O);function GO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 GS=E.forwardRef(GO);function VO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}),E.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 zO=E.forwardRef(VO);function qO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 KO=E.forwardRef(qO);function WO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 YO=E.forwardRef(WO);function XO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 VS=E.forwardRef(XO);function QO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 ZO=E.forwardRef(QO);function JO({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 ex=E.forwardRef(JO);function eM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 tM=E.forwardRef(eM);function iM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 tx=E.forwardRef(iM);function sM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 nM=E.forwardRef(sM);function rM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 aM=E.forwardRef(rM);function oM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const sb=E.forwardRef(oM);function pm(...s){return s.filter(Boolean).join(" ")}const lM=E.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:a,className:u,leftAction:c={label:g.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[g.jsx(Zv,{className:"h-6 w-6","aria-hidden":"true"}),g.jsx("span",{children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:g.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[g.jsx(tx,{className:"h-6 w-6","aria-hidden":"true"}),g.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=180,thresholdRatio:p=.1,ignoreFromBottomPx:y=72,ignoreSelector:v="[data-swipe-ignore]",snapMs:b=180,commitMs:_=180,tapIgnoreSelector:S="button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]",onDoubleTap:L,hotTargetSelector:I="[data-hot-target]",doubleTapMs:R=360,doubleTapMaxMovePx:$=48},B){const F=E.useRef(null),M=E.useRef(!1),G=E.useRef(0),D=E.useRef(null),O=E.useRef(0),W=E.useRef(null),Y=E.useRef(null),J=E.useRef(null),ae=E.useRef(null),se=E.useRef({id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1}),[K,X]=E.useState(0),[ee,le]=E.useState(null),[pe,P]=E.useState(0),Q=E.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),G.current=0,F.current&&(F.current.style.touchAction="pan-y"),P(b),X(0),le(null),window.setTimeout(()=>P(0),b)},[b]),ue=E.useCallback(async(Ee,Ge)=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),F.current&&(F.current.style.touchAction="pan-y");const lt=F.current?.offsetWidth||360;P(_),le(Ee==="right"?"right":"left");const _t=Ee==="right"?lt+40:-(lt+40);G.current=_t,X(_t);let mt=!0;if(Ge)try{mt=Ee==="right"?await a():await r()}catch{mt=!1}return mt===!1?(P(b),le(null),X(0),window.setTimeout(()=>P(0),b),!1):!0},[_,r,a,b]),he=E.useCallback(()=>{Y.current!=null&&(window.clearTimeout(Y.current),Y.current=null)},[]),re=E.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),G.current=0,P(0),X(0),le(null);try{const Ee=F.current;Ee&&(Ee.style.touchAction="pan-y")}catch{}},[]),Pe=E.useCallback((Ee,Ge)=>{const Ve=W.current,lt=F.current;if(!Ve||!lt)return;const _t=ae.current;if(!_t)return;const mt=Ve.getBoundingClientRect();let Ze=mt.width/2,bt=mt.height/2;typeof Ee=="number"&&typeof Ge=="number"&&(Ze=Ee-mt.left,bt=Ge-mt.top,Ze=Math.max(0,Math.min(mt.width,Ze)),bt=Math.max(0,Math.min(mt.height,bt)));const gt=I?lt.querySelector(I):null;let at=Ze,wt=bt;if(gt){const nt=gt.getBoundingClientRect();at=nt.left-mt.left+nt.width/2,wt=nt.top-mt.top+nt.height/2}const Et=at-Ze,Ot=wt-bt,ot=document.createElement("div");ot.textContent="🔥",ot.style.position="absolute",ot.style.left=`${Ze}px`,ot.style.top=`${bt}px`,ot.style.transform="translate(-50%, -50%)",ot.style.fontSize="30px",ot.style.filter="drop-shadow(0 10px 16px rgba(0,0,0,0.22))",ot.style.pointerEvents="none",ot.style.willChange="transform, opacity",_t.appendChild(ot);const ht=200,ve=500,dt=400,qe=ht+ve+dt,st=ht/qe,ft=(ht+ve)/qe,yt=ot.animate([{transform:"translate(-50%, -50%) scale(0.15)",opacity:0,offset:0},{transform:"translate(-50%, -50%) scale(1.25)",opacity:1,offset:st*.55},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:st},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:ft},{transform:`translate(calc(-50% + ${Et}px), calc(-50% + ${Ot}px)) scale(0.85)`,opacity:.95,offset:ft+(1-ft)*.75},{transform:`translate(calc(-50% + ${Et}px), calc(-50% + ${Ot}px)) scale(0.55)`,opacity:0,offset:1}],{duration:qe,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)",fill:"forwards"});gt&&window.setTimeout(()=>{try{gt.animate([{transform:"translateZ(0) scale(1)",filter:"brightness(1)"},{transform:"translateZ(0) scale(1.10)",filter:"brightness(1.25)",offset:.35},{transform:"translateZ(0) scale(1)",filter:"brightness(1)"}],{duration:260,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)"})}catch{}},ht+ve+Math.round(dt*.75)),yt.onfinish=()=>ot.remove()},[I]);return E.useEffect(()=>()=>{Y.current!=null&&window.clearTimeout(Y.current)},[]),E.useImperativeHandle(B,()=>({swipeLeft:Ee=>ue("left",Ee?.runAction??!0),swipeRight:Ee=>ue("right",Ee?.runAction??!0),reset:()=>Q()}),[ue,Q]),g.jsxs("div",{ref:W,className:pm("relative isolate overflow-hidden rounded-lg",u),children:[g.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[g.jsx("div",{className:pm("absolute inset-0 transition-opacity duration-200 ease-out",K===0?"opacity-0":"opacity-100",K>0?c.className:d.className)}),g.jsx("div",{className:pm("absolute inset-0 flex items-center transition-all duration-200 ease-out"),style:{transform:`translateX(${Math.max(-24,Math.min(24,K/8))}px)`,opacity:K===0?0:1,justifyContent:K>0?"flex-start":"flex-end",paddingLeft:K>0?16:0,paddingRight:K>0?0:16},children:K>0?c.label:d.label})]}),g.jsx("div",{ref:ae,className:"pointer-events-none absolute inset-0 z-50"}),g.jsx("div",{ref:F,className:"relative",style:{transform:K!==0?`translate3d(${K}px,0,0)`:void 0,transition:pe?`transform ${pe}ms ease`:void 0,touchAction:"pan-y",willChange:K!==0?"transform":void 0},onPointerDown:Ee=>{if(!t||i)return;const Ge=Ee.target,Ve=!!(S&&Ge?.closest?.(S));if(v&&Ge?.closest?.(v))return;const lt=Ee.currentTarget,mt=Array.from(lt.querySelectorAll("video")).find(wt=>wt.controls);if(mt){const wt=mt.getBoundingClientRect();if(Ee.clientX>=wt.left&&Ee.clientX<=wt.right&&Ee.clientY>=wt.top&&Ee.clientY<=wt.bottom){if(wt.bottom-Ee.clientY<=72)return;const ht=64,ve=Ee.clientX-wt.left,dt=wt.right-Ee.clientX;if(!(ve<=ht||dt<=ht))return}}const bt=Ee.currentTarget.getBoundingClientRect().bottom-Ee.clientY;if(y&&bt<=y)return;se.current={id:Ee.pointerId,x:Ee.clientX,y:Ee.clientY,dragging:!1,captured:!1,tapIgnored:Ve};const at=F.current?.offsetWidth||360;O.current=Math.min(f,at*p),G.current=0},onPointerMove:Ee=>{if(!t||i||se.current.id!==Ee.pointerId)return;const Ge=Ee.clientX-se.current.x,Ve=Ee.clientY-se.current.y;if(!se.current.dragging){if(Math.abs(Ve)>Math.abs(Ge)&&Math.abs(Ve)>8){se.current.id=null;return}if(Math.abs(Ge)<12)return;se.current.dragging=!0,Ee.currentTarget.style.touchAction="none",P(0);try{Ee.currentTarget.setPointerCapture(Ee.pointerId),se.current.captured=!0}catch{se.current.captured=!1}}G.current=Ge,D.current==null&&(D.current=requestAnimationFrame(()=>{D.current=null,X(G.current)}));const lt=O.current,_t=Ge>lt?"right":Ge<-lt?"left":null;le(mt=>mt===_t?mt:_t)},onPointerUp:Ee=>{if(!t||i||se.current.id!==Ee.pointerId)return;const Ge=O.current||Math.min(f,(F.current?.offsetWidth||360)*p),Ve=se.current.dragging,lt=se.current.captured,_t=se.current.tapIgnored;if(se.current.id=null,se.current.dragging=!1,se.current.captured=!1,lt)try{Ee.currentTarget.releasePointerCapture(Ee.pointerId)}catch{}if(Ee.currentTarget.style.touchAction="pan-y",!Ve){if(_t){P(0),X(0),le(null);return}const Ze=Date.now(),bt=J.current,gt=bt&&Math.hypot(Ee.clientX-bt.x,Ee.clientY-bt.y)<=$;if(!!L&&bt&&Ze-bt.t<=R&>){if(J.current=null,he(),M.current)return;M.current=!0,requestAnimationFrame(()=>{try{Pe(Ee.clientX,Ee.clientY)}catch{}}),(async()=>{try{await L?.()}catch{}finally{M.current=!1}})();return}re(),J.current={t:Ze,x:Ee.clientX,y:Ee.clientY},he(),Y.current=window.setTimeout(()=>{Y.current=null,J.current=null,n?.()},L?R:0);return}const mt=G.current;D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),mt>Ge?ue("right",!0):mt<-Ge?ue("left",!0):Q(),G.current=0},onPointerCancel:Ee=>{if(!(!t||i)){if(se.current.captured&&se.current.id!=null)try{Ee.currentTarget.releasePointerCapture(se.current.id)}catch{}se.current={id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1},D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),G.current=0;try{Ee.currentTarget.style.touchAction="pan-y"}catch{}Q()}},children:g.jsxs("div",{className:"relative",children:[g.jsx("div",{className:"relative z-10",children:e}),g.jsx("div",{className:pm("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",ee==="right"&&"bg-emerald-500/20 opacity-100",ee==="left"&&"bg-red-500/20 opacity-100",ee===null&&"opacity-0")})]})})]})});function uM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{fillRule:"evenodd",d:"M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z",clipRule:"evenodd"}))}const cM=E.forwardRef(uM);function dM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.createElement("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"}),E.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 Lc=E.forwardRef(dM);function hM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 zS=E.forwardRef(hM);function fM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 mM=E.forwardRef(fM);function pM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 Rc=E.forwardRef(pM);function gM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 yM=E.forwardRef(gM);function vM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 xM=E.forwardRef(vM);function bM({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 TM=E.forwardRef(bM);function _M({title:s,titleId:e,...t},i){return E.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?E.createElement("title",{id:e},s):null,E.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 Ah=E.forwardRef(_M);function aa({tag:s,children:e,title:t,active:i,onClick:n,maxWidthClassName:r="max-w-[11rem]",className:a,stopPropagation:u=!0}){const c=s??(typeof e=="string"||typeof e=="number"?String(e):""),d=xi("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"),y=xi(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":"",a),v=_=>_.stopPropagation(),b=u?{onPointerDown:v,onMouseDown:v}:{};return n?g.jsx("button",{type:"button",className:y,title:t??c,"aria-pressed":!!i,...b,onClick:_=>{u&&(_.preventDefault(),_.stopPropagation()),c&&n(c)},children:e??s}):g.jsx("span",{className:y,title:t??c,...b,onClick:u?v:void 0,children:e??s})}function Si(...s){return s.filter(Boolean).join(" ")}const SM=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",EM=s=>s.startsWith("HOT ")?s.slice(4):s,wM=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function AM(s){const t=EM(SM(s||"")).replace(/\.[^.]+$/,""),i=t.match(wM);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function Ua({job:s,variant:e="overlay",collapseToMenu:t=!1,inlineCount:i,busy:n=!1,compact:r=!1,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onToggleFavorite:f,onToggleLike:p,onToggleHot:y,onKeep:v,onDelete:b,onToggleWatch:_,onAddToDownloads:S,order:L,className:I}){const R=e==="overlay"?r?"p-1.5":"p-2":"p-1.5",$=r?"size-4":"size-5",B="h-full w-full",F=e==="table"?`inline-flex items-center justify-center rounded-md ${R} 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 ${R} 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`,M=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"},G=L??["watch","favorite","like","hot","keep","delete","details"],D=Lt=>G.includes(Lt),O=String(s?.sourceUrl??"").trim(),W=AM(s.output||""),Y=W?`Mehr zu ${W} anzeigen`:"Mehr anzeigen",J=D("favorite"),ae=D("like"),se=D("hot"),K=D("watch"),X=D("keep"),ee=D("delete"),le=D("details")&&!!W,pe=D("add"),[P,Q]=E.useState("idle"),ue=E.useRef(null);E.useEffect(()=>()=>{ue.current&&window.clearTimeout(ue.current)},[]);const he=()=>{Q("ok"),ue.current&&window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>Q("idle"),800)},re=async()=>{if(n||P==="busy"||!S&&!!!O)return!1;Q("busy");try{let z=!0;return S?z=await S(s)!==!1:O?(window.dispatchEvent(new CustomEvent("downloads:add-url",{detail:{url:O}})),z=!0):z=!1,z?he():Q("idle"),z}catch{return Q("idle"),!1}},[Pe,Ee]=E.useState(0),[Ge,Ve]=E.useState(4),lt=Lt=>z=>{z.preventDefault(),z.stopPropagation(),!(n||!Lt)&&Promise.resolve(Lt(s)).catch(()=>{})},_t=le?g.jsxs("button",{type:"button",className:Si(F),title:Y,"aria-label":Y,disabled:n,onClick:Lt=>{Lt.preventDefault(),Lt.stopPropagation(),!n&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:W}}))},children:[g.jsx("span",{className:Si("inline-flex items-center justify-center",$),children:g.jsx(GS,{className:Si(B,M.off)})}),g.jsx("span",{className:"sr-only",children:Y})]}):null,mt=pe?g.jsxs("button",{type:"button",className:Si(F),title:O?"URL zu Downloads hinzufügen":"Keine URL vorhanden","aria-label":"Zu Downloads hinzufügen",disabled:n||P==="busy"||!S&&!O,onClick:async Lt=>{Lt.preventDefault(),Lt.stopPropagation(),await re()},children:[g.jsx("span",{className:Si("inline-flex items-center justify-center",$),children:P==="ok"?g.jsx(cM,{className:Si(B,"text-emerald-600 dark:text-emerald-300")}):g.jsx(jS,{className:Si(B,M.off)})}),g.jsx("span",{className:"sr-only",children:"Zu Downloads"})]}):null,Ze=J?g.jsx("button",{type:"button",className:F,title:u?"Favorit entfernen":"Als Favorit markieren","aria-label":u?"Favorit entfernen":"Als Favorit markieren","aria-pressed":u,disabled:n||!f,onClick:lt(f),children:g.jsxs("span",{className:Si("relative inline-block",$),children:[g.jsx(ex,{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",B,M.off)}),g.jsx(Ah,{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",B,M.favOn)})]})}):null,bt=ae?g.jsx("button",{type:"button",className:F,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||!p,onClick:lt(p),children:g.jsxs("span",{className:Si("relative inline-block",$),children:[g.jsx(ap,{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",B,M.off)}),g.jsx(Rc,{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",B,M.likeOn)})]})}):null,gt=se?g.jsx("button",{type:"button","data-hot-target":!0,className:F,title:a?"HOT entfernen":"Als HOT markieren","aria-label":a?"HOT entfernen":"Als HOT markieren","aria-pressed":a,disabled:n||!y,onClick:lt(y),children:g.jsxs("span",{className:Si("relative inline-block",$),children:[g.jsx(HS,{className:Si("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",B,M.off)}),g.jsx(zS,{className:Si("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",B,M.hotOn)})]})}):null,at=K?g.jsx("button",{type:"button",className:F,title:d?"Watched entfernen":"Als Watched markieren","aria-label":d?"Watched entfernen":"Als Watched markieren","aria-pressed":d,disabled:n||!_,onClick:lt(_),children:g.jsxs("span",{className:Si("relative inline-block",$),children:[g.jsx(Jv,{className:Si("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",B,M.off)}),g.jsx(Lc,{className:Si("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",B,M.watchOn)})]})}):null,wt=X?g.jsx("button",{type:"button",className:F,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:n||!v,onClick:lt(v),children:g.jsx("span",{className:Si("inline-flex items-center justify-center",$),children:g.jsx(Zv,{className:Si(B,M.keep)})})}):null,Et=ee?g.jsx("button",{type:"button",className:F,title:"Löschen","aria-label":"Löschen",disabled:n||!b,onClick:lt(b),children:g.jsx("span",{className:Si("inline-flex items-center justify-center",$),children:g.jsx(tx,{className:Si(B,M.del)})})}):null,Ot={details:_t,add:mt,favorite:Ze,like:bt,watch:at,hot:gt,keep:wt,delete:Et},ot=t&&e==="overlay",ht=G.filter(Lt=>!!Ot[Lt]),ve=ot&&typeof i!="number",st=(r?16:20)+(e==="overlay"?r?6:8:6)*2,ft=r?2:3,yt=E.useMemo(()=>{if(!ve)return i??ft;const Lt=Pe||0;if(Lt<=0)return Math.min(ht.length,ft);for(let z=ht.length;z>=0;z--)if(z*st+st+(z>0?z*Ge:0)<=Lt)return z;return 0},[ve,i,ft,Pe,ht.length,st,Ge]),nt=ot?ht.slice(0,yt):ht,jt=ot?ht.slice(yt):[],[qt,Yt]=E.useState(!1),Ut=E.useRef(null);E.useLayoutEffect(()=>{const Lt=Ut.current;if(!Lt||typeof window>"u")return;const z=()=>{const te=Ut.current;if(!te)return;const xe=Math.floor(te.getBoundingClientRect().width||0);xe>0&&Ee(xe);const Me=window.getComputedStyle(te),ut=Me.columnGap||Me.gap||"0",Pt=parseFloat(ut);Number.isFinite(Pt)&&Pt>=0&&Ve(Pt)};z();const V=new ResizeObserver(()=>z());return V.observe(Lt),window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),V.disconnect()}},[]);const Ni=E.useRef(null),rt=E.useRef(null),Dt=208,ii=4,ci=8,[mi,Ht]=E.useState(null);E.useEffect(()=>{if(!qt)return;const Lt=V=>{V.key==="Escape"&&Yt(!1)},z=V=>{const te=Ut.current,xe=rt.current,Me=V.target;te&&te.contains(Me)||xe&&xe.contains(Me)||Yt(!1)};return window.addEventListener("keydown",Lt),window.addEventListener("mousedown",z),()=>{window.removeEventListener("keydown",Lt),window.removeEventListener("mousedown",z)}},[qt]),E.useLayoutEffect(()=>{if(!qt){Ht(null);return}const Lt=()=>{const z=Ni.current;if(!z)return;const V=z.getBoundingClientRect(),te=window.innerWidth,xe=window.innerHeight;let Me=V.right-Dt;Me=Math.max(ci,Math.min(Me,te-Dt-ci));let ut=V.bottom+ii;ut=Math.max(ci,Math.min(ut,xe-ci));const Pt=Math.max(120,xe-ut-ci);Ht({top:ut,left:Me,maxH:Pt})};return Lt(),window.addEventListener("resize",Lt),window.addEventListener("scroll",Lt,!0),()=>{window.removeEventListener("resize",Lt),window.removeEventListener("scroll",Lt,!0)}},[qt]);const Oi=()=>{W&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:W}}))},Ki=Lt=>Lt==="details"?g.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:z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),Oi()},children:[g.jsx(GS,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:"Details"})]},"details"):Lt==="add"?g.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||!S&&!O,onClick:async z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await re()},children:[g.jsx(jS,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:"Zu Downloads"})]},"add"):Lt==="favorite"?g.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||!f,onClick:async z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await f?.(s)},children:[u?g.jsx(Ah,{className:Si("size-4",M.favOn)}):g.jsx(ex,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:u?"Favorit entfernen":"Als Favorit markieren"})]},"favorite"):Lt==="like"?g.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||!p,onClick:async z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await p?.(s)},children:[c?g.jsx(Rc,{className:Si("size-4",M.favOn)}):g.jsx(ap,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:c?"Gefällt mir entfernen":"Gefällt mir"})]},"like"):Lt==="watch"?g.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:async z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await _?.(s)},children:[d?g.jsx(Lc,{className:Si("size-4",M.favOn)}):g.jsx(Jv,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:d?"Watched entfernen":"Watched"})]},"watch"):Lt==="hot"?g.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||!y,onClick:async z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await y?.(s)},children:[a?g.jsx(zS,{className:Si("size-4",M.favOn)}):g.jsx(HS,{className:Si("size-4",M.off)}),g.jsx("span",{className:"truncate",children:a?"HOT entfernen":"Als HOT markieren"})]},"hot"):Lt==="keep"?g.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 z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await v?.(s)},children:[g.jsx(Zv,{className:Si("size-4",M.keep)}),g.jsx("span",{className:"truncate",children:"Behalten"})]},"keep"):Lt==="delete"?g.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 z=>{z.preventDefault(),z.stopPropagation(),Yt(!1),await b?.(s)},children:[g.jsx(tx,{className:Si("size-4",M.del)}),g.jsx("span",{className:"truncate",children:"Löschen"})]},"delete"):null;return g.jsxs("div",{ref:Ut,className:Si("relative flex items-center flex-nowrap",I??"gap-2"),children:[nt.map(Lt=>{const z=Ot[Lt];return z?g.jsx(E.Fragment,{children:z},Lt):null}),ot&&jt.length>0?g.jsxs("div",{className:"relative",children:[g.jsx("button",{ref:Ni,type:"button",className:F,"aria-label":"Mehr",title:"Mehr","aria-haspopup":"menu","aria-expanded":qt,disabled:n,onClick:Lt=>{Lt.preventDefault(),Lt.stopPropagation(),!n&&Yt(z=>!z)},children:g.jsx("span",{className:Si("inline-flex items-center justify-center",$),children:g.jsx(DO,{className:Si(B,M.off)})})}),qt&&mi&&typeof document<"u"?kc.createPortal(g.jsx("div",{ref:rt,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:mi.top,left:mi.left,width:Dt,maxHeight:mi.maxH},onClick:Lt=>Lt.stopPropagation(),children:jt.map(Ki)}),document.body):null]}):null]})}const MA=/^HOT[ \u00A0]+/i,PA=s=>String(s||"").replaceAll(" "," "),uc=s=>MA.test(PA(s)),_o=s=>PA(s).replace(MA,"");function CM(...s){return s.filter(Boolean).join(" ")}const kM=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n};function DM({rows:s,isSmall:e,teaserPlayback:t,teaserAudio:i,hoverTeaserKey:n,blurPreviews:r,teaserKey:a,inlinePlay:u,setInlinePlay:c,deletingKeys:d,keepingKeys:f,removingKeys:p,swipeRefs:y,assetNonce:v,keyFor:b,baseName:_,modelNameFromOutput:S,runtimeOf:L,sizeBytesOf:I,formatBytes:R,lower:$,onHoverPreviewKeyChange:B,onOpenPlayer:F,openPlayer:M,startInline:G,tryAutoplayInline:D,registerTeaserHost:O,deleteVideo:W,keepVideo:Y,releasePlayingFile:J,modelsByKey:ae,activeTagSet:se,onToggleTagFilter:K,onToggleHot:X,onToggleFavorite:ee,onToggleLike:le,onToggleWatch:pe}){const[P,Q]=E.useState(null),ue=E.useRef(null);return E.useEffect(()=>{if(!P)return;const he=Pe=>{Pe.key==="Escape"&&Q(null)},re=Pe=>{const Ee=ue.current;Ee&&(Ee.contains(Pe.target)||Q(null))};return document.addEventListener("keydown",he),document.addEventListener("pointerdown",re),()=>{document.removeEventListener("keydown",he),document.removeEventListener("pointerdown",re)}},[P]),E.useEffect(()=>{if(!P)return;s.some(re=>b(re)===P)||Q(null)},[s,b,P]),g.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:s.map(he=>{const re=b(he),Pe=u?.key===re,Ge=!(!!i&&(Pe||n===re)),Ve=Pe?u?.nonce??0:0,lt=d.has(re)||f.has(re)||p.has(re),_t=S(he.output),mt=_(he.output||""),Ze=uc(mt),bt=ae[$(_t)],gt=!!bt?.favorite,at=bt?.liked===!0,wt=!!bt?.watching,Et=kM(bt?.tags),Ot=Et.slice(0,6),ot=Et.length-Ot.length,ht=Et.join(", "),ve=he.status==="failed"?"bg-red-500/35":he.status==="finished"?"bg-emerald-500/35":he.status==="stopped"?"bg-amber-500/35":"bg-black/40",dt=L(he),qe=R(I(he)),st=`inline-prev-${encodeURIComponent(re)}`,ft=e?"":"transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-md dark:hover:shadow-none",yt=g.jsx("div",{role:"button",tabIndex:0,className:["group","content-visibility-auto","[contain-intrinsic-size:180px_120px]",ft,"rounded-xl","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",lt&&"pointer-events-none",d.has(re)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30 animate-pulse",f.has(re)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30 animate-pulse",p.has(re)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),onClick:e?void 0:()=>M(he),onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&F(he)},children:g.jsxs(ja,{noBodyPadding:!0,className:"overflow-hidden",children:[g.jsxs("div",{id:st,ref:O(re),className:"relative aspect-video bg-black/5 dark:bg-white/5",onMouseEnter:e?void 0:()=>B?.(re),onMouseLeave:e?void 0:()=>B?.(null),onClick:nt=>{nt.preventDefault(),nt.stopPropagation(),!e&&G(re)},children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(ib,{job:he,getFileName:_,className:"w-full h-full",showPopover:!1,blur:e||Pe?!1:r,animated:t==="all"?!0:t==="hover"?a===re:!1,animatedMode:"teaser",animatedTrigger:"always",inlineVideo:Pe?"always":!1,inlineNonce:Ve,inlineControls:Pe,inlineLoop:!1,muted:Ge,popoverMuted:Ge,assetNonce:v??0})}),g.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",Pe?"opacity-0":"opacity-100"].join(" ")}),g.jsx("div",{className:["pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white","transition-opacity duration-150",Pe?"opacity-0":"opacity-100"].join(" "),children:g.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] opacity-90",children:[g.jsx("span",{className:CM("rounded px-1.5 py-0.5 font-semibold",ve),children:he.status}),g.jsxs("div",{className:"flex items-center gap-1.5",children:[g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:dt}),g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:qe})]})]})}),!e&&u?.key===re&&g.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:nt=>{nt.preventDefault(),nt.stopPropagation(),c(jt=>({key:re,nonce:jt?.key===re?jt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}),g.jsx("div",{className:"absolute right-2 top-2 flex items-center gap-2",onClick:nt=>nt.stopPropagation(),onMouseDown:nt=>nt.stopPropagation(),children:g.jsx(Ua,{job:he,variant:"overlay",busy:lt,isHot:Ze,isFavorite:gt,isLiked:at,isWatching:wt,onToggleWatch:pe,onToggleFavorite:ee,onToggleLike:le,onToggleHot:X?async nt=>{const jt=_(nt.output||"");jt&&(await J(jt,{close:!0}),await new Promise(qt=>setTimeout(qt,150))),await X(nt)}:void 0,onKeep:Y,onDelete:W,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"flex items-center gap-2"})})]}),g.jsxs("div",{className:["px-4 py-3 rounded-b-lg border-t border-gray-200/60 dark:border-white/10",e?"bg-white/90 dark:bg-gray-950/80":"bg-white/60 backdrop-blur dark:bg-white/5"].join(" "),children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:_t}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[wt?g.jsx(Lc,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,at?g.jsx(Rc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,gt?g.jsx(Ah,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsx("span",{className:"truncate",children:_o(mt)||"—"}),Ze?g.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]}),g.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:nt=>nt.stopPropagation(),onMouseDown:nt=>nt.stopPropagation(),children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:Ot.length>0?Ot.map(nt=>g.jsx(aa,{tag:nt,active:se.has($(nt)),onClick:K},nt)):g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),ot>0?g.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:ht,"aria-haspopup":"dialog","aria-expanded":P===re,onPointerDown:nt=>nt.stopPropagation(),onClick:nt=>{nt.preventDefault(),nt.stopPropagation(),Q(jt=>jt===re?null:re)},children:["+",ot]}):null,P===re?g.jsxs("div",{ref:ue,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",e?"":"backdrop-blur","dark:border-white/10 dark:bg-gray-950/90 dark:ring-white/10"].join(" "),onClick:nt=>nt.stopPropagation(),onMouseDown:nt=>nt.stopPropagation(),children:[g.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:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),g.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:()=>Q(null),"aria-label":"Schließen",title:"Schließen",children:"✕"})]}),g.jsx("div",{className:"max-h-48 overflow-auto p-2",children:g.jsx("div",{className:"flex flex-wrap gap-1.5",children:Et.map(nt=>g.jsx(aa,{tag:nt,active:se.has($(nt)),onClick:K},nt))})})]}):null]})]})]})});return e?g.jsx(lM,{ref:nt=>{nt?y.current.set(re,nt):y.current.delete(re)},enabled:!0,disabled:lt,ignoreFromBottomPx:110,doubleTapMs:360,doubleTapMaxMovePx:48,onTap:()=>{const nt=`inline-prev-${encodeURIComponent(re)}`;G(re),requestAnimationFrame(()=>{D(nt)||requestAnimationFrame(()=>D(nt))})},onDoubleTap:X?async()=>{if(Ze)return!1;try{const nt=_(he.output||"");return nt&&(u?.key===re||(await J(nt,{close:!0}),await new Promise(qt=>setTimeout(qt,150)))),await X(he),!0}catch{return!1}}:void 0,onSwipeLeft:()=>W(he),onSwipeRight:()=>Y(he),children:yt},re):g.jsx(E.Fragment,{children:yt},re)})})}function LM({rows:s,columns:e,getRowKey:t,sort:i,onSortChange:n,onRowClick:r,rowClassName:a}){return g.jsx(ph,{rows:s,columns:e,getRowKey:t,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,sort:i,onSortChange:n,onRowClick:r,rowClassName:a})}function RM({rows:s,blurPreviews:e,durations:t,teaserPlayback:i,teaserAudio:n,hoverTeaserKey:r,teaserKey:a,handleDuration:u,keyFor:c,baseName:d,modelNameFromOutput:f,runtimeOf:p,sizeBytesOf:y,formatBytes:v,deletingKeys:b,keepingKeys:_,removingKeys:S,deletedKeys:L,registerTeaserHost:I,onHoverPreviewKeyChange:R,onOpenPlayer:$,deleteVideo:B,keepVideo:F,onToggleHot:M,lower:G,modelsByKey:D,activeTagSet:O,onToggleTagFilter:W,onToggleFavorite:Y,onToggleLike:J,onToggleWatch:ae}){const[se,K]=E.useState(null),X=E.useRef(null),ee=i==="hover"||i==="all",le=E.useCallback(P=>Q=>{if(!ee){I(P)(null);return}I(P)(Q)},[I,ee]);E.useEffect(()=>{if(!se)return;const P=ue=>{ue.key==="Escape"&&K(null)},Q=ue=>{const he=X.current;he&&(he.contains(ue.target)||K(null))};return document.addEventListener("keydown",P),document.addEventListener("pointerdown",Q),()=>{document.removeEventListener("keydown",P),document.removeEventListener("pointerdown",Q)}},[se]),E.useEffect(()=>{if(!se)return;s.some(Q=>c(Q)===se)||K(null)},[s,c,se]);const pe=P=>{const Q=String(P??"").trim();if(!Q)return[];const ue=Q.split(/[\n,;|]+/g).map(Pe=>Pe.trim()).filter(Boolean),he=new Set,re=[];for(const Pe of ue){const Ee=Pe.toLowerCase();he.has(Ee)||(he.add(Ee),re.push(Pe))}return re};return g.jsx(g.Fragment,{children:g.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:s.map(P=>{const Q=c(P),he=!(!!n&&r===Q),re=f(P.output),Pe=G(re),Ee=D[Pe],Ge=!!Ee?.favorite,Ve=Ee?.liked===!0,lt=!!Ee?.watching,_t=pe(Ee?.tags),mt=_t.slice(0,6),Ze=_t.length-mt.length,bt=_t.join(", "),gt=d(P.output||""),at=uc(gt),wt=_o(gt),Et=p(P),Ot=v(y(P)),ot=b.has(Q)||_.has(Q)||S.has(Q),ht=L.has(Q);return g.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",ot&&"pointer-events-none opacity-70",b.has(Q)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",S.has(Q)&&"opacity-0 translate-y-2 scale-[0.98]",ht&&"hidden"].filter(Boolean).join(" "),onClick:()=>$(P),onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&$(P)},children:[g.jsxs("div",{className:"group relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",ref:le(Q),onMouseEnter:()=>R?.(Q),onMouseLeave:()=>R?.(null),children:[g.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-t-lg",children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(ib,{job:P,getFileName:ve=>_o(d(ve)),durationSeconds:t[Q]??P?.durationSeconds,onDuration:u,variant:"fill",showPopover:!1,blur:e,animated:i==="all"?!0:i==="hover"?a===Q:!1,animatedMode:"teaser",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,muted:he,popoverMuted:he})}),g.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 + `}),g.jsx("div",{className:` + pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white + `,children:g.jsxs("div",{className:"flex items-end justify-between gap-2",children:[g.jsx("div",{className:"min-w-0",children:g.jsx("div",{children:g.jsx("span",{className:["inline-block rounded px-1.5 py-0.5 text-[11px] font-semibold",P.status==="finished"?"bg-emerald-600/70":P.status==="stopped"?"bg-amber-600/70":P.status==="failed"?"bg-red-600/70":"bg-black/50"].join(" "),children:P.status})})}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:Et}),g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:Ot})]})]})})]}),g.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:ve=>ve.stopPropagation(),children:g.jsx(Ua,{job:P,variant:"overlay",busy:ot,collapseToMenu:!0,isHot:at,isFavorite:Ge,isLiked:Ve,isWatching:lt,onToggleWatch:ae,onToggleFavorite:Y,onToggleLike:J,onToggleHot:M,onKeep:F,onDelete:B,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"w-full justify-end gap-1"})})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:re}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[lt?g.jsx(Lc,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,Ve?g.jsx(Rc,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Ge?g.jsx(Ah,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsx("span",{className:"truncate",children:_o(wt)||"—"}),at?g.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]}),g.jsxs("div",{className:"mt-2 h-6 relative flex items-center gap-1.5",onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:mt.length>0?mt.map(ve=>g.jsx(aa,{tag:ve,active:O.has(G(ve)),onClick:W},ve)):g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),Ze>0?g.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:bt,"aria-haspopup":"dialog","aria-expanded":se===Q,onPointerDown:ve=>ve.stopPropagation(),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),K(dt=>dt===Q?null:Q)},children:["+",Ze]}):null,se===Q?g.jsxs("div",{ref:X,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:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),children:[g.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:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Tags"}),g.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:"✕"})]}),g.jsx("div",{className:"max-h-48 overflow-auto p-2",children:g.jsx("div",{className:"flex flex-wrap gap-1.5",children:_t.map(ve=>g.jsx(aa,{tag:ve,active:O.has(G(ve)),onClick:W},ve))})})]}):null]})]})]},Q)})})})}function qS(s,e,t){return Math.max(e,Math.min(t,s))}function wy(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function IM(s,e,t,i){if(s<=1)return[1];const n=1,r=s,a=wy(n,Math.min(t,r)),u=wy(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(...a),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const p=new Set;return f.filter(y=>{const v=String(y);return p.has(v)?!1:(p.add(v),!0)})}function NM({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const a=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return g.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:xi("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",a,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 BA({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:a=!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))),y=qS(s||1,1,p);if(p<=1)return null;const v=t===0?0:(y-1)*e+1,b=Math.min(y*e,t),_=IM(p,y,r,n),S=L=>i(qS(L,1,p));return g.jsxs("div",{className:xi("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:[g.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[g.jsx("button",{type:"button",onClick:()=>S(y-1),disabled:y<=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}),g.jsx("button",{type:"button",onClick:()=>S(y+1),disabled:y>=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})]}),g.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[g.jsx("div",{children:a?g.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",g.jsx("span",{className:"font-medium",children:v})," to"," ",g.jsx("span",{className:"font-medium",children:b})," of"," ",g.jsx("span",{className:"font-medium",children:t})," results"]}):null}),g.jsx("div",{children:g.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[g.jsxs("button",{type:"button",onClick:()=>S(y-1),disabled:y<=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:[g.jsx("span",{className:"sr-only",children:d}),g.jsx(oO,{"aria-hidden":"true",className:"size-5"})]}),_.map((L,I)=>L==="ellipsis"?g.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}`):g.jsx(NM,{active:L===y,onClick:()=>S(L),rounded:"none",children:L},L)),g.jsxs("button",{type:"button",onClick:()=>S(y+1),disabled:y>=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:[g.jsx("span",{className:"sr-only",children:f}),g.jsx(uO,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}const FA=E.createContext(null);function OM(s){switch(s){case"success":return{Icon:CO,cls:"text-emerald-500"};case"error":return{Icon:aM,cls:"text-rose-500"};case"warning":return{Icon:RO,cls:"text-amber-500"};default:return{Icon:FO,cls:"text-sky-500"}}}function MM(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 PM(s){switch(s){case"success":return"Erfolg";case"error":return"Fehler";case"warning":return"Hinweis";default:return"Info"}}function BM(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function FM({children:s,maxToasts:e=3,defaultDurationMs:t=3500,position:i="bottom-right"}){const[n,r]=E.useState([]),[a,u]=E.useState(!0),c=E.useCallback(async()=>{try{const S=await fetch("/api/settings",{cache:"no-store"});if(!S.ok)return;const L=await S.json();u(!!(L?.enableNotifications??!0))}catch{}},[]);E.useEffect(()=>{c();const S=()=>c();return window.addEventListener("recorder-settings-updated",S),()=>window.removeEventListener("recorder-settings-updated",S)},[c]),E.useEffect(()=>{a||r(S=>S.filter(L=>L.type==="error"))},[a]);const d=E.useCallback(S=>{r(L=>L.filter(I=>I.id!==S))},[]),f=E.useCallback(()=>r([]),[]),p=E.useCallback(S=>{if(!a&&S.type!=="error")return"";const L=BM(),I=S.durationMs??t;return r(R=>[{...S,id:L,durationMs:I},...R].slice(0,Math.max(1,e))),I&&I>0&&window.setTimeout(()=>d(L),I),L},[t,e,d,a]),y=E.useMemo(()=>({push:p,remove:d,clear:f}),[p,d,f]),v=i==="top-right"||i==="top-left"?"items-start sm:items-start sm:justify-start":"items-end sm:items-end sm:justify-end",b=i.endsWith("left")?"sm:items-start":"sm:items-end",_=i.startsWith("top")?"top-0 bottom-auto":"bottom-0 top-auto";return g.jsxs(FA.Provider,{value:y,children:[s,g.jsx("div",{"aria-live":"assertive",className:["pointer-events-none fixed z-[80] inset-x-0",_].join(" "),children:g.jsx("div",{className:["flex w-full px-4 py-6 sm:p-6",v].join(" "),children:g.jsx("div",{className:["flex w-full flex-col space-y-3",b].join(" "),children:n.map(S=>{const{Icon:L,cls:I}=OM(S.type),R=(S.title||"").trim()||PM(S.type),$=(S.message||"").trim(),B=(S.imageUrl||"").trim(),F=(S.imageAlt||R).trim();return g.jsx(mh,{appear:!0,show:!0,children:g.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",MM(S.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:g.jsx("div",{className:"p-4",children:g.jsxs("div",{className:"flex items-start gap-3",children:[B?g.jsx("div",{className:"shrink-0",children:g.jsx("img",{src:B,alt:F,loading:"lazy",referrerPolicy:"no-referrer",className:["h-12 w-12 rounded-lg object-cover","ring-1 ring-black/10 dark:ring-white/10"].join(" ")})}):g.jsx("div",{className:"shrink-0",children:g.jsx(L,{className:["size-6",I].join(" "),"aria-hidden":"true"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:R}),$?g.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300 break-words",children:$}):null]}),g.jsxs("button",{type:"button",onClick:()=>d(S.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:[g.jsx("span",{className:"sr-only",children:"Close"}),g.jsx(dO,{"aria-hidden":"true",className:"size-5"})]})]})})})},S.id)})})})})]})}function UM(){const s=E.useContext(FA);if(!s)throw new Error("useToast must be used within ");return s}function UA(){const{push:s,remove:e,clear:t}=UM(),i=n=>(r,a,u)=>s({type:n,title:r,message:a,...u});return{push:s,remove:e,clear:t,success:i("success"),error:i("error"),info:i("info"),warning:i("warning")}}const nb=s=>(s||"").replaceAll("\\","/"),Rn=s=>{const t=nb(s).split("/");return t[t.length-1]||""},ar=s=>Rn(s.output||"")||s.id,jM=s=>{const e=nb(String(s??""));return e.includes("/.trash/")||e.endsWith("/.trash")};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 Ay(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 WS(s){const[e,t]=E.useState(!1);return E.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 $M=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},ol=s=>{const e=Rn(s||""),t=_o(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},jn=s=>(s||"").trim().toLowerCase(),YS=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n},gm=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:a,onToggleHot:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,doneTotal:p,page:y,pageSize:v,onPageChange:b,assetNonce:_,sortMode:S,onSortModeChange:L,modelsByKey:I}){const R=i??"hover",$=WS("(hover: hover) and (pointer: fine)"),B=UA(),F=E.useRef(new Map),[M,G]=E.useState(null),[D,O]=E.useState(null),W=E.useRef(null),Y=E.useRef(new WeakMap),[J,ae]=E.useState(()=>new Set),[se,K]=E.useState(()=>new Set),[X,ee]=E.useState(null),[le,pe]=E.useState(!1),[P,Q]=E.useState({}),[ue,he]=E.useState(null),[re,Pe]=E.useState(null),[Ee,Ge]=E.useState(0),Ve=E.useRef(null),lt=E.useCallback(()=>{Ve.current&&window.clearTimeout(Ve.current),Ve.current=window.setTimeout(()=>Ge(me=>me+1),80)},[]),[_t,mt]=E.useState(null),Ze="finishedDownloads_view",bt="finishedDownloads_includeKeep_v2",gt="finishedDownloads_mobileOptionsOpen_v1",[at,wt]=E.useState("table"),[Et,Ot]=E.useState(!1),[ot,ht]=E.useState(!1),ve=E.useRef(new Map),dt=E.useCallback(async()=>{if(!X||le)return;pe(!0);const me=ye=>{ae(Se=>{const Ue=new Set(Se);return Ue.delete(ye),Ue}),K(Se=>{const Ue=new Set(Se);return Ue.delete(ye),Ue}),Mi(Se=>{const Ue=new Set(Se);return Ue.delete(ye),Ue}),Wi(Se=>{const Ue=new Set(Se);return Ue.delete(ye),Ue})};try{if(X.kind==="delete"){const ye=await fetch(`/api/record/restore?token=${encodeURIComponent(X.undoToken)}`,{method:"POST"});if(!ye.ok){const Qe=await ye.text().catch(()=>"");throw new Error(Qe||`HTTP ${ye.status}`)}const Se=await ye.json().catch(()=>null),Ue=String(Se?.restoredFile||X.originalFile);me(X.originalFile),me(Ue),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),lt(),ee(null);return}if(X.kind==="keep"){const ye=await fetch(`/api/record/unkeep?file=${encodeURIComponent(X.keptFile)}`,{method:"POST"});if(!ye.ok){const Qe=await ye.text().catch(()=>"");throw new Error(Qe||`HTTP ${ye.status}`)}const Se=await ye.json().catch(()=>null),Ue=String(Se?.newFile||X.originalFile);me(X.originalFile),me(Ue),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:1}})),lt(),ee(null);return}if(X.kind==="hot"){const ye=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(X.currentFile)}`,{method:"POST"});if(!ye.ok){const Kt=await ye.text().catch(()=>"");throw new Error(Kt||`HTTP ${ye.status}`)}const Se=await ye.json().catch(()=>null),Ue=String(Se?.oldFile||X.currentFile),Qe=String(Se?.newFile||"");Qe&&ms(Ue,Qe),lt(),ee(null);return}}catch(ye){B.error("Undo fehlgeschlagen",String(ye?.message||ye))}finally{pe(!1)}},[X,le,B,lt]),[qe,st]=E.useState([]),ft=E.useMemo(()=>new Set(qe.map(jn)),[qe]),yt=E.useMemo(()=>{const me={},ye={};for(const[Se,Ue]of Object.entries(I??{})){const Qe=jn(Se),Kt=YS(Ue?.tags);me[Qe]=Kt,ye[Qe]=new Set(Kt.map(jn))}return{tagsByModelKey:me,tagSetByModelKey:ye}},[I]),[nt,jt]=E.useState(""),qt=E.useDeferredValue(nt),Yt=E.useMemo(()=>jn(qt).split(/\s+/g).map(me=>me.trim()).filter(Boolean),[qt]),Ut=E.useCallback(()=>jt(""),[]),Ni=E.useCallback(me=>{const ye=jn(me);st(Se=>Se.some(Qe=>jn(Qe)===ye)?Se.filter(Qe=>jn(Qe)!==ye):[...Se,me])},[]),rt=Yt.length>0||ft.size>0,Dt=E.useCallback(async me=>{const ye=await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(S)}&withCount=1${Et?"&includeKeep=1":""}`,{cache:"no-store",signal:me});if(!ye.ok)return;const Se=await ye.json().catch(()=>null),Ue=Array.isArray(Se?.items)?Se.items:[],Qe=Number(Se?.count??Se?.totalCount??Ue.length);he(Ue),Pe(Number.isFinite(Qe)?Qe:Ue.length)},[S,Et]),ii=E.useCallback(()=>st([]),[]);E.useEffect(()=>{try{const me=localStorage.getItem("finishedDownloads_pendingTags");if(!me)return;const ye=JSON.parse(me),Se=Array.isArray(ye)?ye.map(Ue=>String(Ue||"").trim()).filter(Boolean):[];if(Se.length===0)return;kc.flushSync(()=>st(Se)),y!==1&&b(1)}catch{}finally{try{localStorage.removeItem("finishedDownloads_pendingTags")}catch{}}},[]),E.useEffect(()=>{if(!rt)return;const me=new AbortController,ye=window.setTimeout(()=>{Dt(me.signal).catch(()=>{})},250);return()=>{window.clearTimeout(ye),me.abort()}},[rt,Dt]),E.useEffect(()=>{if(Ee===0)return;if(rt){const ye=new AbortController;return(async()=>{try{await Dt(ye.signal)}catch{}})(),()=>ye.abort()}const me=new AbortController;return(async()=>{try{const ye=await fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1${Et?"&includeKeep=1":""}`,{cache:"no-store",signal:me.signal});if(ye.ok){const Se=await ye.json().catch(()=>null),Ue=Array.isArray(Se?.items)?Se.items:[],Qe=Number(Se?.count??Se?.totalCount??Ue.length);if(he(Ue),Number.isFinite(Qe)&&Qe>=0){Pe(Qe);const Kt=Math.max(1,Math.ceil(Qe/v));if(y>Kt){b(Kt),he(null);return}}}}catch{}})(),()=>me.abort()},[Ee,y,v,b,S,rt,Dt,Et]),E.useEffect(()=>{rt||(he(null),Pe(null))},[y,v,S,Et,rt]),E.useEffect(()=>{if(!Et){rt||(he(null),Pe(null));return}if(rt)return;const me=new AbortController;return(async()=>{try{const ye=await fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1&includeKeep=1`,{cache:"no-store",signal:me.signal});if(!ye.ok)return;const Se=await ye.json().catch(()=>null),Ue=Array.isArray(Se?.items)?Se.items:[],Qe=Number(Se?.count??Se?.totalCount??Ue.length);he(Ue),Pe(Number.isFinite(Qe)?Qe:Ue.length)}catch{}})(),()=>me.abort()},[Et,rt,y,v,S]),E.useEffect(()=>{try{const me=localStorage.getItem(Ze);wt(me==="table"||me==="cards"||me==="gallery"?me:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{wt("table")}},[]),E.useEffect(()=>{try{localStorage.setItem(Ze,at)}catch{}},[at]),E.useEffect(()=>{try{const me=localStorage.getItem(bt);Ot(me==="1"||me==="true"||me==="yes")}catch{Ot(!1)}},[]),E.useEffect(()=>{try{localStorage.setItem(bt,Et?"1":"0")}catch{}},[Et]),E.useEffect(()=>{try{const me=localStorage.getItem(gt);ht(me==="1"||me==="true"||me==="yes")}catch{ht(!1)}},[]),E.useEffect(()=>{try{localStorage.setItem(gt,ot?"1":"0")}catch{}},[ot]);const[ci,mi]=E.useState({}),Ht=E.useRef({}),Oi=E.useRef(null);E.useEffect(()=>{Ht.current=ci},[ci]);const Ki=E.useCallback(()=>{Oi.current==null&&(Oi.current=window.setTimeout(()=>{Oi.current=null,mi({...Ht.current})},200))},[]);E.useEffect(()=>()=>{Oi.current!=null&&(window.clearTimeout(Oi.current),Oi.current=null)},[]);const[Lt,z]=E.useState(null),V=!n,te=E.useCallback(me=>{const Se=document.getElementById(me)?.querySelector("video");if(!Se)return!1;rp(Se,{muted:V});const Ue=Se.play?.();return Ue&&typeof Ue.catch=="function"&&Ue.catch(()=>{}),!0},[V]),xe=E.useCallback(me=>{z(ye=>ye?.key===me?{key:me,nonce:ye.nonce+1}:{key:me,nonce:1})},[]),Me=E.useCallback(me=>{z(null),r(me)},[r]),ut=E.useCallback((me,ye)=>{K(Se=>{const Ue=new Set(Se);return ye?Ue.add(me):Ue.delete(me),Ue})},[]),Pt=E.useCallback(me=>{ae(ye=>{const Se=new Set(ye);return Se.add(me),Se})},[]),[Ii,Mi]=E.useState(()=>new Set),Fi=E.useCallback((me,ye)=>{Mi(Se=>{const Ue=new Set(Se);return ye?Ue.add(me):Ue.delete(me),Ue})},[]),[Ui,Wi]=E.useState(()=>new Set),pi=E.useRef(new Map),os=E.useCallback((me,ye)=>{Wi(Se=>{const Ue=new Set(Se);return ye?Ue.add(me):Ue.delete(me),Ue})},[]),Yi=E.useCallback(me=>{const ye=pi.current.get(me);ye!=null&&(window.clearTimeout(ye),pi.current.delete(me))},[]),zi=E.useCallback(me=>{Yi(me),ae(ye=>{const Se=new Set(ye);return Se.delete(me),Se}),Wi(ye=>{const Se=new Set(ye);return Se.delete(me),Se}),K(ye=>{const Se=new Set(ye);return Se.delete(me),Se}),Mi(ye=>{const Se=new Set(ye);return Se.delete(me),Se})},[Yi]),si=E.useCallback(me=>{os(me,!0),Yi(me);const ye=window.setTimeout(()=>{pi.current.delete(me),Pt(me),os(me,!1),lt()},320);pi.current.set(me,ye)},[Pt,os,lt,Yi]),Gt=E.useCallback(async(me,ye)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:me}})),ye?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:me}})),await new Promise(Se=>window.setTimeout(Se,250))},[]),Xt=E.useCallback(async me=>{const ye=Rn(me.output||""),Se=ar(me);if(!ye)return B.error("Löschen nicht möglich","Kein Dateiname gefunden – kann nicht löschen."),!1;if(se.has(Se))return!1;ut(Se,!0);try{if(await Gt(ye,{close:!0}),a){const hi=(await a(me))?.undoToken;return ee(typeof hi=="string"&&hi?{kind:"delete",undoToken:hi,originalFile:ye}:null),si(Se),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}const Ue=await fetch(`/api/record/delete?file=${encodeURIComponent(ye)}`,{method:"POST"});if(!Ue.ok){const Zt=await Ue.text().catch(()=>"");throw new Error(Zt||`HTTP ${Ue.status}`)}const Qe=await Ue.json().catch(()=>null),Kt=typeof Qe?.undoToken=="string"?Qe.undoToken:"";return ee(Kt?{kind:"delete",undoToken:Kt,originalFile:ye}:null),si(Se),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(Ue){return zi(Se),B.error("Löschen fehlgeschlagen",String(Ue?.message||Ue)),!1}finally{ut(Se,!1)}},[se,ut,Gt,a,si,B,ee]),ys=E.useCallback(async me=>{const ye=Rn(me.output||""),Se=ar(me);if(!ye)return B.error("Keep nicht möglich","Kein Dateiname gefunden – kann nicht behalten."),!1;if(Ii.has(Se)||se.has(Se))return!1;Fi(Se,!0);try{await Gt(ye,{close:!0});const Ue=await fetch(`/api/record/keep?file=${encodeURIComponent(ye)}`,{method:"POST"});if(!Ue.ok){const Zt=await Ue.text().catch(()=>"");throw new Error(Zt||`HTTP ${Ue.status}`)}const Qe=await Ue.json().catch(()=>null),Kt=typeof Qe?.newFile=="string"&&Qe.newFile?Qe.newFile:ye;return ee({kind:"keep",keptFile:Kt,originalFile:ye}),si(Se),window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:-1}})),!0}catch(Ue){return B.error("Keep fehlgeschlagen",String(Ue?.message||Ue)),!1}finally{Fi(Se,!1)}},[Ii,se,Fi,Gt,si,B,ee]),ms=E.useCallback((me,ye)=>{if(!me||!ye||me===ye)return;Q(Qe=>{const Kt={...Qe};for(const[Zt,hi]of Object.entries(Kt))(Zt===me||Zt===ye||hi===me||hi===ye)&&delete Kt[Zt];return Kt[me]=ye,Kt}),z(Qe=>Qe?.key===me?{...Qe,key:ye}:Qe),G(Qe=>Qe===me?ye:Qe),O(Qe=>Qe===me?ye:Qe);const Se=Ht.current||{},Ue=Se[me];if(typeof Ue=="number"){const Qe={...Se};delete Qe[me],Qe[ye]=Ue,Ht.current=Qe,mi(Qe)}else if(me in Se){const Qe={...Se};delete Qe[me],Ht.current=Qe,mi(Qe)}},[]),vn=E.useCallback(async me=>{const ye=Rn(me.output||"");if(!ye){B.error("HOT nicht möglich","Kein Dateiname gefunden – kann nicht HOT togglen.");return}const Se=Zt=>uc(Zt)?_o(Zt):`HOT ${Zt}`,Ue=(Zt,hi)=>{!Zt||!hi||Zt===hi||ms(Zt,hi)},Qe=ye,Kt=Se(Qe);ms(Qe,Kt);try{if(await Gt(Qe,{close:!0}),u){const Gi=await u(me),Ns=typeof Gi?.oldFile=="string"?Gi.oldFile:"",li=typeof Gi?.newFile=="string"?Gi.newFile:"";Ns&&li&&Ue(Ns,li),ee({kind:"hot",currentFile:li||Kt}),lt();return}const Zt=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(Qe)}`,{method:"POST"});if(!Zt.ok){const Gi=await Zt.text().catch(()=>"");throw new Error(Gi||`HTTP ${Zt.status}`)}const hi=await Zt.json().catch(()=>null),Hi=typeof hi?.oldFile=="string"&&hi.oldFile?hi.oldFile:Qe,nn=typeof hi?.newFile=="string"&&hi.newFile?hi.newFile:Kt;Hi!==nn&&Ue(Hi,nn),ee({kind:"hot",currentFile:nn}),lt()}catch(Zt){ms(Kt,Qe),ee(null),B.error("HOT umbenennen fehlgeschlagen",String(Zt?.message||Zt))}},[Rn,B,ms,Gt,u,lt,ee]),Mn=E.useCallback(me=>{const ye=me?.durationSeconds;if(typeof ye=="number"&&Number.isFinite(ye)&&ye>0)return ye;const Se=Date.parse(String(me?.startedAt||"")),Ue=Date.parse(String(me?.endedAt||""));if(Number.isFinite(Se)&&Number.isFinite(Ue)&&Ue>Se){const Qe=(Ue-Se)/1e3;if(Qe>=1&&Qe<=1440*60)return Qe}return Number.POSITIVE_INFINITY},[]),vs=E.useCallback(me=>{const ye=nb(me.output||""),Se=Rn(ye),Ue=P[Se];if(!Ue)return me;const Qe=ye.lastIndexOf("/"),Kt=Qe>=0?ye.slice(0,Qe+1):"";return{...me,output:Kt+Ue}},[P,Rn]),Ti=ue??e,Is=re??p,Us=E.useMemo(()=>{const me=new Map;for(const Se of Ti){const Ue=vs(Se);me.set(ar(Ue),Ue)}for(const Se of s){const Ue=vs(Se),Qe=ar(Ue);me.has(Qe)&&me.set(Qe,{...me.get(Qe),...Ue})}return Array.from(me.values()).filter(Se=>J.has(ar(Se))||jM(Se.output)?!1:Se.status==="finished"||Se.status==="failed"||Se.status==="stopped")},[s,Ti,J,vs]);E.useEffect(()=>{const me=ye=>{const Se=ye.detail;if(!Se?.file)return;const Ue=Se.file;if(Se.phase==="start"){ut(Ue,!0),si(Ue);return}if(Se.phase==="error"){zi(Ue),ve.current.get(Ue)?.reset();return}if(Se.phase==="success"){ut(Ue,!1),lt();return}};return window.addEventListener("finished-downloads:delete",me),()=>window.removeEventListener("finished-downloads:delete",me)},[si,ut,lt,zi]),E.useEffect(()=>{const me=ye=>{const Se=ye.detail,Ue=String(Se?.oldFile??"").trim(),Qe=String(Se?.newFile??"").trim();!Ue||!Qe||Ue===Qe||ms(Ue,Qe)};return window.addEventListener("finished-downloads:rename",me),()=>window.removeEventListener("finished-downloads:rename",me)},[ms]);const bs=E.useMemo(()=>{const me=Us.filter(Se=>!J.has(ar(Se))),ye=Yt.length?me.filter(Se=>{const Ue=Rn(Se.output||""),Qe=ol(Se.output),Kt=jn(Qe),Zt=yt.tagsByModelKey[Kt]??[],hi=jn([Ue,_o(Ue),Qe,Se.id,Se.status,Zt.join(" ")].join(" "));for(const Hi of Yt)if(!hi.includes(Hi))return!1;return!0}):me;return ft.size===0?ye:ye.filter(Se=>{const Ue=jn(ol(Se.output)),Qe=yt.tagSetByModelKey[Ue];if(!Qe||Qe.size===0)return!1;for(const Kt of ft)if(!Qe.has(Kt))return!1;return!0})},[Us,J,ft,yt,Yt]),Pi=rt?bs.length:Is,Ts=E.useMemo(()=>{if(!rt)return bs;const me=(y-1)*v,ye=me+v;return bs.slice(Math.max(0,me),Math.max(0,ye))},[rt,bs,y,v]),xn=!rt&&Pi===0,tn=rt&&bs.length===0;E.useEffect(()=>{if(!rt)return;const me=Math.max(1,Math.ceil(bs.length/v));y>me&&b(me)},[rt,bs.length,y,v,b]),E.useEffect(()=>{if(!(R==="hover"&&!$&&(at==="cards"||at==="gallery"||at==="table"))){G(null),W.current?.disconnect(),W.current=null;return}if(at==="cards"&&Lt?.key){G(Lt.key);return}W.current?.disconnect();const ye=new IntersectionObserver(Se=>{let Ue=null,Qe=0;for(const Kt of Se){if(!Kt.isIntersecting)continue;const Zt=Y.current.get(Kt.target);Zt&&Kt.intersectionRatio>Qe&&(Qe=Kt.intersectionRatio,Ue=Zt)}Ue&&G(Kt=>Kt===Ue?Kt:Ue)},{threshold:[0,.15,.3,.5,.7,.9],rootMargin:"0px"});W.current=ye;for(const[Se,Ue]of F.current)Y.current.set(Ue,Se),ye.observe(Ue);return()=>{ye.disconnect(),W.current===ye&&(W.current=null)}},[at,R,$,Lt?.key]);const sn=me=>{const ye=ar(me),Se=ci[ye]??me?.durationSeconds;if(typeof Se=="number"&&Number.isFinite(Se)&&Se>0)return KS(Se*1e3);const Ue=Date.parse(String(me.startedAt||"")),Qe=Date.parse(String(me.endedAt||""));return Number.isFinite(Ue)&&Number.isFinite(Qe)&&Qe>Ue?KS(Qe-Ue):"—"},Or=E.useCallback(me=>ye=>{const Se=F.current.get(me);Se&&W.current&&W.current.unobserve(Se),ye?(F.current.set(me,ye),Y.current.set(ye,me),W.current?.observe(ye)):F.current.delete(me)},[]),Mr=E.useCallback((me,ye)=>{if(!Number.isFinite(ye)||ye<=0)return;const Se=ar(me),Ue=Ht.current[Se];typeof Ue=="number"&&Math.abs(Ue-ye)<.5||(Ht.current={...Ht.current,[Se]:ye},Ki())},[Ki]),js=[{key:"preview",header:"Vorschau",widthClassName:"w-[140px]",cell:me=>{const ye=ar(me),Ue=!(!!n&&D===ye);return g.jsx("div",{ref:Or(ye),className:"py-1",onClick:Qe=>Qe.stopPropagation(),onMouseDown:Qe=>Qe.stopPropagation(),onMouseEnter:()=>{$&&O(ye)},onMouseLeave:()=>{$&&O(null)},children:g.jsx(ib,{job:me,getFileName:Rn,durationSeconds:ci[ye],muted:Ue,popoverMuted:Ue,onDuration:Mr,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"?M===ye:!1,animatedMode:"teaser",animatedTrigger:"always",assetNonce:_})})}},{key:"Model",header:"Model",sortable:!0,sortValue:me=>{const ye=Rn(me.output||""),Se=uc(ye),Ue=ol(me.output),Qe=_o(ye);return`${Ue} ${Se?"HOT":""} ${Qe}`.trim()},cell:me=>{const ye=Rn(me.output||""),Se=uc(ye),Ue=_o(ye),Qe=ol(me.output),Kt=jn(ol(me.output)),Zt=YS(I[Kt]?.tags),hi=Zt.slice(0,6),Hi=Zt.length-hi.length,nn=Zt.join(", ");return g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:Qe}),g.jsxs("div",{className:"mt-0.5 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"truncate",title:Ue,children:Ue||"—"}),Se?g.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]}),hi.length>0?g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 min-w-0",children:[hi.map(Gi=>g.jsx(aa,{tag:Gi,active:ft.has(jn(Gi)),onClick:Ni},Gi)),Hi>0?g.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:nn,children:["+",Hi]}):null]}):null]})]})}},{key:"status",header:"Status",sortable:!0,sortValue:me=>me.status==="finished"?0:me.status==="stopped"?1:me.status==="failed"?2:9,cell:me=>{const ye="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset";if(me.status==="failed"){const Se=$M(me.error),Ue=Se?`failed (${Se})`:"failed";return g.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:me.error||"",children:Ue})}return me.status==="finished"?g.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"}):me.status==="stopped"?g.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"}):g.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:me.status})}},{key:"completedAt",header:"Fertiggestellt am",sortable:!0,widthClassName:"w-[150px]",sortValue:me=>{const ye=Date.parse(String(me.endedAt||""));return Number.isFinite(ye)?ye:Number.NEGATIVE_INFINITY},cell:me=>{const ye=Date.parse(String(me.endedAt||""));if(!Number.isFinite(ye))return g.jsx("span",{className:"text-xs text-gray-400",children:"—"});const Se=new Date(ye),Ue=Se.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),Qe=Se.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"});return g.jsxs("time",{dateTime:Se.toISOString(),title:`${Ue} ${Qe}`,className:"tabular-nums whitespace-nowrap text-sm text-gray-900 dark:text-white",children:[g.jsx("span",{className:"font-medium",children:Ue}),g.jsx("span",{className:"mx-1 text-gray-400 dark:text-gray-600",children:"·"}),g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:Qe})]})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:me=>Mn(me),cell:me=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:sn(me)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:me=>{const ye=gm(me);return typeof ye=="number"?ye:Number.NEGATIVE_INFINITY},cell:me=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Ay(gm(me))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:me=>{const ye=ar(me),Se=se.has(ye)||Ii.has(ye)||Ui.has(ye),Ue=Rn(me.output||""),Qe=uc(Ue),Kt=jn(ol(me.output)),Zt=I[Kt],hi=!!Zt?.favorite,Hi=Zt?.liked===!0,nn=!!Zt?.watching;return g.jsx(Ua,{job:me,variant:"table",busy:Se,isHot:Qe,isFavorite:hi,isLiked:Hi,isWatching:nn,onToggleWatch:f,onToggleFavorite:c,onToggleLike:d,onToggleHot:vn,onKeep:ys,onDelete:Xt,order:["watch","favorite","like","hot","details","add","keep","delete"],className:"flex items-center justify-end gap-1"})}}],bn=me=>{if(!me)return"completed_desc";const ye=me,Se=String(ye.key??ye.columnKey??ye.id??""),Ue=String(ye.dir??ye.direction??ye.order??"").toLowerCase(),Qe=Ue==="asc"||Ue==="1"||Ue==="true";return Se==="completedAt"?Qe?"completed_asc":"completed_desc":Se==="runtime"?Qe?"duration_asc":"duration_desc":Se==="size"?Qe?"size_asc":"size_desc":Se==="Model"||Se==="video"?Qe?"file_asc":"file_desc":Qe?"completed_asc":"completed_desc"},Pn=me=>{mt(me);const ye=bn(me);L(ye),y!==1&&b(1)},Bi=WS("(max-width: 639px)");return E.useEffect(()=>{Bi||(ve.current=new Map)},[Bi]),E.useEffect(()=>{let me=null,ye=!1,Se=null,Ue=null;const Qe=()=>{Ue==null&&(Ue=window.setTimeout(()=>{Ue=null,xn&&y!==1&&b(1),lt()},80))},Kt=()=>{if(!ye)try{me=new EventSource("/api/record/done/stream"),me.onmessage=()=>{Qe()},me.onerror=()=>{try{me?.close()}catch{}me=null,!ye&&(Se!=null&&window.clearTimeout(Se),Se=window.setTimeout(Kt,1e3))}}catch{Se!=null&&window.clearTimeout(Se),Se=window.setTimeout(Kt,1e3)}};return Kt(),()=>{ye=!0,Se!=null&&window.clearTimeout(Se),Ue!=null&&window.clearTimeout(Ue);try{me?.close()}catch{}}},[lt,xn,y,b]),E.useEffect(()=>{xn&&y!==1&&b(1)},[xn,y,b]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:[g.jsxs("div",{className:"flex items-center gap-3 p-3",children:[g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Pi})]}),g.jsxs("div",{className:"sm:hidden flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Pi})]}),g.jsxs("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:[g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("input",{value:nt,onChange:me=>jt(me.target.value),placeholder:"Suchen…",className:` + h-9 w-full max-w-[420px] 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] + `}),(nt||"").trim()!==""?g.jsx(ti,{size:"sm",variant:"soft",onClick:Ut,children:"Leeren"}):null]}),g.jsx("div",{className:"hidden sm:block",children:g.jsx(po,{label:"Behaltene Downloads anzeigen",checked:Et,onChange:me=>{y!==1&&b(1),Ot(me),lt()}})}),at!=="table"&&g.jsxs("div",{className:"hidden sm:block",children:[g.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort",value:S,onChange:me=>{const ye=me.target.value;L(ye),y!==1&&b(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:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),g.jsx(ti,{size:Bi?"sm":"md",variant:"soft",disabled:!X||le,onClick:dt,title:X?`Letzte Aktion rückgängig machen (${X.kind})`:"Keine Aktion zum Rückgängig machen",children:"Undo"}),g.jsx(pO,{value:at,onChange:me=>wt(me),size:Bi?"sm":"md",ariaLabel:"Ansicht",items:[{id:"table",icon:g.jsx(tM,{className:Bi?"size-4":"size-5"}),label:Bi?void 0:"Tabelle",srLabel:"Tabelle"},{id:"cards",icon:g.jsx(YO,{className:Bi?"size-4":"size-5"}),label:Bi?void 0:"Cards",srLabel:"Cards"},{id:"gallery",icon:g.jsx(ZO,{className:Bi?"size-4":"size-5"}),label:Bi?void 0:"Galerie",srLabel:"Galerie"}]}),g.jsxs("button",{type:"button",className:`sm:hidden relative inline-flex items-center justify-center rounded-md border border-gray-200 bg-white p-2 shadow-sm + hover:bg-gray-50 dark:border-white/10 dark:bg-gray-900 dark:text-gray-100 dark:hover:bg-white/10`,onClick:()=>ht(me=>!me),"aria-expanded":ot,"aria-controls":"finished-mobile-options","aria-label":"Filter & Optionen",children:[g.jsx(yO,{className:"size-5"}),rt||Et?g.jsx("span",{className:"absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-indigo-500 ring-2 ring-white dark:ring-gray-950"}):null]})]})]}),qe.length>0?g.jsxs("div",{className:"hidden sm:flex items-center gap-2 border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[qe.map(me=>g.jsx(aa,{tag:me,active:!0,onClick:Ni},me)),g.jsx(ti,{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:ii,children:"Zurücksetzen"})]})]}):null,g.jsxs("div",{id:"finished-mobile-options",className:["sm:hidden overflow-hidden transition-[max-height,opacity] duration-200 ease-in-out",ot?"max-h-[720px] opacity-100":"max-h-0 opacity-0"].join(" "),children:[g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 p-3",children:g.jsxs("div",{className:"space-y-2",children:[g.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("input",{value:nt,onChange:me=>jt(me.target.value),placeholder:"Suchen…",className:` + h-10 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-900 + focus:outline-none focus:ring-2 focus:ring-indigo-500 + dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] + `}),(nt||"").trim()!==""?g.jsx(ti,{size:"sm",variant:"soft",onClick:Ut,children:"Clear"}):null]})}),g.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-100",children:"Keep anzeigen"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Behaltene Downloads in der Liste"})]}),g.jsx(Qv,{checked:Et,onChange:me=>{y!==1&&b(1),Ot(me),lt()},ariaLabel:"Behaltene Downloads anzeigen",size:"default"})]})}),at!=="table"?g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/60",children:[g.jsx("div",{className:"text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort-mobile",value:S,onChange:me=>{const ye=me.target.value;L(ye),y!==1&&b(1)},className:` + w-full h-10 rounded-md border border-gray-200 bg-white px-2 text-sm text-gray-900 shadow-sm + dark:border-white/10 dark:bg-gray-950/60 dark:text-gray-100 dark:[color-scheme:dark] + `,children:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}):null]})}),qe.length>0?g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[qe.map(me=>g.jsx(aa,{tag:me,active:!0,onClick:Ni},me)),g.jsx(ti,{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:ii,children:"Zurücksetzen"})]})]})}):null]})]})}),xn?g.jsx(ja,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"📁"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine abgeschlossenen Downloads"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Im Zielordner ist aktuell nichts vorhanden."})]})]})}):tn?g.jsxs(ja,{grayBody:!0,children:[g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Treffer für die aktuellen Filter."}),qe.length>0||(nt||"").trim()!==""?g.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[qe.length>0?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:ii,children:"Tag-Filter zurücksetzen"}):null,(nt||"").trim()!==""?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:Ut,children:"Suche zurücksetzen"}):null]}):null]}):g.jsxs(g.Fragment,{children:[at==="cards"&&g.jsx(DM,{rows:Ts,isSmall:Bi,blurPreviews:t,durations:ci,teaserKey:M,teaserPlayback:R,teaserAudio:n,hoverTeaserKey:D,inlinePlay:Lt,setInlinePlay:z,deletingKeys:se,keepingKeys:Ii,removingKeys:Ui,swipeRefs:ve,keyFor:ar,baseName:Rn,modelNameFromOutput:ol,runtimeOf:sn,sizeBytesOf:gm,formatBytes:Ay,lower:jn,onOpenPlayer:r,openPlayer:Me,startInline:xe,tryAutoplayInline:te,registerTeaserHost:Or,handleDuration:Mr,deleteVideo:Xt,keepVideo:ys,releasePlayingFile:Gt,modelsByKey:I,onToggleHot:vn,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:ft,onToggleTagFilter:Ni,onHoverPreviewKeyChange:O,assetNonce:_??0}),at==="table"&&g.jsx(LM,{rows:Ts,columns:js,getRowKey:me=>ar(me),sort:_t,onSortChange:Pn,onRowClick:r,rowClassName:me=>{const ye=ar(me);return["transition-all duration-300",(se.has(ye)||Ui.has(ye))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",se.has(ye)&&"animate-pulse",(Ii.has(ye)||Ui.has(ye))&&"pointer-events-none",Ii.has(ye)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",Ui.has(ye)&&"opacity-0"].filter(Boolean).join(" ")}}),at==="gallery"&&g.jsx(RM,{rows:Ts,blurPreviews:t,durations:ci,handleDuration:Mr,teaserKey:M,teaserPlayback:R,teaserAudio:n,hoverTeaserKey:D,keyFor:ar,baseName:Rn,modelNameFromOutput:ol,runtimeOf:sn,sizeBytesOf:gm,formatBytes:Ay,deletingKeys:se,keepingKeys:Ii,removingKeys:Ui,deletedKeys:J,registerTeaserHost:Or,onOpenPlayer:r,deleteVideo:Xt,keepVideo:ys,onToggleHot:vn,lower:jn,modelsByKey:I,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:ft,onToggleTagFilter:Ni,onHoverPreviewKeyChange:O}),g.jsx(BA,{page:y,pageSize:v,totalItems:Pi,onPageChange:me=>{kc.flushSync(()=>{z(null),G(null),O(null)});for(const ye of Ts){const Se=Rn(ye.output||"");Se&&(window.dispatchEvent(new CustomEvent("player:release",{detail:{file:Se}})),window.dispatchEvent(new CustomEvent("player:close",{detail:{file:Se}})))}window.scrollTo({top:0,behavior:"auto"}),b(me)},showSummary:!1,prevLabel:"Zurück",nextLabel:"Weiter",className:"mt-4"})]})]})}var Cy,XS;function Yp(){if(XS)return Cy;XS=1;var s;return typeof window<"u"?s=window:typeof ep<"u"?s=ep:typeof self<"u"?s=self:s={},Cy=s,Cy}var GM=Yp();const de=Vc(GM),VM={},zM=Object.freeze(Object.defineProperty({__proto__:null,default:VM},Symbol.toStringTag,{value:"Module"})),qM=RI(zM);var ky,QS;function jA(){if(QS)return ky;QS=1;var s=typeof ep<"u"?ep:typeof window<"u"?window:{},e=qM,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),ky=t,ky}var KM=jA();const pt=Vc(KM);var ym={exports:{}},Dy={exports:{}},ZS;function WM(){return ZS||(ZS=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 a=Object.prototype.toString.call(n).slice(8,-1);if(a==="Object"&&n.constructor&&(a=n.constructor.name),a==="Map"||a==="Set")return Array.from(n);if(a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var a=0,u=new Array(r);a=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 a=r.split("="),u=a[0],c=a[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Ny=e,Ny}var sE;function JM(){if(sE)return ym.exports;sE=1;var s=Yp(),e=WM(),t=YM(),i=XM(),n=QM();d.httpHandler=ZM(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(b){var _={};return b&&b.trim().split(` +`).forEach(function(S){var L=S.indexOf(":"),I=S.slice(0,L).trim().toLowerCase(),R=S.slice(L+1).trim();typeof _[I]>"u"?_[I]=R:Array.isArray(_[I])?_[I].push(R):_[I]=[_[I],R]}),_};ym.exports=d,ym.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||y,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,a(["get","put","post","patch","head","delete"],function(v){d[v==="delete"?"del":v]=function(b,_,S){return _=c(b,_,S),_.method=v.toUpperCase(),f(_)}});function a(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 S=!1,L=function(ee,le,pe){S||(S=!0,v.callback(ee,le,pe))};function I(){F.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(B,0)}function R(){var X=void 0;if(F.response?X=F.response:X=F.responseText||p(F),ae)try{X=JSON.parse(X)}catch{}return X}function $(X){if(clearTimeout(se),clearTimeout(v.retryTimeout),X instanceof Error||(X=new Error(""+(X||"Unknown XMLHttpRequest Error"))),X.statusCode=0,!G&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=F,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ee={headers:K.headers||{},body:K.body,responseUrl:F.responseURL,responseType:F.responseType},le=d.responseInterceptorsStorage.execute(v.requestType,ee);K.body=le.body,K.headers=le.headers}return L(X,K)}function B(){if(!G){var X;clearTimeout(se),clearTimeout(v.retryTimeout),v.useXDR&&F.status===void 0?X=200:X=F.status===1223?204:F.status;var ee=K,le=null;if(X!==0?(ee={body:R(),statusCode:X,method:O,headers:{},url:D,rawRequest:F},F.getAllResponseHeaders&&(ee.headers=r(F.getAllResponseHeaders()))):le=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var pe={headers:ee.headers||{},body:ee.body,responseUrl:F.responseURL,responseType:F.responseType},P=d.responseInterceptorsStorage.execute(v.requestType,pe);ee.body=P.body,ee.headers=P.headers}return L(le,ee,ee.body)}}var F=v.xhr||null;F||(v.cors||v.useXDR?F=new d.XDomainRequest:F=new d.XMLHttpRequest);var M,G,D=F.url=v.uri||v.url,O=F.method=v.method||"GET",W=v.body||v.data,Y=F.headers=v.headers||{},J=!!v.sync,ae=!1,se,K={body:void 0,headers:{},statusCode:0,method:O,url:D,rawRequest:F};if("json"in v&&v.json!==!1&&(ae=!0,Y.accept||Y.Accept||(Y.Accept="application/json"),O!=="GET"&&O!=="HEAD"&&(Y["content-type"]||Y["Content-Type"]||(Y["Content-Type"]="application/json"),W=JSON.stringify(v.json===!0?W:v.json))),F.onreadystatechange=I,F.onload=B,F.onerror=$,F.onprogress=function(){},F.onabort=function(){G=!0,clearTimeout(v.retryTimeout)},F.ontimeout=$,F.open(O,D,!J,v.username,v.password),J||(F.withCredentials=!!v.withCredentials),!J&&v.timeout>0&&(se=setTimeout(function(){if(!G){G=!0,F.abort("timeout");var X=new Error("XMLHttpRequest timeout");X.code="ETIMEDOUT",$(X)}},v.timeout)),F.setRequestHeader)for(M in Y)Y.hasOwnProperty(M)&&F.setRequestHeader(M,Y[M]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&(F.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend(F),F.send(W||null),F}function p(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 y(){}return ym.exports}var e3=JM();const $A=Vc(e3);var Oy={exports:{}},My,nE;function t3(){if(nE)return My;nE=1;var s=jA(),e=Object.create||(function(){function D(){}return function(O){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return D.prototype=O,new D}})();function t(D,O){this.name="ParsingError",this.code=D.code,this.message=O||D.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(D){function O(Y,J,ae,se){return(Y|0)*3600+(J|0)*60+(ae|0)+(se|0)/1e3}var W=D.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return W?W[3]?O(W[1],W[2],W[3].replace(":",""),W[4]):W[1]>59?O(W[1],W[2],0,W[4]):O(0,W[1],W[2],W[4]):null}function n(){this.values=e(null)}n.prototype={set:function(D,O){!this.get(D)&&O!==""&&(this.values[D]=O)},get:function(D,O,W){return W?this.has(D)?this.values[D]:O[W]:this.has(D)?this.values[D]:O},has:function(D){return D in this.values},alt:function(D,O,W){for(var Y=0;Y=0&&O<=100)?(this.set(D,O),!0):!1}};function r(D,O,W,Y){var J=Y?D.split(Y):[D];for(var ae in J)if(typeof J[ae]=="string"){var se=J[ae].split(W);if(se.length===2){var K=se[0].trim(),X=se[1].trim();O(K,X)}}}function a(D,O,W){var Y=D;function J(){var K=i(D);if(K===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+Y);return D=D.replace(/^[^\sa-zA-Z-]+/,""),K}function ae(K,X){var ee=new n;r(K,function(le,pe){switch(le){case"region":for(var P=W.length-1;P>=0;P--)if(W[P].id===pe){ee.set(le,W[P].region);break}break;case"vertical":ee.alt(le,pe,["rl","lr"]);break;case"line":var Q=pe.split(","),ue=Q[0];ee.integer(le,ue),ee.percent(le,ue)&&ee.set("snapToLines",!1),ee.alt(le,ue,["auto"]),Q.length===2&&ee.alt("lineAlign",Q[1],["start","center","end"]);break;case"position":Q=pe.split(","),ee.percent(le,Q[0]),Q.length===2&&ee.alt("positionAlign",Q[1],["start","center","end"]);break;case"size":ee.percent(le,pe);break;case"align":ee.alt(le,pe,["start","center","end","left","right"]);break}},/:/,/\s/),X.region=ee.get("region",null),X.vertical=ee.get("vertical","");try{X.line=ee.get("line","auto")}catch{}X.lineAlign=ee.get("lineAlign","start"),X.snapToLines=ee.get("snapToLines",!0),X.size=ee.get("size",100);try{X.align=ee.get("align","center")}catch{X.align=ee.get("align","middle")}try{X.position=ee.get("position","auto")}catch{X.position=ee.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},X.align)}X.positionAlign=ee.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},X.align)}function se(){D=D.replace(/^\s+/,"")}if(se(),O.startTime=J(),se(),D.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+Y);D=D.substr(3),se(),O.endTime=J(),se(),ae(D,O)}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 y(D,O){function W(){if(!O)return null;function ue(re){return O=O.substr(re.length),re}var he=O.match(/^([^<]*)(<[^>]*>?)?/);return ue(he[1]?he[1]:he[2])}function Y(ue){return u.innerHTML=ue,ue=u.textContent,u.textContent="",ue}function J(ue,he){return!p[he.localName]||p[he.localName]===ue.localName}function ae(ue,he){var re=c[ue];if(!re)return null;var Pe=D.document.createElement(re),Ee=f[ue];return Ee&&he&&(Pe[Ee]=he.trim()),Pe}for(var se=D.document.createElement("div"),K=se,X,ee=[];(X=W())!==null;){if(X[0]==="<"){if(X[1]==="/"){ee.length&&ee[ee.length-1]===X.substr(2).replace(">","")&&(ee.pop(),K=K.parentNode);continue}var le=i(X.substr(1,X.length-2)),pe;if(le){pe=D.document.createProcessingInstruction("timestamp",le),K.appendChild(pe);continue}var P=X.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!P||(pe=ae(P[1],P[3]),!pe)||!J(K,pe))continue;if(P[2]){var Q=P[2].split(".");Q.forEach(function(ue){var he=/^bg_/.test(ue),re=he?ue.slice(3):ue;if(d.hasOwnProperty(re)){var Pe=he?"background-color":"color",Ee=d[re];pe.style[Pe]=Ee}}),pe.className=Q.join(" ")}ee.push(P[1]),K.appendChild(pe),K=pe;continue}K.appendChild(D.document.createTextNode(Y(X)))}return se}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(D){for(var O=0;O=W[0]&&D<=W[1])return!0}return!1}function _(D){var O=[],W="",Y;if(!D||!D.childNodes)return"ltr";function J(K,X){for(var ee=X.childNodes.length-1;ee>=0;ee--)K.push(X.childNodes[ee])}function ae(K){if(!K||!K.length)return null;var X=K.pop(),ee=X.textContent||X.innerText;if(ee){var le=ee.match(/^.*(\n|\r)/);return le?(K.length=0,le[0]):ee}if(X.tagName==="ruby")return ae(K);if(X.childNodes)return J(K,X),ae(K)}for(J(O,D);W=ae(O);)for(var se=0;se=0&&D.line<=100))return D.line;if(!D.track||!D.track.textTrackList||!D.track.textTrackList.mediaElement)return-1;for(var O=D.track,W=O.textTrackList,Y=0,J=0;JD.left&&this.topD.top},R.prototype.overlapsAny=function(D){for(var O=0;O=D.top&&this.bottom<=D.bottom&&this.left>=D.left&&this.right<=D.right},R.prototype.overlapsOppositeAxis=function(D,O){switch(O){case"+x":return this.leftD.right;case"+y":return this.topD.bottom}},R.prototype.intersectPercentage=function(D){var O=Math.max(0,Math.min(this.right,D.right)-Math.max(this.left,D.left)),W=Math.max(0,Math.min(this.bottom,D.bottom)-Math.max(this.top,D.top)),Y=O*W;return Y/(this.height*this.width)},R.prototype.toCSSCompatValues=function(D){return{top:this.top-D.top,bottom:D.bottom-this.bottom,left:this.left-D.left,right:D.right-this.right,height:this.height,width:this.width}},R.getSimpleBoxPosition=function(D){var O=D.div?D.div.offsetHeight:D.tagName?D.offsetHeight:0,W=D.div?D.div.offsetWidth:D.tagName?D.offsetWidth:0,Y=D.div?D.div.offsetTop:D.tagName?D.offsetTop:0;D=D.div?D.div.getBoundingClientRect():D.tagName?D.getBoundingClientRect():D;var J={left:D.left,right:D.right,top:D.top||Y,height:D.height||O,bottom:D.bottom||Y+(D.height||O),width:D.width||W};return J};function $(D,O,W,Y){function J(re,Pe){for(var Ee,Ge=new R(re),Ve=1,lt=0;lt_t&&(Ee=new R(re),Ve=_t),re=new R(Ge)}return Ee||Ge}var ae=new R(O),se=O.cue,K=S(se),X=[];if(se.snapToLines){var ee;switch(se.vertical){case"":X=["+y","-y"],ee="height";break;case"rl":X=["+x","-x"],ee="width";break;case"lr":X=["-x","+x"],ee="width";break}var le=ae.lineHeight,pe=le*Math.round(K),P=W[ee]+le,Q=X[0];Math.abs(pe)>P&&(pe=pe<0?-1:1,pe*=Math.ceil(P/le)*le),K<0&&(pe+=se.vertical===""?W.height:W.width,X=X.reverse()),ae.move(Q,pe)}else{var ue=ae.lineHeight/W.height*100;switch(se.lineAlign){case"center":K-=ue/2;break;case"end":K-=ue;break}switch(se.vertical){case"":O.applyStyles({top:O.formatStyle(K,"%")});break;case"rl":O.applyStyles({left:O.formatStyle(K,"%")});break;case"lr":O.applyStyles({right:O.formatStyle(K,"%")});break}X=["+y","-x","+x","-y"],ae=new R(O)}var he=J(ae,X);O.move(he.toCSSCompatValues(W))}function B(){}B.StringDecoder=function(){return{decode:function(D){if(!D)return"";if(typeof D!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(D))}}},B.convertCueToDOMTree=function(D,O){return!D||!O?null:y(D,O)};var F=.05,M="sans-serif",G="1.5%";return B.processCues=function(D,O,W){if(!D||!O||!W)return null;for(;W.firstChild;)W.removeChild(W.firstChild);var Y=D.document.createElement("div");Y.style.position="absolute",Y.style.left="0",Y.style.right="0",Y.style.top="0",Y.style.bottom="0",Y.style.margin=G,W.appendChild(Y);function J(le){for(var pe=0;pe")===-1){O.cue.id=se;continue}case"CUE":try{a(se,O.cue,O.regionList)}catch(le){O.reportOrThrowError(le),O.cue=null,O.state="BADCUE";continue}O.state="CUETEXT";continue;case"CUETEXT":var ee=se.indexOf("-->")!==-1;if(!se||ee&&(X=!0)){O.oncue&&O.oncue(O.cue),O.cue=null,O.state="ID";continue}O.cue.text&&(O.cue.text+=` +`),O.cue.text+=se.replace(/\u2028/g,` +`).replace(/u2029/g,` +`);continue;case"BADCUE":se||(O.state="ID");continue}}}catch(le){O.reportOrThrowError(le),O.state==="CUETEXT"&&O.cue&&O.oncue&&O.oncue(O.cue),O.cue=null,O.state=O.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var D=this;try{if(D.buffer+=D.decoder.decode(),(D.cue||D.state==="HEADER")&&(D.buffer+=` + +`,D.parse()),D.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(O){D.reportOrThrowError(O)}return D.onflush&&D.onflush(),this}},My=B,My}var Py,rE;function i3(){if(rE)return Py;rE=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(a){if(typeof a!="string")return!1;var u=e[a.toLowerCase()];return u?a.toLowerCase():!1}function n(a){if(typeof a!="string")return!1;var u=t[a.toLowerCase()];return u?a.toLowerCase():!1}function r(a,u,c){this.hasBeenReset=!1;var d="",f=!1,p=a,y=u,v=c,b=null,_="",S=!0,L="auto",I="start",R="auto",$="auto",B=100,F="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 y},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");y=M,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return v},set:function(M){v=""+M,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return b},set:function(M){b=M,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _},set:function(M){var G=i(M);if(G===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_=G,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return S},set:function(M){S=!!M,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return L},set:function(M){if(typeof M!="number"&&M!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");L=M,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return I},set:function(M){var G=n(M);G?(I=G,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return R},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");R=M,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return $},set:function(M){var G=n(M);G?($=G,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return B},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");B=M,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return F},set:function(M){var G=n(M);if(!G)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");F=G,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Py=r,Py}var By,aE;function s3(){if(aE)return By;aE=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,a=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 a},set:function(p){if(!t(p))throw new Error("RegionAnchorY must be between 0 and 100.");a=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 y=e(p);y===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=y}}})}return By=i,By}var oE;function n3(){if(oE)return Oy.exports;oE=1;var s=Yp(),e=Oy.exports={WebVTT:t3(),VTTCue:i3(),VTTRegion:s3()};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 r3=n3();const lE=Vc(r3);function Ks(){return Ks=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,a=0;a-1;t=this.buffer.indexOf(` +`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const l3=" ",Fy=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},u3=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},$n=function(s){const e={};if(!s)return e;const t=s.split(u3());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},cE=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 c3 extends rb{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,a)=>{const u=a(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let a=0;ar),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 d3=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),ll=function(s){const e={};return Object.keys(s).forEach(function(t){e[d3(t)]=s[t]}),e},Uy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",a="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&&a&&(n.key=a),!n.timeline&&typeof p=="number"&&(n.timeline=p),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(_){let S,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 R in _.attributes)typeof _.attributes[R]=="string"&&(_.attributes[R]=_.attributes[R].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=y)),"offset"in _&&(n.byterange=I,I.offset=_.offset),y=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"){a=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:HA(_.attributes.URI.split(",")[1])};return}_.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),a={method:_.attributes.METHOD||"AES-128",uri:_.attributes.URI},typeof _.attributes.IV<"u"&&(a.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),a&&(r.key=a)},"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={}),Ks(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"]]||{},S=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)),S[_.attributes.NAME]=L},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((R,$)=>($.programDateTime=R-$.duration*1e3,$.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(_.duration)||_.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+_.duration});return}this.manifest.targetDuration=_.duration,Uy.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=ll(_.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",_.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const I=this.manifest.segments.length,R=ll(_.attributes);n.parts=n.parts||[],n.parts.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=v),v=R.byterange.offset+R.byterange.length);const $=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${$} for segment #${I}`,_.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((B,F)=>{B.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${F} lacks required attribute(s): LAST-PART`})})},"server-control"(){const I=this.manifest.serverControl=ll(_.attributes);I.hasOwnProperty("canBlockReload")||(I.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Uy.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,R=ll(_.attributes),$=R.type&&R.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=$?v:0,$&&(v=R.byterange.offset+R.byterange.length)));const B=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${B} for segment #${I}`,_.attributes,["TYPE","URI"]),!!R.type)for(let F=0;FF.id===R.id);this.manifest.dateRanges[B]=Ks(this.manifest.dateRanges[B],R),b[R.id]=Ks(b[R.id],R),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=ll(_.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",_.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const I=(R,$)=>{if(R in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${R}`});return}this.manifest.definitions[R]=$};if("QUERYPARAM"in _.attributes){if("NAME"in _.attributes||"IMPORT"in _.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const R=this.params.get(_.attributes.QUERYPARAM);if(!R){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${_.attributes.QUERYPARAM}`});return}I(_.attributes.QUERYPARAM,decodeURIComponent(R));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),a&&(n.key=a),n.timeline=p,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){(ep&&(f-=p,f-=p,f-=wn(2))}return Number(f)},S3=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=wn(e);for(var a=b3(e),u=new Uint8Array(new ArrayBuffer(a)),c=0;c=t.length&&d.call(t,function(f,p){var y=c[p]?c[p]&e[a+p]:e[a+p];return f===y})},w3=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var a in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][a];i(u,n,r,a)}})},Yd={},uo={},Xl={},fE;function Qp(){if(fE)return Xl;fE=1;function s(r,a,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,a);for(var c=0;c=0&&z=0){for(var Me=V.length-1;xe0},lookupPrefix:function(z){for(var V=this;V;){var te=V._nsMap;if(te){for(var xe in te)if(Object.prototype.hasOwnProperty.call(te,xe)&&te[xe]===z)return xe}V=V.nodeType==y?V.ownerDocument:V.parentNode}return null},lookupNamespaceURI:function(z){for(var V=this;V;){var te=V._nsMap;if(te&&Object.prototype.hasOwnProperty.call(te,z))return te[z];V=V.nodeType==y?V.ownerDocument:V.parentNode}return null},isDefaultNamespace:function(z){var V=this.lookupPrefix(z);return V==null}};function Q(z){return z=="<"&&"<"||z==">"&&">"||z=="&"&&"&"||z=='"'&&"""||"&#"+z.charCodeAt()+";"}c(f,P),c(f,P.prototype);function ue(z,V){if(V(z))return!0;if(z=z.firstChild)do if(ue(z,V))return!0;while(z=z.nextSibling)}function he(){this.ownerDocument=this}function re(z,V,te){z&&z._inc++;var xe=te.namespaceURI;xe===t.XMLNS&&(V._nsMap[te.prefix?te.localName:""]=te.value)}function Pe(z,V,te,xe){z&&z._inc++;var Me=te.namespaceURI;Me===t.XMLNS&&delete V._nsMap[te.prefix?te.localName:""]}function Ee(z,V,te){if(z&&z._inc){z._inc++;var xe=V.childNodes;if(te)xe[xe.length++]=te;else{for(var Me=V.firstChild,ut=0;Me;)xe[ut++]=Me,Me=Me.nextSibling;xe.length=ut,delete xe[xe.length]}}}function Ge(z,V){var te=V.previousSibling,xe=V.nextSibling;return te?te.nextSibling=xe:z.firstChild=xe,xe?xe.previousSibling=te:z.lastChild=te,V.parentNode=null,V.previousSibling=null,V.nextSibling=null,Ee(z.ownerDocument,z),V}function Ve(z){return z&&(z.nodeType===P.DOCUMENT_NODE||z.nodeType===P.DOCUMENT_FRAGMENT_NODE||z.nodeType===P.ELEMENT_NODE)}function lt(z){return z&&(mt(z)||Ze(z)||_t(z)||z.nodeType===P.DOCUMENT_FRAGMENT_NODE||z.nodeType===P.COMMENT_NODE||z.nodeType===P.PROCESSING_INSTRUCTION_NODE)}function _t(z){return z&&z.nodeType===P.DOCUMENT_TYPE_NODE}function mt(z){return z&&z.nodeType===P.ELEMENT_NODE}function Ze(z){return z&&z.nodeType===P.TEXT_NODE}function bt(z,V){var te=z.childNodes||[];if(e(te,mt)||_t(V))return!1;var xe=e(te,_t);return!(V&&xe&&te.indexOf(xe)>te.indexOf(V))}function gt(z,V){var te=z.childNodes||[];function xe(ut){return mt(ut)&&ut!==V}if(e(te,xe))return!1;var Me=e(te,_t);return!(V&&Me&&te.indexOf(Me)>te.indexOf(V))}function at(z,V,te){if(!Ve(z))throw new Y(D,"Unexpected parent node type "+z.nodeType);if(te&&te.parentNode!==z)throw new Y(O,"child not in parent");if(!lt(V)||_t(V)&&z.nodeType!==P.DOCUMENT_NODE)throw new Y(D,"Unexpected node type "+V.nodeType+" for parent node type "+z.nodeType)}function wt(z,V,te){var xe=z.childNodes||[],Me=V.childNodes||[];if(V.nodeType===P.DOCUMENT_FRAGMENT_NODE){var ut=Me.filter(mt);if(ut.length>1||e(Me,Ze))throw new Y(D,"More than one element or text in fragment");if(ut.length===1&&!bt(z,te))throw new Y(D,"Element in fragment can not be inserted before doctype")}if(mt(V)&&!bt(z,te))throw new Y(D,"Only one element can be added and only after doctype");if(_t(V)){if(e(xe,_t))throw new Y(D,"Only one doctype is allowed");var Pt=e(xe,mt);if(te&&xe.indexOf(Pt)1||e(Me,Ze))throw new Y(D,"More than one element or text in fragment");if(ut.length===1&&!gt(z,te))throw new Y(D,"Element in fragment can not be inserted before doctype")}if(mt(V)&&!gt(z,te))throw new Y(D,"Only one element can be added and only after doctype");if(_t(V)){let Mi=function(Fi){return _t(Fi)&&Fi!==te};var Ii=Mi;if(e(xe,Mi))throw new Y(D,"Only one doctype is allowed");var Pt=e(xe,mt);if(te&&xe.indexOf(Pt)0&&ue(te.documentElement,function(Me){if(Me!==te&&Me.nodeType===p){var ut=Me.getAttribute("class");if(ut){var Pt=z===ut;if(!Pt){var Ii=a(ut);Pt=V.every(u(Ii))}Pt&&xe.push(Me)}}}),xe})},createElement:function(z){var V=new ve;V.ownerDocument=this,V.nodeName=z,V.tagName=z,V.localName=z,V.childNodes=new J;var te=V.attributes=new K;return te._ownerElement=V,V},createDocumentFragment:function(){var z=new Ut;return z.ownerDocument=this,z.childNodes=new J,z},createTextNode:function(z){var V=new st;return V.ownerDocument=this,V.appendData(z),V},createComment:function(z){var V=new ft;return V.ownerDocument=this,V.appendData(z),V},createCDATASection:function(z){var V=new yt;return V.ownerDocument=this,V.appendData(z),V},createProcessingInstruction:function(z,V){var te=new Ni;return te.ownerDocument=this,te.tagName=te.nodeName=te.target=z,te.nodeValue=te.data=V,te},createAttribute:function(z){var V=new dt;return V.ownerDocument=this,V.name=z,V.nodeName=z,V.localName=z,V.specified=!0,V},createEntityReference:function(z){var V=new Yt;return V.ownerDocument=this,V.nodeName=z,V},createElementNS:function(z,V){var te=new ve,xe=V.split(":"),Me=te.attributes=new K;return te.childNodes=new J,te.ownerDocument=this,te.nodeName=V,te.tagName=V,te.namespaceURI=z,xe.length==2?(te.prefix=xe[0],te.localName=xe[1]):te.localName=V,Me._ownerElement=te,te},createAttributeNS:function(z,V){var te=new dt,xe=V.split(":");return te.ownerDocument=this,te.nodeName=V,te.name=V,te.namespaceURI=z,te.specified=!0,xe.length==2?(te.prefix=xe[0],te.localName=xe[1]):te.localName=V,te}},d(he,P);function ve(){this._nsMap={}}ve.prototype={nodeType:p,hasAttribute:function(z){return this.getAttributeNode(z)!=null},getAttribute:function(z){var V=this.getAttributeNode(z);return V&&V.value||""},getAttributeNode:function(z){return this.attributes.getNamedItem(z)},setAttribute:function(z,V){var te=this.ownerDocument.createAttribute(z);te.value=te.nodeValue=""+V,this.setAttributeNode(te)},removeAttribute:function(z){var V=this.getAttributeNode(z);V&&this.removeAttributeNode(V)},appendChild:function(z){return z.nodeType===B?this.insertBefore(z,null):ht(this,z)},setAttributeNode:function(z){return this.attributes.setNamedItem(z)},setAttributeNodeNS:function(z){return this.attributes.setNamedItemNS(z)},removeAttributeNode:function(z){return this.attributes.removeNamedItem(z.nodeName)},removeAttributeNS:function(z,V){var te=this.getAttributeNodeNS(z,V);te&&this.removeAttributeNode(te)},hasAttributeNS:function(z,V){return this.getAttributeNodeNS(z,V)!=null},getAttributeNS:function(z,V){var te=this.getAttributeNodeNS(z,V);return te&&te.value||""},setAttributeNS:function(z,V,te){var xe=this.ownerDocument.createAttributeNS(z,V);xe.value=xe.nodeValue=""+te,this.setAttributeNode(xe)},getAttributeNodeNS:function(z,V){return this.attributes.getNamedItemNS(z,V)},getElementsByTagName:function(z){return new ae(this,function(V){var te=[];return ue(V,function(xe){xe!==V&&xe.nodeType==p&&(z==="*"||xe.tagName==z)&&te.push(xe)}),te})},getElementsByTagNameNS:function(z,V){return new ae(this,function(te){var xe=[];return ue(te,function(Me){Me!==te&&Me.nodeType===p&&(z==="*"||Me.namespaceURI===z)&&(V==="*"||Me.localName==V)&&xe.push(Me)}),xe})}},he.prototype.getElementsByTagName=ve.prototype.getElementsByTagName,he.prototype.getElementsByTagNameNS=ve.prototype.getElementsByTagNameNS,d(ve,P);function dt(){}dt.prototype.nodeType=y,d(dt,P);function qe(){}qe.prototype={data:"",substringData:function(z,V){return this.data.substring(z,z+V)},appendData:function(z){z=this.data+z,this.nodeValue=this.data=z,this.length=z.length},insertData:function(z,V){this.replaceData(z,0,V)},appendChild:function(z){throw new Error(G[D])},deleteData:function(z,V){this.replaceData(z,V,"")},replaceData:function(z,V,te){var xe=this.data.substring(0,z),Me=this.data.substring(z+V);te=xe+te+Me,this.nodeValue=this.data=te,this.length=te.length}},d(qe,P);function st(){}st.prototype={nodeName:"#text",nodeType:v,splitText:function(z){var V=this.data,te=V.substring(z);V=V.substring(0,z),this.data=this.nodeValue=V,this.length=V.length;var xe=this.ownerDocument.createTextNode(te);return this.parentNode&&this.parentNode.insertBefore(xe,this.nextSibling),xe}},d(st,qe);function ft(){}ft.prototype={nodeName:"#comment",nodeType:I},d(ft,qe);function yt(){}yt.prototype={nodeName:"#cdata-section",nodeType:b},d(yt,qe);function nt(){}nt.prototype.nodeType=$,d(nt,P);function jt(){}jt.prototype.nodeType=F,d(jt,P);function qt(){}qt.prototype.nodeType=S,d(qt,P);function Yt(){}Yt.prototype.nodeType=_,d(Yt,P);function Ut(){}Ut.prototype.nodeName="#document-fragment",Ut.prototype.nodeType=B,d(Ut,P);function Ni(){}Ni.prototype.nodeType=L,d(Ni,P);function rt(){}rt.prototype.serializeToString=function(z,V,te){return Dt.call(z,V,te)},P.prototype.toString=Dt;function Dt(z,V){var te=[],xe=this.nodeType==9&&this.documentElement||this,Me=xe.prefix,ut=xe.namespaceURI;if(ut&&Me==null){var Me=xe.lookupPrefix(ut);if(Me==null)var Pt=[{namespace:ut,prefix:null}]}return mi(this,te,z,V,Pt),te.join("")}function ii(z,V,te){var xe=z.prefix||"",Me=z.namespaceURI;if(!Me||xe==="xml"&&Me===t.XML||Me===t.XMLNS)return!1;for(var ut=te.length;ut--;){var Pt=te[ut];if(Pt.prefix===xe)return Pt.namespace!==Me}return!0}function ci(z,V,te){z.push(" ",V,'="',te.replace(/[<>&"\t\n\r]/g,Q),'"')}function mi(z,V,te,xe,Me){if(Me||(Me=[]),xe)if(z=xe(z),z){if(typeof z=="string"){V.push(z);return}}else return;switch(z.nodeType){case p:var ut=z.attributes,Pt=ut.length,Gt=z.firstChild,Ii=z.tagName;te=t.isHTML(z.namespaceURI)||te;var Mi=Ii;if(!te&&!z.prefix&&z.namespaceURI){for(var Fi,Ui=0;Ui=0;Wi--){var pi=Me[Wi];if(pi.prefix===""&&pi.namespace===z.namespaceURI){Fi=pi.namespace;break}}if(Fi!==z.namespaceURI)for(var Wi=Me.length-1;Wi>=0;Wi--){var pi=Me[Wi];if(pi.namespace===z.namespaceURI){pi.prefix&&(Mi=pi.prefix+":"+Ii);break}}}V.push("<",Mi);for(var os=0;os"),te&&/^script$/i.test(Ii))for(;Gt;)Gt.data?V.push(Gt.data):mi(Gt,V,te,xe,Me.slice()),Gt=Gt.nextSibling;else for(;Gt;)mi(Gt,V,te,xe,Me.slice()),Gt=Gt.nextSibling;V.push("")}else V.push("/>");return;case R:case B:for(var Gt=z.firstChild;Gt;)mi(Gt,V,te,xe,Me.slice()),Gt=Gt.nextSibling;return;case y:return ci(V,z.name,z.value);case v:return V.push(z.data.replace(/[<&>]/g,Q));case b:return V.push("");case I:return V.push("");case $:var Xt=z.publicId,ys=z.systemId;if(V.push("");else if(ys&&ys!=".")V.push(" SYSTEM ",ys,">");else{var ms=z.internalSubset;ms&&V.push(" [",ms,"]"),V.push(">")}return;case L:return V.push("");case _:return V.push("&",z.nodeName,";");default:V.push("??",z.nodeName)}}function Ht(z,V,te){var xe;switch(V.nodeType){case p:xe=V.cloneNode(!1),xe.ownerDocument=z;case B:break;case y:te=!0;break}if(xe||(xe=V.cloneNode(!1)),xe.ownerDocument=z,xe.parentNode=null,te)for(var Me=V.firstChild;Me;)xe.appendChild(Ht(z,Me,te)),Me=Me.nextSibling;return xe}function Oi(z,V,te){var xe=new V.constructor;for(var Me in V)if(Object.prototype.hasOwnProperty.call(V,Me)){var ut=V[Me];typeof ut!="object"&&ut!=xe[Me]&&(xe[Me]=ut)}switch(V.childNodes&&(xe.childNodes=new J),xe.ownerDocument=z,xe.nodeType){case p:var Pt=V.attributes,Ii=xe.attributes=new K,Mi=Pt.length;Ii._ownerElement=xe;for(var Fi=0;Fi",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})($y)),$y}var vm={},gE;function C3(){if(gE)return vm;gE=1;var s=Qp().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,a=2,u=3,c=4,d=5,f=6,p=7;function y(D,O){this.message=D,this.locator=O,Error.captureStackTrace&&Error.captureStackTrace(this,y)}y.prototype=new Error,y.prototype.name=y.name;function v(){}v.prototype={parse:function(D,O,W){var Y=this.domBuilder;Y.startDocument(),$(O,O={}),b(D,O,W,Y,this.errorHandler),Y.endDocument()}};function b(D,O,W,Y,J){function ae(ht){if(ht>65535){ht-=65536;var ve=55296+(ht>>10),dt=56320+(ht&1023);return String.fromCharCode(ve,dt)}else return String.fromCharCode(ht)}function se(ht){var ve=ht.slice(1,-1);return Object.hasOwnProperty.call(W,ve)?W[ve]:ve.charAt(0)==="#"?ae(parseInt(ve.substr(1).replace("x","0x"))):(J.error("entity not found:"+ht),ht)}function K(ht){if(ht>he){var ve=D.substring(he,ht).replace(/&#?\w+;/g,se);P&&X(he),Y.characters(ve,0,ht-he),he=ht}}function X(ht,ve){for(;ht>=le&&(ve=pe.exec(D));)ee=ve.index,le=ee+ve[0].length,P.lineNumber++;P.columnNumber=ht-ee+1}for(var ee=0,le=0,pe=/.*(?:\r\n?|\n)|.*$/g,P=Y.locator,Q=[{currentNSMap:O}],ue={},he=0;;){try{var re=D.indexOf("<",he);if(re<0){if(!D.substr(he).match(/^\s*$/)){var Pe=Y.doc,Ee=Pe.createTextNode(D.substr(he));Pe.appendChild(Ee),Y.currentElement=Ee}return}switch(re>he&&K(re),D.charAt(re+1)){case"/":var at=D.indexOf(">",re+3),Ge=D.substring(re+2,at).replace(/[ \t\n\r]+$/g,""),Ve=Q.pop();at<0?(Ge=D.substring(re+2).replace(/[\s<].*/,""),J.error("end tag name: "+Ge+" is not complete:"+Ve.tagName),at=re+1+Ge.length):Ge.match(/\she?he=at:K(Math.max(re,he)+1)}}function _(D,O){return O.lineNumber=D.lineNumber,O.columnNumber=D.columnNumber,O}function S(D,O,W,Y,J,ae){function se(P,Q,ue){W.attributeNames.hasOwnProperty(P)&&ae.fatalError("Attribute "+P+" redefined"),W.addValue(P,Q.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,J),ue)}for(var K,X,ee=++O,le=n;;){var pe=D.charAt(ee);switch(pe){case"=":if(le===r)K=D.slice(O,ee),le=u;else if(le===a)le=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(le===u||le===r)if(le===r&&(ae.warning('attribute value must after "="'),K=D.slice(O,ee)),O=ee+1,ee=D.indexOf(pe,O),ee>0)X=D.slice(O,ee),se(K,X,O-1),le=d;else throw new Error("attribute value no end '"+pe+"' match");else if(le==c)X=D.slice(O,ee),se(K,X,O),ae.warning('attribute "'+K+'" missed start quot('+pe+")!!"),O=ee+1,le=d;else throw new Error('attribute value must after "="');break;case"/":switch(le){case n:W.setTagName(D.slice(O,ee));case d:case f:case p:le=p,W.closed=!0;case c:case r:break;case a:W.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return ae.error("unexpected end of input"),le==n&&W.setTagName(D.slice(O,ee)),ee;case">":switch(le){case n:W.setTagName(D.slice(O,ee));case d:case f:case p:break;case c:case r:X=D.slice(O,ee),X.slice(-1)==="/"&&(W.closed=!0,X=X.slice(0,-1));case a:le===a&&(X=K),le==c?(ae.warning('attribute "'+X+'" missed quot(")!'),se(K,X,O)):((!s.isHTML(Y[""])||!X.match(/^(?:disabled|checked|selected)$/i))&&ae.warning('attribute "'+X+'" missed value!! "'+X+'" instead!!'),se(X,X,O));break;case u:throw new Error("attribute value missed!!")}return ee;case"€":pe=" ";default:if(pe<=" ")switch(le){case n:W.setTagName(D.slice(O,ee)),le=f;break;case r:K=D.slice(O,ee),le=a;break;case c:var X=D.slice(O,ee);ae.warning('attribute "'+X+'" missed quot(")!!'),se(K,X,O);case d:le=f;break}else switch(le){case a:W.tagName,(!s.isHTML(Y[""])||!K.match(/^(?:disabled|checked|selected)$/i))&&ae.warning('attribute "'+K+'" missed value!! "'+K+'" instead2!!'),se(K,K,O),O=ee,le=r;break;case d:ae.warning('attribute space is required"'+K+'"!!');case f:le=r,O=ee;break;case u:le=c,O=ee;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}ee++}}function L(D,O,W){for(var Y=D.tagName,J=null,pe=D.length;pe--;){var ae=D[pe],se=ae.qName,K=ae.value,P=se.indexOf(":");if(P>0)var X=ae.prefix=se.slice(0,P),ee=se.slice(P+1),le=X==="xmlns"&ⅇelse ee=se,X=null,le=se==="xmlns"&&"";ae.localName=ee,le!==!1&&(J==null&&(J={},$(W,W={})),W[le]=J[le]=K,ae.uri=s.XMLNS,O.startPrefixMapping(le,K))}for(var pe=D.length;pe--;){ae=D[pe];var X=ae.prefix;X&&(X==="xml"&&(ae.uri=s.XML),X!=="xmlns"&&(ae.uri=W[X||""]))}var P=Y.indexOf(":");P>0?(X=D.prefix=Y.slice(0,P),ee=D.localName=Y.slice(P+1)):(X=null,ee=D.localName=Y);var Q=D.uri=W[X||""];if(O.startElement(Q,ee,Y,D),D.closed){if(O.endElement(Q,ee,Y),J)for(X in J)Object.prototype.hasOwnProperty.call(J,X)&&O.endPrefixMapping(X)}else return D.currentNSMap=W,D.localNSMap=J,!0}function I(D,O,W,Y,J){if(/^(?:script|textarea)$/i.test(W)){var ae=D.indexOf("",O),se=D.substring(O+1,ae);if(/[&<]/.test(se))return/^script$/i.test(W)?(J.characters(se,0,se.length),ae):(se=se.replace(/&#?\w+;/g,Y),J.characters(se,0,se.length),ae)}return O+1}function R(D,O,W,Y){var J=Y[W];return J==null&&(J=D.lastIndexOf(""),J",O+4);return ae>O?(W.comment(D,O+4,ae-O-4),ae+3):(Y.error("Unclosed comment"),-1)}else return-1;default:if(D.substr(O+3,6)=="CDATA["){var ae=D.indexOf("]]>",O+9);return W.startCDATA(),W.characters(D,O+9,ae-O-9),W.endCDATA(),ae+3}var se=G(D,O),K=se.length;if(K>1&&/!doctype/i.test(se[0][0])){var X=se[1][0],ee=!1,le=!1;K>3&&(/^public$/i.test(se[2][0])?(ee=se[3][0],le=K>4&&se[4][0]):/^system$/i.test(se[2][0])&&(le=se[3][0]));var pe=se[K-1];return W.startDTD(X,ee,le),W.endDTD(),pe.index+pe[0].length}}return-1}function F(D,O,W){var Y=D.indexOf("?>",O);if(Y){var J=D.substring(O,Y).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return J?(J[0].length,W.processingInstruction(J[1],J[2]),Y+2):-1}return-1}function M(){this.attributeNames={}}M.prototype={setTagName:function(D){if(!i.test(D))throw new Error("invalid tagName:"+D);this.tagName=D},addValue:function(D,O,W){if(!i.test(D))throw new Error("invalid attribute:"+D);this.attributeNames[D]=this.length,this[this.length++]={qName:D,value:O,offset:W}},length:0,getLocalName:function(D){return this[D].localName},getLocator:function(D){return this[D].locator},getQName:function(D){return this[D].qName},getURI:function(D){return this[D].uri},getValue:function(D){return this[D].value}};function G(D,O){var W,Y=[],J=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(J.lastIndex=O,J.exec(D);W=J.exec(D);)if(Y.push(W),W[1])return Y}return vm.XMLReader=v,vm.ParseError=y,vm}var yE;function k3(){if(yE)return Xd;yE=1;var s=Qp(),e=WA(),t=A3(),i=C3(),n=e.DOMImplementation,r=s.NAMESPACE,a=i.ParseError,u=i.XMLReader;function c(S){return S.replace(/\r[\n\u0085]/g,` +`).replace(/[\r\u0085\u2028]/g,` +`)}function d(S){this.options=S||{locator:{}}}d.prototype.parseFromString=function(S,L){var I=this.options,R=new u,$=I.domBuilder||new p,B=I.errorHandler,F=I.locator,M=I.xmlns||{},G=/\/x?html?$/.test(L),D=G?t.HTML_ENTITIES:t.XML_ENTITIES;F&&$.setDocumentLocator(F),R.errorHandler=f(B,$,F),R.domBuilder=I.domBuilder||$,G&&(M[""]=r.HTML),M.xml=M.xml||r.XML;var O=I.normalizeLineEndings||c;return S&&typeof S=="string"?R.parse(O(S),M,D):R.errorHandler.error("invalid doc source"),$.doc};function f(S,L,I){if(!S){if(L instanceof p)return L;S=L}var R={},$=S instanceof Function;I=I||{};function B(F){var M=S[F];!M&&$&&(M=S.length==2?function(G){S(F,G)}:S),R[F]=M&&function(G){M("[xmldom "+F+"] "+G+v(I))}||function(){}}return B("warning"),B("error"),B("fatalError"),R}function p(){this.cdata=!1}function y(S,L){L.lineNumber=S.lineNumber,L.columnNumber=S.columnNumber}p.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(S,L,I,R){var $=this.doc,B=$.createElementNS(S,I||L),F=R.length;_(this,B),this.currentElement=B,this.locator&&y(this.locator,B);for(var M=0;M=L+I||L?new java.lang.String(S,L,I)+"":S}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(S){p.prototype[S]=function(){return null}});function _(S,L){S.currentElement?S.currentElement.appendChild(L):S.doc.appendChild(L)}return Xd.__DOMHandler=p,Xd.normalizeLineEndings=c,Xd.DOMParser=d,Xd}var vE;function D3(){if(vE)return Yd;vE=1;var s=WA();return Yd.DOMImplementation=s.DOMImplementation,Yd.XMLSerializer=s.XMLSerializer,Yd.DOMParser=k3().DOMParser,Yd}var L3=D3();const xE=s=>!!s&&typeof s=="object",gn=(...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]):xE(e[i])&&xE(t[i])?e[i]=gn(e[i],t[i]):e[i]=t[i]}),e),{}),YA=s=>Object.keys(s).map(e=>s[e]),R3=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),XA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),N3=(s,e)=>YA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var Oc={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 Ch=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:Xp(s||"",e)};if(t||i){const a=(t||i).split("-");let u=de.BigInt?de.BigInt(a[0]):parseInt(a[0],10),c=de.BigInt?de.BigInt(a[1]):parseInt(a[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=de.BigInt(s.offset)+de.BigInt(s.length)-de.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},bE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),M3={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=bE(s.endNumber),a=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/a}:{start:0,end:i/a}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:a=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=bE(s.endNumber),f=(e+t)/1e3,p=i+a,v=f+u-p,b=Math.ceil(v*n/r),_=Math.floor((f-p-c)*n/r),S=Math.floor((f-p)*n/r);return{start:Math.max(0,_),end:typeof d=="number"?d:Math.min(b,S)}}},P3=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}},ab=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:a,end:u}=M3[e](s),c=R3(a,u).map(P3(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},QA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:a,number:u=0,duration:c}=s;if(!e)throw new Error(Oc.NO_BASE_URL);const d=Ch({baseUrl:e,source:t.sourceURL,range:t.range}),f=Ch({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const p=ab(s);p.length&&(f.duration=p[0].duration,f.timeline=p[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=a||r,f.number=u,[f]},ob=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,a=s.sidx.byterange,u=a.offset+a.length,c=e.timescale,d=e.references.filter(S=>S.referenceType!==1),f=[],p=s.endList?"static":"dynamic",y=s.sidx.timeline;let v=y,b=s.mediaSequence||0,_;typeof e.firstOffset=="bigint"?_=de.BigInt(u)+e.firstOffset:_=u+e.firstOffset;for(let S=0;SN3(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),U3=(s,e)=>{for(let t=0;t{let e=[];return w3(s,B3,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},_E=({playlist:s,mediaSequence:e})=>{s.mediaSequence=e,s.segments.forEach((t,i)=>{t.number=s.mediaSequence+i})},j3=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=U3(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],a=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[a].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),_E({playlist:i,mediaSequence:n.segments[a].number})})},$3=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(TE(s)),i=e.playlists.concat(TE(e));return e.timelineStarts=ZA([s.timelineStarts,e.timelineStarts]),j3({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},Zp=s=>s&&s.uri+"-"+O3(s.byterange),Hy=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=YA(i.reduce((r,a)=>{const u=a.attributes.id+(a.attributes.lang||"");return r[u]?(a.segments&&(a.segments[0]&&(a.segments[0].discontinuity=!0),r[u].segments.push(...a.segments)),a.attributes.contentProtection&&(r[u].attributes.contentProtection=a.attributes.contentProtection)):(r[u]=a,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:a.attributes.periodStart,timeline:a.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=I3(i.segments||[],"discontinuity"),i))},lb=(s,e)=>{const t=Zp(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&ob(s,i,s.sidx.resolvedUri),s},H3=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=lb(s[t],e);return s},G3=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},a)=>{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),a&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},V3=({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 a={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&&(a.attributes.serviceLocation=s.serviceLocation),a},z3=(s,e={},t=!1)=>{let i;const n=s.reduce((r,a)=>{const u=a.attributes.role&&a.attributes.role.value||"",c=a.attributes.lang||"";let d=a.attributes.label||"main";if(c&&!a.attributes.label){const p=u?` (${u})`:"";d=`${a.attributes.lang}${p}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=lb(G3(a,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=a,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},q3=(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(lb(V3(i),e)),t},{}),K3=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),{}),W3=({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},Y3=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",X3=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",Q3=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",Z3=(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})})},SE=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],J3=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:a,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=Hy(s.filter(Y3)).map(W3),p=Hy(s.filter(X3)),y=Hy(s.filter(Q3)),v=s.map($=>$.attributes.captionServices).filter(Boolean),b={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:a,playlists:H3(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,S=p.length?z3(p,i,_):null,L=y.length?q3(y,i):null,I=f.concat(SE(S),SE(L)),R=I.map(({timelineStarts:$})=>$);return b.timelineStarts=ZA(R),Z3(I,b.timelineStarts),S&&(b.mediaGroups.AUDIO.audio=S),L&&(b.mediaGroups.SUBTITLES.subs=L),v.length&&(b.mediaGroups["CLOSED-CAPTIONS"].cc=K3(v)),n?$3({oldManifest:n,newManifest:b}):b},eP=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:a=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,y=d+c-f;return Math.ceil((y*a-e)/t)},JA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:a=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let p=0;pf&&(f=_);let S;if(b<0){const R=p+1;R===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?S=eP(s,f,v):S=(r*a-f)/v:S=(e[R].t-f)/v}else S=b+1;const L=u+d.length+S;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}`},EE=(s,e)=>s.replace(tP,iP(e)),sP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?ab(s):JA(s,e),nP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=Ch({baseUrl:s.baseUrl,source:EE(i.sourceURL,t),range:i.range});return sP(s,e).map(a=>{t.Number=a.number,t.Time=a.time;const u=EE(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(a.time-d)/c;return{uri:u,timeline:a.timeline,duration:a.duration,resolvedUri:Xp(s.baseUrl||"",u),map:n,number:a.number,presentationTime:f}})},rP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=Ch({baseUrl:t,source:i.sourceURL,range:i.range}),r=Ch({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},aP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(Oc.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>rP(s,c));let a;return t&&(a=ab(s)),e&&(a=JA(s,e)),a.map((c,d)=>{if(r[d]){const f=r[d],p=s.timescale||1,y=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-y)/p,f}}).filter(c=>c)},oP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=nP,t=gn(s,e.template)):e.base?(i=QA,t=gn(s,e.base)):e.list&&(i=aP,t=gn(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:a,timescale:u=1}=t;t.duration=a/u}else r.length?t.duration=r.reduce((a,u)=>Math.max(a,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},lP=s=>s.map(oP),ws=(s,e)=>XA(s.childNodes).filter(({tagName:t})=>t===e),Hh=s=>s.textContent.trim(),uP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),Xu=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,y,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(p||0)*3600+parseFloat(y||0)*60+parseFloat(v||0)},cP=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),wE={mediaPresentationDuration(s){return Xu(s)},availabilityStartTime(s){return cP(s)/1e3},minimumUpdatePeriod(s){return Xu(s)},suggestedPresentationDelay(s){return Xu(s)},type(s){return s},timeShiftBufferDepth(s){return Xu(s)},start(s){return Xu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return uP(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)?Xu(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}},en=s=>s&&s.attributes?XA(s.attributes).reduce((e,t)=>{const i=wE[t.name]||wE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},dP={"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"},Jp=(s,e)=>e.length?Nc(s.map(function(t){return e.map(function(i){const n=Hh(i),r=Xp(t.baseUrl,n),a=gn(en(i),{baseUrl:r});return r!==n&&!a.serviceLocation&&t.serviceLocation&&(a.serviceLocation=t.serviceLocation),a})})):s,ub=s=>{const e=ws(s,"SegmentTemplate")[0],t=ws(s,"SegmentList")[0],i=t&&ws(t,"SegmentURL").map(p=>gn({tag:"SegmentURL"},en(p))),n=ws(s,"SegmentBase")[0],r=t||e,a=r&&ws(r,"SegmentTimeline")[0],u=t||n||e,c=u&&ws(u,"Initialization")[0],d=e&&en(e);d&&c?d.initialization=c&&en(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:a&&ws(a,"S").map(p=>en(p)),list:t&&gn(en(t),{segmentUrls:i,initialization:en(c)}),base:n&&gn(en(n),{initialization:en(c)})};return Object.keys(f).forEach(p=>{f[p]||delete f[p]}),f},hP=(s,e,t)=>i=>{const n=ws(i,"BaseURL"),r=Jp(e,n),a=gn(s,en(i)),u=ub(i);return r.map(c=>({segmentInfo:gn(t,u),attributes:gn(a,c)}))},fP=s=>s.reduce((e,t)=>{const i=en(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=dP[i.schemeIdUri];if(n){e[n]={attributes:i};const r=ws(t,"cenc:pssh")[0];if(r){const a=Hh(r);e[n].pssh=a&&HA(a)}}return e},{}),mP=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(a=>{const[u,c]=a.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})},pP=s=>Nc(ws(s.node,"EventStream").map(e=>{const t=en(e),i=t.schemeIdUri;return ws(e,"Event").map(n=>{const r=en(n),a=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=a/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:Hh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),gP=(s,e,t)=>i=>{const n=en(i),r=Jp(e,ws(i,"BaseURL")),a=ws(i,"Role")[0],u={role:en(a)};let c=gn(s,n,u);const d=ws(i,"Accessibility")[0],f=mP(en(d));f&&(c=gn(c,{captionServices:f}));const p=ws(i,"Label")[0];if(p&&p.childNodes.length){const S=p.childNodes[0].nodeValue.trim();c=gn(c,{label:S})}const y=fP(ws(i,"ContentProtection"));Object.keys(y).length&&(c=gn(c,{contentProtection:y}));const v=ub(i),b=ws(i,"Representation"),_=gn(t,v);return Nc(b.map(hP(c,r,_)))},yP=(s,e)=>(t,i)=>{const n=Jp(e,ws(t.node,"BaseURL")),r=gn(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const a=ws(t.node,"AdaptationSet"),u=ub(t.node);return Nc(a.map(gP(r,n,u)))},vP=(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=gn({serverURL:Hh(s[0])},en(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},xP=({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,bP=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,a=ws(s,"Period");if(!a.length)throw new Error(Oc.INVALID_NUMBER_OF_PERIOD);const u=ws(s,"Location"),c=en(s),d=Jp([{baseUrl:t}],ws(s,"BaseURL")),f=ws(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(Hh));const p=[];return a.forEach((y,v)=>{const b=en(y),_=p[v-1];b.start=xP({attributes:b,priorPeriodAttributes:_?_.attributes:null,mpdType:c.type}),p.push({node:y,attributes:b})}),{locations:c.locations,contentSteeringInfo:vP(f,r),representationInfo:Nc(p.map(yP(c,d))),eventStream:Nc(p.map(pP))}},eC=s=>{if(s==="")throw new Error(Oc.DASH_EMPTY_MANIFEST);const e=new L3.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(Oc.DASH_INVALID_XML);return i},TP=s=>{const e=ws(s,"UTCTiming")[0];if(!e)return null;const t=en(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(Oc.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},_P=(s,e={})=>{const t=bP(eC(s),e),i=lP(t.representationInfo);return J3({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},SP=s=>TP(eC(s));var Gy,AE;function EP(){if(AE)return Gy;AE=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,a--)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 Vy=e,Vy}var AP=wP();const CP=Vc(AP);var kP=Wt([73,68,51]),DP=function(e,t){t===void 0&&(t=0),e=Wt(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},oh=function s(e,t){return t===void 0&&(t=0),e=Wt(e),e.length-t<10||!Es(e,kP,{offset:t})?t:(t+=DP(e,t),s(e,t))},kE=function(e){return typeof e=="string"?KA(e):e},LP=function(e){return Array.isArray(e)?e.map(function(t){return kE(t)}):[kE(e)]},RP=function s(e,t,i){i===void 0&&(i=!1),t=LP(t),e=Wt(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(a===0)break;var c=r+a;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);Es(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},xm={EBML:Wt([26,69,223,163]),DocType:Wt([66,130]),Segment:Wt([24,83,128,103]),SegmentInfo:Wt([21,73,169,102]),Tracks:Wt([22,84,174,107]),Track:Wt([174]),TrackNumber:Wt([215]),DefaultDuration:Wt([35,227,131]),TrackEntry:Wt([174]),TrackType:Wt([131]),FlagDefault:Wt([136]),CodecID:Wt([134]),CodecPrivate:Wt([99,162]),VideoTrack:Wt([224]),AudioTrack:Wt([225]),Cluster:Wt([31,67,182,117]),Timestamp:Wt([231]),TimestampScale:Wt([42,215,177]),BlockGroup:Wt([160]),BlockDuration:Wt([155]),Block:Wt([161]),SimpleBlock:Wt([163])},sx=[128,64,32,16,8,4,2,1],IP=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=op(t,i,!1);if(Es(e.bytes,n.bytes))return i;var r=op(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},LE=function s(e,t){t=NP(t),e=Wt(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+a.value,d=e.subarray(u,c);Es(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+a.length+d.length;n+=f}return i},MP=Wt([0,0,0,1]),PP=Wt([0,0,1]),BP=Wt([0,0,3]),FP=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(a=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},UP=function(e,t,i){return tC(e,"h264",t,i)},jP=function(e,t,i){return tC(e,"h265",t,i)},Hn={webm:Wt([119,101,98,109]),matroska:Wt([109,97,116,114,111,115,107,97]),flac:Wt([102,76,97,67]),ogg:Wt([79,103,103,83]),ac3:Wt([11,119]),riff:Wt([82,73,70,70]),avi:Wt([65,86,73]),wav:Wt([87,65,86,69]),"3gp":Wt([102,116,121,112,51,103]),mp4:Wt([102,116,121,112]),fmp4:Wt([115,116,121,112]),mov:Wt([102,116,121,112,113,116]),moov:Wt([109,111,111,118]),moof:Wt([109,111,111,102])},Mc={aac:function(e){var t=oh(e);return Es(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=oh(e);return Es(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=LE(e,[xm.EBML,xm.DocType])[0];return Es(t,Hn.webm)},mkv:function(e){var t=LE(e,[xm.EBML,xm.DocType])[0];return Es(t,Hn.matroska)},mp4:function(e){if(Mc["3gp"](e)||Mc.mov(e))return!1;if(Es(e,Hn.mp4,{offset:4})||Es(e,Hn.fmp4,{offset:4})||Es(e,Hn.moof,{offset:4})||Es(e,Hn.moov,{offset:4}))return!0},mov:function(e){return Es(e,Hn.mov,{offset:4})},"3gp":function(e){return Es(e,Hn["3gp"],{offset:4})},ac3:function(e){var t=oh(e);return Es(e,Hn.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},zy,RE;function GP(){if(RE)return zy;RE=1;var s=9e4,e,t,i,n,r,a,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))},a=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},zy={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:a,metadataTsToSeconds:u},zy}var lu=GP();var rx="8.23.4";const bo={},El=function(s,e){return bo[s]=bo[s]||[],e&&(bo[s]=bo[s].concat(e)),bo[s]},VP=function(s,e){El(s,e)},iC=function(s,e){const t=El(s).indexOf(e);return t<=-1?!1:(bo[s]=bo[s].slice(),bo[s].splice(t,1),!0)},zP=function(s,e){El(s,[].concat(e).map(t=>{const i=(...n)=>(iC(s,i),t(...n));return i}))},lp={prefixed:!0},Gm=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],IE=Gm[0];let lh;for(let s=0;s(i,n,r)=>{const a=e.levels[n],u=new RegExp(`^(${a})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),lr){lr.push([].concat(r));const f=lr.length-1e3;lr.splice(0,f>0?f:0)}if(!de.console)return;let d=de.console[i];!d&&i==="debug"&&(d=de.console.info||de.console.log),!(!d||!a||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](de.console,r)};function ax(s,e=":",t=""){let i="info",n;function r(...a){n("log",i,a)}return n=qP(s,r,t),r.createLogger=(a,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,p=`${s} ${d} ${a}`;return ax(p,d,f)},r.createNewLogger=(a,u,c)=>ax(a,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=a=>{if(typeof a=="string"){if(!r.levels.hasOwnProperty(a))throw new Error(`"${a}" in not a valid log level`);i=a}return i},r.history=()=>lr?[].concat(lr):[],r.history.filter=a=>(lr||[]).filter(u=>new RegExp(`.*${a}.*`).test(u[0])),r.history.clear=()=>{lr&&(lr.length=0)},r.history.disable=()=>{lr!==null&&(lr.length=0,lr=null)},r.history.enable=()=>{lr===null&&(lr=[])},r.error=(...a)=>n("error",i,a),r.warn=(...a)=>n("warn",i,a),r.debug=(...a)=>n("debug",i,a),r}const vi=ax("VIDEOJS"),sC=vi.createLogger,KP=Object.prototype.toString,nC=function(s){return $a(s)?Object.keys(s):[]};function pc(s,e){nC(s).forEach(t=>e(s[t],t))}function rC(s,e,t=0){return nC(s).reduce((i,n)=>e(i,s[n],n),t)}function $a(s){return!!s&&typeof s=="object"}function Pc(s){return $a(s)&&KP.call(s)==="[object Object]"&&s.constructor===Object}function rs(...s){const e={};return s.forEach(t=>{t&&pc(t,(i,n)=>{if(!Pc(i)){e[n]=i;return}Pc(e[n])||(e[n]={}),e[n]=rs(e[n],i)})}),e}function aC(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function e0(s,e,t,i=!0){const n=a=>Object.defineProperty(s,e,{value:a,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const a=t();return n(a),a}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var WP=Object.freeze({__proto__:null,each:pc,reduce:rC,isObject:$a,isPlain:Pc,merge:rs,values:aC,defineLazyProperty:e0});let db=!1,oC=null,la=!1,lC,uC=!1,gc=!1,yc=!1,Ha=!1,hb=null,t0=null;const YP=!!(de.cast&&de.cast.framework&&de.cast.framework.CastReceiverContext);let cC=null,up=!1,i0=!1,cp=!1,s0=!1,dp=!1,hp=!1,fp=!1;const kh=!!(zc()&&("ontouchstart"in de||de.navigator.maxTouchPoints||de.DocumentTouch&&de.document instanceof de.DocumentTouch)),ul=de.navigator&&de.navigator.userAgentData;ul&&ul.platform&&ul.brands&&(la=ul.platform==="Android",gc=!!ul.brands.find(s=>s.brand==="Microsoft Edge"),yc=!!ul.brands.find(s=>s.brand==="Chromium"),Ha=!gc&&yc,hb=t0=(ul.brands.find(s=>s.brand==="Chromium")||{}).version||null,i0=ul.platform==="Windows");if(!yc){const s=de.navigator&&de.navigator.userAgent||"";db=/iPod/i.test(s),oC=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),la=/Android/i.test(s),lC=(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})(),uC=/Firefox/i.test(s),gc=/Edg/i.test(s),yc=/Chrome/i.test(s)||/CriOS/i.test(s),Ha=!gc&&yc,hb=t0=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),cC=(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})(),dp=/Tizen/i.test(s),hp=/Web0S/i.test(s),fp=dp||hp,up=/Safari/i.test(s)&&!Ha&&!la&&!gc&&!fp,i0=/Windows/i.test(s),cp=/iPad/i.test(s)||up&&kh&&!/iPhone/i.test(s),s0=/iPhone/i.test(s)&&!cp}const In=s0||cp||db,n0=(up||In)&&!Ha;var dC=Object.freeze({__proto__:null,get IS_IPOD(){return db},get IOS_VERSION(){return oC},get IS_ANDROID(){return la},get ANDROID_VERSION(){return lC},get IS_FIREFOX(){return uC},get IS_EDGE(){return gc},get IS_CHROMIUM(){return yc},get IS_CHROME(){return Ha},get CHROMIUM_VERSION(){return hb},get CHROME_VERSION(){return t0},IS_CHROMECAST_RECEIVER:YP,get IE_VERSION(){return cC},get IS_SAFARI(){return up},get IS_WINDOWS(){return i0},get IS_IPAD(){return cp},get IS_IPHONE(){return s0},get IS_TIZEN(){return dp},get IS_WEBOS(){return hp},get IS_SMART_TV(){return fp},TOUCH_ENABLED:kh,IS_IOS:In,IS_ANY_SAFARI:n0});function NE(s){return typeof s=="string"&&!!s.trim()}function XP(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function zc(){return pt===de.document}function qc(s){return $a(s)&&s.nodeType===1}function hC(){try{return de.parent!==de.self}catch{return!0}}function fC(s){return function(e,t){if(!NE(e))return pt[s](null);NE(t)&&(t=pt.querySelector(t));const i=qc(t)?t:pt;return i[s]&&i[s](e)}}function ei(s="div",e={},t={},i){const n=pt.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const a=e[r];r==="textContent"?kl(n,a):(n[r]!==a||r==="tabIndex")&&(n[r]=a)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&fb(n,i),n}function kl(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function ox(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function yh(s,e){return XP(e),s.classList.contains(e)}function du(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function r0(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(vi.warn("removeClass was called with an element that doesn't exist"),null)}function mC(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 pC(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 pl(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 a=i[n].value;t.includes(r)&&(a=a!==null),e[r]=a}}return e}function gC(s,e){return s.getAttribute(e)}function Bc(s,e,t){s.setAttribute(e,t)}function a0(s,e){s.removeAttribute(e)}function yC(){pt.body.focus(),pt.onselectstart=function(){return!1}}function vC(){pt.onselectstart=function(){return!0}}function Fc(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(Uc(s,"height"))),t.width||(t.width=parseFloat(Uc(s,"width"))),t}}function Dh(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!==pt[lp.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function o0(s,e){const t={x:0,y:0};if(In){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const p=Uc(f,"transform");if(/^matrix/.test(p)){const y=p.slice(7,-1).split(/,\s/).map(Number);t.x+=y[4],t.y+=y[5]}else if(/^matrix3d/.test(p)){const y=p.slice(9,-1).split(/,\s/).map(Number);t.x+=y[12],t.y+=y[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&de.WebKitCSSMatrix){const y=de.getComputedStyle(f.assignedSlot.parentElement).transform,v=new de.WebKitCSSMatrix(y);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=Dh(e.target),r=Dh(s),a=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,In&&(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/a)),i}function xC(s){return $a(s)&&s.nodeType===3}function l0(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function bC(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),qc(e)||xC(e))return e;if(typeof e=="string"&&/\S/.test(e))return pt.createTextNode(e)}).filter(e=>e)}function fb(s,e){return bC(e).forEach(t=>s.appendChild(t)),s}function TC(s,e){return fb(l0(s),e)}function Lh(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 wl=fC("querySelector"),_C=fC("querySelectorAll");function Uc(s,e){if(!s||!e)return"";if(typeof de.getComputedStyle=="function"){let t;try{t=de.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function SC(s){[...pt.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=pt.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=pt.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var EC=Object.freeze({__proto__:null,isReal:zc,isEl:qc,isInFrame:hC,createEl:ei,textContent:kl,prependTo:ox,hasClass:yh,addClass:du,removeClass:r0,toggleClass:mC,setAttributes:pC,getAttributes:pl,getAttribute:gC,setAttribute:Bc,removeAttribute:a0,blockTextSelection:yC,unblockTextSelection:vC,getBoundingClientRect:Fc,findPosition:Dh,getPointerPosition:o0,isTextNode:xC,emptyEl:l0,normalizeContent:bC,appendContent:fb,insertContent:TC,isSingleLeftClick:Lh,$:wl,$$:_C,computedStyle:Uc,copyStyleSheetsToWindow:SC});let wC=!1,lx;const QP=function(){if(lx.options.autoSetup===!1)return;const s=Array.prototype.slice.call(pt.getElementsByTagName("video")),e=Array.prototype.slice.call(pt.getElementsByTagName("audio")),t=Array.prototype.slice.call(pt.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 Nn(s,e,t){if(!zn.has(s))return;const i=zn.get(s);if(!i.handlers)return;if(Array.isArray(e))return mb(Nn,s,e,t);const n=function(a,u){i.handlers[u]=[],OE(a,u)};if(e===void 0){for(const a in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},a)&&n(s,a);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let a=0;a=e&&(s(...n),t=r)}},kC=function(s,e,t,i=de){let n;const r=()=>{i.clearTimeout(n),n=null},a=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 a.cancel=r,a};var s4=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:qr,bind_:gs,throttle:Ga,debounce:kC});let Qd;class Nr{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Ir(this,e,t),this.addEventListener=i}off(e,t){Nn(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},c0(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},pb(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=u0(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Kc(this,e)}queueTrigger(e){Qd||(Qd=new Map);const t=e.type||e;let i=Qd.get(this);i||(i=new Map,Qd.set(this,i));const n=i.get(t);i.delete(t),de.clearTimeout(n);const r=de.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,Qd.delete(this)),this.trigger(e)},0);i.set(t,r)}}Nr.prototype.allowedEvents_={};Nr.prototype.addEventListener=Nr.prototype.on;Nr.prototype.removeEventListener=Nr.prototype.off;Nr.prototype.dispatchEvent=Nr.prototype.trigger;const d0=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,Eo=s=>s instanceof Nr||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),n4=(s,e)=>{Eo(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},dx=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,mp=(s,e,t)=>{if(!s||!s.nodeName&&!Eo(s))throw new Error(`Invalid target for ${d0(e)}#${t}; must be a DOM node or evented object.`)},DC=(s,e,t)=>{if(!dx(s))throw new Error(`Invalid event type for ${d0(e)}#${t}; must be a non-empty string or array.`)},LC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${d0(e)}#${t}; must be a function.`)},qy=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,a;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,a]=e):(n=e[0],r=e[1],a=e[2]),mp(n,s,t),DC(r,s,t),LC(a,s,t),a=gs(s,a),{isTargetingSelf:i,target:n,type:r,listener:a}},Ql=(s,e,t,i)=>{mp(s,s,e),s.nodeName?i4[e](s,t,i):s[e](t,i)},r4={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=qy(this,s,"on");if(Ql(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const a=()=>this.off("dispose",r);a.guid=n.guid,Ql(this,"on","dispose",r),Ql(t,"on","dispose",a)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=qy(this,s,"one");if(e)Ql(t,"one",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,Ql(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=qy(this,s,"any");if(e)Ql(t,"any",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,Ql(t,"any",i,r)}},off(s,e,t){if(!s||dx(s))Nn(this.eventBusEl_,s,e);else{const i=s,n=e;mp(i,this,"off"),DC(n,this,"off"),LC(t,this,"off"),t=gs(this,t),this.off("dispose",t),i.nodeName?(Nn(i,n,t),Nn(i,"dispose",t)):Eo(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){mp(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!dx(t))throw new Error(`Invalid event type for ${d0(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Kc(this.eventBusEl_,s,e)}};function gb(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_=ei("span",{className:"vjs-event-bus"});return Object.assign(s,r4),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&zn.has(i)&&zn.delete(i)}),de.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const a4={state:{},setState(s){typeof s=="function"&&(s=s());let e;return pc(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&Eo(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function RC(s,e){return Object.assign(s,a4),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&Eo(s)&&s.on("statechanged",s.handleStateChanged),s}const vh=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},Fs=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},IC=function(s,e){return Fs(s)===Fs(e)};var o4=Object.freeze({__proto__:null,toLowerCase:vh,toTitleCase:Fs,titleCaseEquals:IC});class ze{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=rs({},this.options_),t=this.options_=rs(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_${zr()}`}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&&(gb(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),RC(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_=rs(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return ei(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),a=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return a&&a[e]?d=a[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,p){const y=t[p-1];let v=y;return typeof y>"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_[Fs(e.name())]=null,this.childNameIndex_[vh(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=a=>{const u=a.name;let c=a.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=ze.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(a){return!n.some(function(u){return typeof u=="string"?a===u:a===u.name})})).map(a=>{let u,c;return typeof a=="string"?(u=a,c=e[u]||this.options_[u]||{}):(u=a.name,c=a),{name:u,opts:c}}).filter(a=>{const u=ze.getComponent(a.opts.componentClass||Fs(a.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 wl(e,t||this.contentEl())}$$(e,t){return _C(e,t||this.contentEl())}hasClass(e){return yh(this.el_,e)}addClass(...e){du(this.el_,...e)}removeClass(...e){r0(this.el_,...e)}toggleClass(e,t){mC(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 gC(this.el_,e)}setAttribute(e,t){Bc(this.el_,e,t)}removeAttribute(e){a0(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"+Fs(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Uc(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${Fs(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=de.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 a=function(){r=!1};this.on("touchleave",a),this.on("touchcancel",a),this.on("touchend",function(u){t=null,r===!0&&de.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),de.clearTimeout(e)),e}setInterval(e,t){e=gs(this,e),this.clearTimersOnDispose_();const i=de.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),de.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=gs(this,e),t=de.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=gs(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),de.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 a=de.getComputedStyle(r,null),u=a.getPropertyValue("visibility");return a.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||de.getComputedStyle(r).height==="0px"||de.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const a={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(a.x<0||a.x>(pt.documentElement.clientWidth||de.innerWidth)||a.y<0||a.y>(pt.documentElement.clientHeight||de.innerHeight))return!1;let u=pt.elementFromPoint(a.x,a.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=ze.getComponent("Tech"),n=i&&i.isTech(t),r=ze===t||ze.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=Fs(e),ze.components_||(ze.components_={});const a=ze.getComponent("Player");if(e==="Player"&&a&&a.players){const u=a.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 ME(s,e,t,i){return l4(s,i,t.length-1),t[i][e]}function Ky(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:ME.bind(null,"start",0,s),end:ME.bind(null,"end",1,s)},de.Symbol&&de.Symbol.iterator&&(e[de.Symbol.iterator]=()=>(s||[]).values()),e}function oa(s,e){return Array.isArray(s)?Ky(s):s===void 0||e===void 0?Ky():Ky([[s,e]])}const NC=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),a=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||a>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let yb=NC;function OC(s){yb=s}function MC(){yb=NC}function yu(s,e=s){return yb(s,e)}var u4=Object.freeze({__proto__:null,createTimeRanges:oa,createTimeRange:oa,setFormatTime:OC,resetFormatTime:MC,formatTime:yu});function PC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=oa(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function Rs(s){if(s instanceof Rs)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:$a(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=Rs.defaultMessages[this.code]||"")}Rs.prototype.code=0;Rs.prototype.message="";Rs.prototype.status=null;Rs.prototype.metadata=null;Rs.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];Rs.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."};Rs.MEDIA_ERR_CUSTOM=0;Rs.prototype.MEDIA_ERR_CUSTOM=0;Rs.MEDIA_ERR_ABORTED=1;Rs.prototype.MEDIA_ERR_ABORTED=1;Rs.MEDIA_ERR_NETWORK=2;Rs.prototype.MEDIA_ERR_NETWORK=2;Rs.MEDIA_ERR_DECODE=3;Rs.prototype.MEDIA_ERR_DECODE=3;Rs.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Rs.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Rs.MEDIA_ERR_ENCRYPTED=5;Rs.prototype.MEDIA_ERR_ENCRYPTED=5;function xh(s){return s!=null&&typeof s.then=="function"}function Ia(s){xh(s)&&s.then(null,e=>{})}const hx=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}})})},c4=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=hx(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(hx))},d4=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 fx={textTracksToJson:c4,jsonToTextTracks:d4,trackToJson:hx};const Wy="vjs-modal-dialog";class Wc extends ze{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_=ei("div",{className:`${Wy}-content`},{role:"document"}),this.descEl_=ei("p",{className:`${Wy}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),kl(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`${Wy} 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(),TC(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"),l0(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=pt.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 de.HTMLAnchorElement||t instanceof de.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof de.HTMLInputElement||t instanceof de.HTMLSelectElement||t instanceof de.HTMLTextAreaElement||t instanceof de.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof de.HTMLIFrameElement||t instanceof de.HTMLObjectElement||t instanceof de.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Wc.prototype.options_={pauseOnOpen:!0,temporary:!0};ze.registerComponent("ModalDialog",Wc);class vu extends Nr{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})},Eo(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){Yy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&Yy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,Yy(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 Xy=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){Xy(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,Xy(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 vb extends vu{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 h4{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(de.console&&de.console.groupCollapsed&&de.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>vi.error(n)),de.console&&de.console.groupEnd&&de.console.groupEnd()),t.flush()},FE=function(s,e){const t={uri:s},i=h0(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),$A(t,gs(this,function(r,a,u){if(r)return vi.error(r,a);e.loaded_=!0,typeof de.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){vi.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return BE(u,e)}):BE(u,e)}))};class Gh extends xb{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=rs(e,{kind:p4[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=PE[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 pp(this.cues_),a=new pp(this.activeCues_);let u=!1;this.timeupdateHandler=gs(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){PE[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&FE(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 a;const d=this.tech_.currentTime(),f=[];for(let p=0,y=this.cues.length;p=d&&f.push(v)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let p=0;p{t=Ao.LOADED,this.trigger({type:"load",target:this})})}}Ao.prototype.allowedEvents_={load:"load"};Ao.NONE=0;Ao.LOADING=1;Ao.LOADED=2;Ao.ERROR=3;const Vr={audio:{ListClass:BC,TrackClass:jC,capitalName:"Audio"},video:{ListClass:FC,TrackClass:$C,capitalName:"Video"},text:{ListClass:vb,TrackClass:Gh,capitalName:"Text"}};Object.keys(Vr).forEach(function(s){Vr[s].getterName=`${s}Tracks`,Vr[s].privateName=`${s}Tracks_`});const jc={remoteText:{ListClass:vb,TrackClass:Gh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:h4,TrackClass:Ao,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Vn=Object.assign({},Vr,jc);jc.names=Object.keys(jc);Vr.names=Object.keys(Vr);Vn.names=[].concat(jc.names).concat(Vr.names);function y4(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const a=new Vn.text.TrackClass(n);return r.addTrack(a),a}class ui extends ze{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}),Vn.names.forEach(i=>{const n=Vn[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 Vn.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(gs(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 oa(0,0)}bufferedPercent(){return PC(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(Vr.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 Rs(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?oa(0,0):oa()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){Vr.names.forEach(e=>{const t=Vr[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(!de.WebVTT)if(pt.body.contains(this.el())){if(!this.options_["vtt.js"]&&Pc(lE)&&Object.keys(lE).length>0){this.trigger("vttjsloaded");return}const e=pt.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}),de.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"),a=()=>{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=zr();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 ui.canPlayType(e.type)}static isTech(e){return e.prototype instanceof ui||e instanceof ui||e===ui}static registerTech(e,t){if(ui.techs_||(ui.techs_={}),!ui.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!ui.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!ui.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=Fs(e),ui.techs_[e]=t,ui.techs_[vh(e)]=t,e!=="Tech"&&ui.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(ui.techs_&&ui.techs_[e])return ui.techs_[e];if(e=Fs(e),de&&de.videojs&&de.videojs[e])return vi.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),de.videojs[e]}}}Vn.names.forEach(function(s){const e=Vn[s];ui.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});ui.prototype.featuresVolumeControl=!0;ui.prototype.featuresMuteControl=!0;ui.prototype.featuresFullscreenResize=!1;ui.prototype.featuresPlaybackRate=!1;ui.prototype.featuresProgressEvents=!1;ui.prototype.featuresSourceset=!1;ui.prototype.featuresTimeupdateEvents=!1;ui.prototype.featuresNativeTextTracks=!1;ui.prototype.featuresVideoFrameCallback=!1;ui.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;riu(e,hu[e.type],t,s),1)}function b4(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function T4(s,e,t){return s.reduceRight(_b(t),e[t]())}function _4(s,e,t,i){return e[t](s.reduce(_b(t),i))}function UE(s,e,t,i=null){const n="call"+Fs(t),r=s.reduce(_b(n),i),a=r===yp,u=a?null:e[t](r);return w4(s,t,u,a),u}const S4={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},E4={setCurrentTime:1,setMuted:1,setVolume:1},jE={play:1,pause:1};function _b(s){return(e,t)=>e===yp?yp:t[s]?t[s](e):e}function w4(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function A4(s){gp.hasOwnProperty(s.id())&&delete gp[s.id()]}function C4(s,e){const t=gp[s.id()];let i=null;if(t==null)return i=e(s),gp[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 HE=dp?10009:hp?461:8,Qu={codes:{play:415,pause:19,ff:417,rw:412,back:HE},names:{415:"play",19:"pause",417:"ff",412:"rw",[HE]:"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}},GE=5;class R4 extends Nr{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(Qu.isEventKey(t,"play")||Qu.isEventKey(t,"pause")||Qu.isEventKey(t,"ff")||Qu.isEventKey(t,"rw")){t.preventDefault();const i=Qu.getEventName(t);this.performMediaAction_(i)}else Qu.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()+GE);break;case"rw":this.userSeek_(this.player_.currentTime()-GE);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(a=>a!==t&&this.isInDirection_(i.boundingClientRect,a.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 a of t){const u=a.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"&&vi.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=ei(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(ei("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=ei("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,kl(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)}}ze.registerComponent("ClickableComponent",f0);class mx extends f0{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 ei("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(ei("picture",{className:"vjs-poster",tabIndex:-1},{},ei("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()?Ia(this.player_.play()):this.player_.pause())}}mx.prototype.crossorigin=mx.prototype.crossOrigin;ze.registerComponent("PosterImage",mx);const Hr="#222",VE="#ccc",N4={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 Qy(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 Ea(s,e,t){try{s.style[e]=t}catch{return}}function zE(s){return s?`${s}px`:""}class O4 extends ze{constructor(e,t,i){super(e,t,i);const n=a=>this.updateDisplay(a),r=a=>{this.updateDisplayOverlay(),this.updateDisplay(a)};e.on("loadstart",a=>this.toggleDisplay(a)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",a=>{this.updateDisplayOverlay(),this.preselectTrack(a)}),e.ready(gs(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const a=de.screen.orientation||de,u=de.screen.orientation?"change":"orientationchange";a.addEventListener(u,r),e.on("dispose",()=>a.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()||!de.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,a=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):a=Math.round((t-e/n)/2)),Ea(this.el_,"insetInline",zE(r)),Ea(this.el_,"insetBlock",zE(a))}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 a=r.displayState;if(t.color&&(a.firstChild.style.color=t.color),t.textOpacity&&Ea(a.firstChild,"color",Qy(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(a.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&Ea(a.firstChild,"backgroundColor",Qy(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?Ea(a,"backgroundColor",Qy(t.windowColor,t.windowOpacity)):a.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?a.firstChild.style.textShadow=`2px 2px 3px ${Hr}, 2px 2px 4px ${Hr}, 2px 2px 5px ${Hr}`:t.edgeStyle==="raised"?a.firstChild.style.textShadow=`1px 1px ${Hr}, 2px 2px ${Hr}, 3px 3px ${Hr}`:t.edgeStyle==="depressed"?a.firstChild.style.textShadow=`1px 1px ${VE}, 0 1px ${VE}, -1px -1px ${Hr}, 0 -1px ${Hr}`:t.edgeStyle==="uniform"&&(a.firstChild.style.textShadow=`0 0 4px ${Hr}, 0 0 4px ${Hr}, 0 0 4px ${Hr}, 0 0 4px ${Hr}`)),t.fontPercent&&t.fontPercent!==1){const u=de.parseFloat(a.style.fontSize);a.style.fontSize=u*t.fontPercent+"px",a.style.height="auto",a.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?a.firstChild.style.fontVariant="small-caps":a.firstChild.style.fontFamily=N4[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof de.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){Ia(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();xh(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}GC.prototype.controlText_="Play Video";ze.registerComponent("BigPlayButton",GC);class P4 extends On{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)}}ze.registerComponent("CloseButton",P4);class VC extends On{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()?Ia(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))}}VC.prototype.controlText_="Play";ze.registerComponent("PlayToggle",VC);class Yc extends ze{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=ei("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=ei("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=yu(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,vi.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_=pt.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}Yc.prototype.labelText_="Time";Yc.prototype.controlText_="Time";ze.registerComponent("TimeDisplay",Yc);class Sb extends Yc{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)}}Sb.prototype.labelText_="Current Time";Sb.prototype.controlText_="Current Time";ze.registerComponent("CurrentTimeDisplay",Sb);class Eb extends Yc{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)}}Eb.prototype.labelText_="Duration";Eb.prototype.controlText_="Duration";ze.registerComponent("DurationDisplay",Eb);class B4 extends ze{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}}ze.registerComponent("TimeDivider",B4);class wb extends Yc{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(ei("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)}}wb.prototype.labelText_="Remaining Time";wb.prototype.controlText_="Remaining Time";ze.registerComponent("RemainingTimeDisplay",wb);class F4 extends ze{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_=ei("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(ei("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(pt.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()}}ze.registerComponent("LiveDisplay",F4);class zC extends On{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_=ei("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()}}zC.prototype.controlText_="Seek to live, currently playing live";ze.registerComponent("SeekToLive",zC);function Vh(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var U4=Object.freeze({__proto__:null,clamp:Vh});class Ab extends ze{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"&&!Ha&&e.preventDefault(),yC(),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;vC(),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(Vh(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=o0(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")}}ze.registerComponent("Slider",Ab);const Zy=(s,e)=>Vh(s/e*100,0,100).toFixed(2)+"%";class j4 extends ze{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=ei("span",{className:"vjs-control-text"}),i=ei("span",{textContent:this.localize("Loaded")}),n=pt.createTextNode(": ");return this.percentageEl_=ei("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(),a=this.partEls_,u=Zy(r,n);this.percent_!==u&&(this.el_.style.width=u,kl(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(a[c-1]);a.length=i.length})}}ze.registerComponent("LoadProgressBar",j4);class $4 extends ze{constructor(e,t){super(e,t),this.update=Ga(gs(this,this.update),qr)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=Dh(this.el_),r=Fc(this.player_.el()),a=e.width*t;if(!r||!n)return;let u=e.left-r.left+a,c=e.width-a+(r.right-e.right);c||(c=e.width-a,u=a);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){kl(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+yu(c,u)}else r=yu(i,a);this.update(e,t,r),n&&n()})}}ze.registerComponent("TimeTooltip",$4);class Cb extends ze{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=Ga(gs(this,this.update),qr)}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)}}Cb.prototype.options_={children:[]};!In&&!la&&Cb.prototype.options_.children.push("timeTooltip");ze.registerComponent("PlayProgressBar",Cb);class qC extends ze{constructor(e,t){super(e,t),this.update=Ga(gs(this,this.update),qr)}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`})}}qC.prototype.options_={children:["timeTooltip"]};ze.registerComponent("MouseTimeDisplay",qC);class m0 extends Ab{constructor(e,t){t=rs(m0.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(In||la)||e.options_.disableSeekWhileScrubbingOnSTV;(!In&&!la||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=gs(this,this.update),this.update=Ga(this.update_,qr),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 pt&&"visibilityState"in pt&&this.on(pt,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){pt.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,qr))}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(pt.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}",[yu(i,r),yu(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(Fc(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){Lh(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Lh(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 a=r.seekableStart(),u=r.liveCurrentTime();if(i=a+n*r.liveWindow(),i>=u&&(i=u),i<=a&&(i=a+.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?Ia(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 pt&&"visibilityState"in pt&&this.off(pt,"visibilitychange",this.toggleVisibility_),super.dispose()}}m0.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};ze.registerComponent("SeekBar",m0);class KC extends ze{constructor(e,t){super(e,t),this.handleMouseMove=Ga(gs(this,this.handleMouseMove),qr),this.throttledHandleMouseSeek=Ga(gs(this,this.handleMouseSeek),qr),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(),a=Dh(r);let u=o0(r,e).x;u=Vh(u,0,1),n&&n.update(a,u),i&&i.update(a,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&&Ia(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"]};ze.registerComponent("ProgressControl",KC);class WC extends On{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(){pt.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in de?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 pt.exitPictureInPicture=="function"&&super.show()}}WC.prototype.controlText_="Picture-in-Picture";ze.registerComponent("PictureInPictureToggle",WC);class YC extends On{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),pt[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()}}YC.prototype.controlText_="Fullscreen";ze.registerComponent("FullscreenToggle",YC);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 G4 extends ze{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}}ze.registerComponent("VolumeLevel",G4);class V4 extends ze{constructor(e,t){super(e,t),this.update=Ga(gs(this,this.update),qr)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=Fc(this.el_),a=Fc(this.player_.el()),u=e.width*t;if(!a||!r)return;const c=e.left-a.left+u,d=e.width-u+(a.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){kl(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}ze.registerComponent("VolumeLevelTooltip",V4);class XC extends ze{constructor(e,t){super(e,t),this.update=Ga(gs(this,this.update),qr)}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`})}}XC.prototype.options_={children:["volumeLevelTooltip"]};ze.registerComponent("MouseVolumeLevelDisplay",XC);class p0 extends Ab{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){Lh(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=Fc(i),r=this.vertical();let a=o0(i,e);a=r?a.y:a.x,a=Vh(a,0,1),t.update(n,a,r)}Lh(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)})}}p0.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!In&&!la&&p0.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");p0.prototype.playerEvent="volumechange";ze.registerComponent("VolumeBar",p0);class QC extends ze{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Pc(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),H4(this,e),this.throttledHandleMouseMove=Ga(gs(this,this.handleMouseMove),qr),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)}}QC.prototype.options_={children:["volumeBar"]};ze.registerComponent("VolumeControl",QC);const z4=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 ZC extends On{constructor(e,t){super(e,t),z4(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"),In&&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),r0(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),du(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}ZC.prototype.controlText_="Mute";ze.registerComponent("MuteToggle",ZC);class JC extends ze{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Pc(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"),Ir(pt,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),Nn(pt,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}JC.prototype.options_={children:["muteToggle","volumeControl"]};ze.registerComponent("VolumePanel",JC);class ek extends On{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]))}}ek.prototype.controlText_="Skip Forward";ze.registerComponent("SkipForward",ek);class tk extends On{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]))}}tk.prototype.controlText_="Skip Backward";ze.registerComponent("SkipBackward",tk);class ik extends ze{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 ze&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof ze&&(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_=ei(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_),Ir(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||pt.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())}}ze.registerComponent("Menu",ik);class kb extends ze{constructor(e,t={}){super(e,t),this.menuButton_=new On(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=On.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(),Ir(pt,"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 ik(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=ei("li",{className:"vjs-menu-title",textContent:Fs(this.options_.title),tabIndex:-1}),i=new ze(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},a=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",a),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",a)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof de.Event!="object")try{u=new de.Event("change")}catch{}u||(u=pt.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&&a.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&&a.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()}}ze.registerComponent("OffTextTrackMenuItem",sk);class Xc extends Db{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=qh){let i;this.label_&&(i=`${this.label_} off`),e.push(new sk(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:a,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${a.kind}-menu-item`),e.push(u)}}return e}}ze.registerComponent("TextTrackButton",Xc);class nk extends zh{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(Fs(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(Fs(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 Nb(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,rk),e}}Mb.prototype.kinds_=["captions","subtitles"];Mb.prototype.controlText_="Subtitles";ze.registerComponent("SubsCapsButton",Mb);class ak extends zh{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=(...a)=>{this.handleTracksChange.apply(this,a)};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(ei("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(ei("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)}}Pb.prototype.contentElType="button";ze.registerComponent("PlaybackRateMenuItem",Pb);class lk extends kb{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_=ei("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 Pb(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")}}lk.prototype.controlText_="Playback Rate";ze.registerComponent("PlaybackRateMenuButton",lk);class uk extends ze{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}ze.registerComponent("Spacer",uk);class q4 extends uk{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}ze.registerComponent("CustomControlSpacer",q4);class ck extends ze{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}ck.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};ze.registerComponent("ControlBar",ck);class dk extends Wc{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):""}}dk.prototype.options_=Object.assign({},Wc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});ze.registerComponent("ErrorDisplay",dk);class hk extends ze{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(),ei("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${zr()}`)+"-"+t[1].replace(/\W+/g,""),n=ei("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}ze.registerComponent("TextTrackSelect",hk);class fu extends ze{constructor(e,t={}){super(e,t);const i=ei("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 a=this.options_.selectConfigs[r],u=a.className,c=a.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${zr()}`;if(this.options_.type==="colors"){d=ei("span",{className:u});const y=ei("label",{id:c,className:"vjs-label",textContent:this.localize(a.label)});y.setAttribute("for",f),d.appendChild(y)}const p=new hk(e,{SelectOptions:a.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 ei("fieldset",{className:this.options_.className})}}ze.registerComponent("TextTrackFieldset",fu);class fk extends ze{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new fu(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 fu(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 a=new fu(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(a)}createEl(){return ei("div",{className:"vjs-track-settings-colors"})}}ze.registerComponent("TextTrackSettingsColors",fk);class mk extends ze{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new fu(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 fu(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 a=new fu(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(a)}createEl(){return ei("div",{className:"vjs-track-settings-font"})}}ze.registerComponent("TextTrackSettingsFont",mk);class pk extends ze{constructor(e,t={}){super(e,t);const i=new On(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 On(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return ei("div",{className:"vjs-track-settings-controls"})}}ze.registerComponent("TrackSettingsControls",pk);const Jy="vjs-text-track-settings",qE=["#000","Black"],KE=["#00F","Blue"],WE=["#0FF","Cyan"],YE=["#0F0","Green"],XE=["#F0F","Magenta"],QE=["#F00","Red"],ZE=["#FFF","White"],JE=["#FF0","Yellow"],ev=["1","Opaque"],tv=["0.5","Semi-Transparent"],e2=["0","Transparent"],gl={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[qE,ZE,QE,YE,KE,JE,XE,WE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[ev,tv,e2],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[ZE,qE,QE,YE,KE,JE,XE,WE],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:[ev,tv],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:[e2,tv,ev],className:"vjs-window-opacity vjs-opacity"}};gl.windowColor.options=gl.backgroundColor.options;function gk(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function K4(s,e){const t=s.options[s.options.selectedIndex].value;return gk(t,e)}function W4(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()}),pc(gl,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 rC(gl,(e,t,i)=>{const n=K4(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){pc(gl,(t,i)=>{W4(this.$(t.selector),e[i],t.parser)})}setDefaults(){pc(gl,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(de.localStorage.getItem(Jy))}catch(t){vi.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?de.localStorage.setItem(Jy,JSON.stringify(e)):de.localStorage.removeItem(Jy)}catch(t){vi.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}ze.registerComponent("TextTrackSettings",Y4);class X4 extends ze{constructor(e,t){let i=t.ResizeObserver||de.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=rs({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||de.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=kC(()=>{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 a=this.unloadListener_=function(){Nn(this,"resize",r),Nn(this,"unload",a),a=null};Ir(this.el_.contentWindow,"unload",a),Ir(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()}}ze.registerComponent("ResizeManager",X4);const Q4={trackingThreshold:20,liveTolerance:15};class Z4 extends ze{constructor(e,t){const i=rs(Q4,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(de.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 a=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,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_,qr),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()}}ze.registerComponent("LiveTracker",Z4);class J4 extends ze{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:ei("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${zr()}`}),description:ei("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${zr()}`})},ei("div",{className:"vjs-title-bar"},{},aC(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],a=this.els[n],u=i[n];l0(a),r&&kl(a,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,a.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}}ze.registerComponent("TitleBar",J4);const eB={initialDisplay:4e3,position:[],takeFocus:!1};class tB extends On{constructor(e,t){t=rs(eB,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=ei("button",{},{type:"button",class:this.buildCSSClass()},ei("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()}}ze.registerComponent("TransientButton",tB);const px=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;iyk([s.el(),de.HTMLMediaElement.prototype,de.Element.prototype,iB],"innerHTML"),t2=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=sB(s),n=r=>(...a)=>{const u=r.apply(e,a);return px(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",rs(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_)},nB=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?UC(de.Element.prototype.getAttribute.call(this,"src")):""},set(s){return de.Element.prototype.setAttribute.call(this,"src",s),s}}),rB=s=>yk([s.el(),de.HTMLMediaElement.prototype,nB],"src"),aB=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=rB(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",rs(t,{set:r=>{const a=t.set.call(e,r);return s.triggerSourceset(e.src),a}})),e.setAttribute=(r,a)=>{const u=i.call(e,r,a);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return px(s)||(s.triggerSourceset(""),t2(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):px(s)||t2(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class kt extends ui{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 a=r.length;const u=[];for(;a--;){const c=r[a];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")&&h0(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=Vr[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[jc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},a=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",a),this.on("dispose",u=>this.off("loadstart",a))}proxyNativeTracks_(){Vr.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),kt.disposeMediaElement(e),e=i}else{e=pt.createElement("video");const i=this.options_.tag&&pl(this.options_.tag),n=rs({},i);(!kh||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,pC(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&&n0?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){vi(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&la&&Ha&&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)Ia(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 vi.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=ei("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return vi.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 vi.warn(`No matching source element found with src: ${e}`),!1}reset(){kt.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=pt.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),de.performance&&(e.creationTime=de.performance.now()),e}}e0(kt,"TEST_VID",function(){if(!zc())return;const s=pt.createElement("video"),e=pt.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});kt.isSupported=function(){try{kt.TEST_VID.volume=.5}catch{return!1}return!!(kt.TEST_VID&&kt.TEST_VID.canPlayType)};kt.canPlayType=function(s){return kt.TEST_VID.canPlayType(s)};kt.canPlaySource=function(s,e){return kt.canPlayType(s.type)};kt.canControlVolume=function(){try{const s=kt.TEST_VID.volume;kt.TEST_VID.volume=s/2+.1;const e=s!==kt.TEST_VID.volume;return e&&In?(de.setTimeout(()=>{kt&&kt.prototype&&(kt.prototype.featuresVolumeControl=s!==kt.TEST_VID.volume)}),!1):e}catch{return!1}};kt.canMuteVolume=function(){try{const s=kt.TEST_VID.muted;return kt.TEST_VID.muted=!s,kt.TEST_VID.muted?Bc(kt.TEST_VID,"muted","muted"):a0(kt.TEST_VID,"muted","muted"),s!==kt.TEST_VID.muted}catch{return!1}};kt.canControlPlaybackRate=function(){if(la&&Ha&&t0<58)return!1;try{const s=kt.TEST_VID.playbackRate;return kt.TEST_VID.playbackRate=s/2+.1,s!==kt.TEST_VID.playbackRate}catch{return!1}};kt.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(pt.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(pt.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(pt.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(pt.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};kt.supportsNativeTextTracks=function(){return n0||In&&Ha};kt.supportsNativeVideoTracks=function(){return!!(kt.TEST_VID&&kt.TEST_VID.videoTracks)};kt.supportsNativeAudioTracks=function(){return!!(kt.TEST_VID&&kt.TEST_VID.audioTracks)};kt.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]){e0(kt.prototype,s,()=>kt[e](),!0)});kt.prototype.featuresVolumeControl=kt.canControlVolume();kt.prototype.movingMediaElementInDOM=!In;kt.prototype.featuresFullscreenResize=!0;kt.prototype.featuresProgressEvents=!0;kt.prototype.featuresTimeupdateEvents=!0;kt.prototype.featuresVideoFrameCallback=!!(kt.TEST_VID&&kt.TEST_VID.requestVideoFrameCallback);kt.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{}})()}};kt.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){kt.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){kt.prototype["set"+Fs(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){kt.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){kt.prototype["set"+Fs(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){kt.prototype[s]=function(){return this.el_[s]()}});ui.withSourceHandlers(kt);kt.nativeSourceHandler={};kt.nativeSourceHandler.canPlayType=function(s){try{return kt.TEST_VID.canPlayType(s)}catch{return""}};kt.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return kt.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=Tb(s.src);return kt.nativeSourceHandler.canPlayType(`video/${t}`)}return""};kt.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};kt.nativeSourceHandler.dispose=function(){};kt.registerSourceHandler(kt.nativeSourceHandler);ui.registerTech("Html5",kt);const vk=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],iv={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},gx=["tiny","xsmall","small","medium","large","xlarge","huge"],Vm={};gx.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;Vm[s]=`vjs-layout-${e}`});const oB={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let As=class ac extends ze{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${zr()}`,t=Object.assign(ac.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const a=e.closest("[lang]");a&&(t.language=a.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=a=>this.documentFullscreenChange_(a),this.boundFullWindowOnEscKey_=a=>this.fullWindowOnEscKey(a),this.boundUpdateStyleEl_=a=>this.updateStyleEl_(a),this.boundApplyInitTime_=a=>this.applyInitTime_(a),this.boundUpdateCurrentBreakpoint_=a=>this.updateCurrentBreakpoint_(a),this.boundHandleTechClick_=a=>this.handleTechClick_(a),this.boundHandleTechDoubleClick_=a=>this.handleTechDoubleClick_(a),this.boundHandleTechTouchStart_=a=>this.handleTechTouchStart_(a),this.boundHandleTechTouchMove_=a=>this.handleTechTouchMove_(a),this.boundHandleTechTouchEnd_=a=>this.handleTechTouchEnd_(a),this.boundHandleTechTap_=a=>this.handleTechTap_(a),this.boundUpdatePlayerHeightOnAudioOnlyMode_=a=>this.updatePlayerHeightOnAudioOnlyMode_(a),this.isFullscreen_=!1,this.log=sC(this.id_),this.fsApi_=lp,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&&pl(e),this.language(this.options_.language),t.languages){const a={};Object.getOwnPropertyNames(t.languages).forEach(function(u){a[u.toLowerCase()]=t.languages[u]}),this.languages_=a}else this.languages_=ac.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(a=>{if(typeof this[a]!="function")throw new Error(`plugin "${a}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),gb(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(Ir(pt,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=rs(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(a=>{this[a](t.plugins[a])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new de.DOMParser().parseFromString(L4,"image/svg+xml");if(u.querySelector("parsererror"))vi.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 R4(this),this.addClass("vjs-spatial-navigation-enabled")),kh&&this.addClass("vjs-touch-enabled"),In||this.addClass("vjs-workinghover"),ac.players[this.id_]=this;const r=rx.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",a=>this.listenForUserActivity_(a)),this.on("keydown",a=>this.handleKeyDown(a)),this.on("languagechange",a=>this.handleLanguagechange(a)),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"),Nn(pt,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),Nn(pt,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),ac.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),A4(this),Vn.names.forEach(e=>{const t=Vn[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=pl(e);if(n){for(t=this.el_=e,e=this.tag=pt.createElement("video");t.children.length;)e.appendChild(t.firstChild);yh(t,"video-js")||du(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",Ha&&i0&&(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 a=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>dC[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),de.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=AC("vjs-styles-dimensions");const c=wl(".vjs-styles-defaults"),d=wl("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"){vi.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)){vi.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,Eo(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),n4(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(de.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(":"),a=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/a:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*a,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),CC(this.styleEl_,` + .${n} { + width: ${e}px; + height: ${t}px; + } + + .${n}.vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: ${a*100}%; + } + `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=Fs(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(ui.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 a={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};Vn.names.forEach(c=>{const d=Vn[c];a[d.getterName]=this[d.privateName]}),Object.assign(a,this.options_[i]),Object.assign(a,this.options_[n]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);const u=ui.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(a),this.tech_.ready(gs(this,this.handleTechReady_),!0),fx.jsonToTextTracks(this.textTracksJson_||[],this.tech_),vk.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${Fs(c)}_`](d))}),Object.keys(iv).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${iv[c]}_`].bind(this),event:d});return}this[`handleTech${iv[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)&&ox(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Vn.names.forEach(e=>{const t=Vn[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=fx.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&&vi.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":rx}}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 a=this.play();if(xh(a))return a.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),xh(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!xh(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=D4(this,t)),this.cache_.source=rs({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],a=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 a=this.techGet_("currentSrc");this.lastSource_.tech=a,this.updateSourceCaches_(a)})}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()?Ia(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()&&!pt.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=pt[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 E4)return _4(this.middleware_,this.tech_,e,t);if(e in jE)return UE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw vi(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in S4)return T4(this.middleware_,this.tech_,e);if(e in jE)return UE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(vi(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(vi(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(vi(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Ia){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(n0||In);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=a=>{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")||oa(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=oa(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=oa(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 PC(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",a)}function a(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",a),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",a),e.off("fullscreenchange",r)}function r(){n(),t()}function a(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",a);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=pt[this.fsApi_.exitFullscreen]();return e&&Ia(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=pt.documentElement.style.overflow,Ir(pt,"keydown",this.boundFullWindowOnEscKey_),pt.documentElement.style.overflow="hidden",du(pt.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,Nn(pt,"keydown",this.boundFullWindowOnEscKey_),pt.documentElement.style.overflow=this.docOrigOverflow,r0(pt.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&&de.documentPictureInPicture){const e=pt.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(ei("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),de.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(SC(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 pt&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(de.documentPictureInPicture&&de.documentPictureInPicture.window)return de.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in pt)return pt.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const a=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?a.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=a=>e.key.toLowerCase()==="f",muteKey:n=a=>e.key.toLowerCase()==="m",playPauseKey:r=a=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=ze.getComponent("FullscreenToggle");pt[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),ze.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),ze.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,ui.getTech(u)]).filter(([u,c])=>c?c.isSupported():(vi.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(y=>{if(f=d(p,y),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),a=([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(a)):n=i(t,e,a),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=HC(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]),x4(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}b4(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?IC(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();Ia(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}),Eo(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(El("beforeerror").forEach(t=>{const i=t(this,e);if(!($a(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 Rs(e),this.addClass("vjs-error"),vi.error(`(CODE:${this.error_.code} ${Rs.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),El("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=gs(this,this.reportUserActivity),r=function(p){(p.screenX!==t||p.screenY!==i)&&(t=p.screenX,i=p.screenY,n())},a=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(p){n(),this.clearInterval(e)};this.on("mousedown",a),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!In&&!la&&(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(),Eo(this)&&this.trigger("languagechange"))}languages(){return rs(ac.prototype.options_.languages,this.languages_)}toJSON(){const e=rs(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:a||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:vp(n.poster)}]),n}return rs(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=pl(e),n=i["data-setup"];if(yh(e,"vjs-fill")&&(i.fill=!0),yh(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){vi.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let a=0,u=r.length;atypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};As.prototype.videoTracks=()=>{};As.prototype.audioTracks=()=>{};As.prototype.textTracks=()=>{};As.prototype.remoteTextTracks=()=>{};As.prototype.remoteTextTrackEls=()=>{};Vn.names.forEach(function(s){const e=Vn[s];As.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});As.prototype.crossorigin=As.prototype.crossOrigin;As.players={};const Zd=de.navigator;As.prototype.options_={techOrder:ui.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:Zd&&(Zd.languages&&Zd.languages[0]||Zd.userLanguage||Zd.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};vk.forEach(function(s){As.prototype[`handleTech${Fs(s)}_`]=function(){return this.trigger(s)}});ze.registerComponent("Player",As);const xp="plugin",vc="activePlugins_",cc={},bp=s=>cc.hasOwnProperty(s),zm=s=>bp(s)?cc[s]:void 0,xk=(s,e)=>{s[vc]=s[vc]||{},s[vc][e]=!0},Tp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},lB=function(s,e){const t=function(){Tp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return xk(this,s),Tp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},i2=(s,e)=>(e.prototype.name=s,function(...t){Tp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,Tp(this,i.getEventHash()),i});class fr{constructor(e){if(this.constructor===fr)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),gb(this),delete this.trigger,RC(this,this.constructor.defaultState),xk(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 Kc(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[vc][e]=!1,this.player=this.state=null,t[e]=i2(e,cc[e])}static isBasic(e){const t=typeof e=="string"?zm(e):e;return typeof t=="function"&&!fr.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(bp(e))vi.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(As.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 cc[e]=t,e!==xp&&(fr.isBasic(t)?As.prototype[e]=lB(e,t):As.prototype[e]=i2(e,t)),t}static deregisterPlugin(e){if(e===xp)throw new Error("Cannot de-register base plugin.");bp(e)&&(delete cc[e],delete As.prototype[e])}static getPlugins(e=Object.keys(cc)){let t;return e.forEach(i=>{const n=zm(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=zm(e);return t&&t.VERSION||""}}fr.getPlugin=zm;fr.BASE_PLUGIN_NAME=xp;fr.registerPlugin(xp,fr);As.prototype.usingPlugin=function(s){return!!this[vc]&&this[vc][s]===!0};As.prototype.hasPlugin=function(s){return!!bp(s)};function uB(s,e){let t=!1;return function(...i){return t||vi.warn(s),t=!0,e.apply(this,i)}}function ua(s,e,t,i){return uB(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var cB={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 bk=s=>s.indexOf("#")===0?s.slice(1):s;function Re(s,e,t){let i=Re.getPlayer(s);if(i)return e&&vi.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?wl("#"+bk(s)):s;if(!qc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in n?n.getRootNode()instanceof de.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!a.contains(n))&&vi.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)),El("beforesetup").forEach(c=>{const d=c(n,rs(e));if(!$a(d)||Array.isArray(d)){vi.error("please return an object in beforesetup hooks");return}e=rs(e,d)});const u=ze.getComponent("Player");return i=new u(n,e,t),El("setup").forEach(c=>c(i)),i}Re.hooks_=bo;Re.hooks=El;Re.hook=VP;Re.hookOnce=zP;Re.removeHook=iC;if(de.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&zc()){let s=wl(".vjs-styles-defaults");if(!s){s=AC("vjs-styles-defaults");const e=wl("head");e&&e.insertBefore(s,e.firstChild),CC(s,` + .video-js { + width: 300px; + height: 150px; + } + + .vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: 56.25% + } + `)}}ux(1,Re);Re.VERSION=rx;Re.options=As.prototype.options_;Re.getPlayers=()=>As.players;Re.getPlayer=s=>{const e=As.players;let t;if(typeof s=="string"){const i=bk(s),n=e[i];if(n)return n;t=wl("#"+i)}else t=s;if(qc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};Re.getAllPlayers=()=>Object.keys(As.players).map(s=>As.players[s]).filter(Boolean);Re.players=As.players;Re.getComponent=ze.getComponent;Re.registerComponent=(s,e)=>(ui.isTech(e)&&vi.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),ze.registerComponent.call(ze,s,e));Re.getTech=ui.getTech;Re.registerTech=ui.registerTech;Re.use=v4;Object.defineProperty(Re,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(Re.middleware,"TERMINATOR",{value:yp,writeable:!1,enumerable:!0});Re.browser=dC;Re.obj=WP;Re.mergeOptions=ua(9,"videojs.mergeOptions","videojs.obj.merge",rs);Re.defineLazyProperty=ua(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",e0);Re.bind=ua(9,"videojs.bind","native Function.prototype.bind",gs);Re.registerPlugin=fr.registerPlugin;Re.deregisterPlugin=fr.deregisterPlugin;Re.plugin=(s,e)=>(vi.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),fr.registerPlugin(s,e));Re.getPlugins=fr.getPlugins;Re.getPlugin=fr.getPlugin;Re.getPluginVersion=fr.getPluginVersion;Re.addLanguage=function(s,e){return s=(""+s).toLowerCase(),Re.options.languages=rs(Re.options.languages,{[s]:e}),Re.options.languages[s]};Re.log=vi;Re.createLogger=sC;Re.time=u4;Re.createTimeRange=ua(9,"videojs.createTimeRange","videojs.time.createTimeRanges",oa);Re.createTimeRanges=ua(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",oa);Re.formatTime=ua(9,"videojs.formatTime","videojs.time.formatTime",yu);Re.setFormatTime=ua(9,"videojs.setFormatTime","videojs.time.setFormatTime",OC);Re.resetFormatTime=ua(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",MC);Re.parseUrl=ua(9,"videojs.parseUrl","videojs.url.parseUrl",bb);Re.isCrossOrigin=ua(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",h0);Re.EventTarget=Nr;Re.any=pb;Re.on=Ir;Re.one=c0;Re.off=Nn;Re.trigger=Kc;Re.xhr=$A;Re.TrackList=vu;Re.TextTrack=Gh;Re.TextTrackList=vb;Re.AudioTrack=jC;Re.AudioTrackList=BC;Re.VideoTrack=$C;Re.VideoTrackList=FC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{Re[s]=function(){return vi.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),EC[s].apply(null,arguments)}});Re.computedStyle=ua(9,"videojs.computedStyle","videojs.dom.computedStyle",Uc);Re.dom=EC;Re.fn=s4;Re.num=U4;Re.str=o4;Re.url=g4;Re.Error=cB;class dB{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 _p extends Re.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 dB(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=Tk,i},_k=function(s){return hB(this,Re.obj.merge({},s))};Re.registerPlugin("qualityLevels",_k);_k.VERSION=Tk;const ur=Xp,Sp=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,Yr=s=>Re.log.debug?Re.log.debug.bind(Re,"VHS:",`${s} >`):function(){};function qi(...s){const e=Re.obj||Re;return(e.merge||e.mergeOptions).apply(e,s)}function yn(...s){const e=Re.time||Re;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function fB(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 Na=1/30,Oa=Na*3,Sk=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},Tm=function(s,e){return Sk(s,function(t){return t-Na>=e})},mB=function(s){if(s.length<2)return yn();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(", ")},gB=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},uu=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},Fb=(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},yx=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),[]),wk=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},Ak=({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},Ck=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=wk(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},vB=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+=Fb(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},xB=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 de.Infinity}return kk(s,e,t)},bh=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(a+=f.duration,r){if(a<0)continue}else if(a+Na<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-bh({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(a-=s.targetDuration,a<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dNa,y=a===0,v=p&&a+Na>=0;if(!((y||v)&&d!==u.length-1)){if(r){if(a>0)continue}else if(a-Na>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+bh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},Rk=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Ub=function(s){return s.excludeUntil&&s.excludeUntil===1/0},g0=function(s){const e=Rk(s);return!s.disabled&&!e},_B=function(s){return s.disabled},SB=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=>g0(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),s2=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},Kh=s=>{if(!s||!s.playlists||!s.playlists.length)return s2(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;eVA(r))||s2(s,r=>jb(t,r))))return!1}return!0};var cr={liveEdgeDelay:Ck,duration:Dk,seekable:bB,getMediaInfoForTime:TB,isEnabled:g0,isDisabled:_B,isExcluded:Rk,isIncompatible:Ub,playlistEnd:Lk,isAes:SB,hasAttribute:Ik,estimateSegmentRequestTime:EB,isLowestEnabledRendition:vx,isAudioOnly:Kh,playlistMatch:jb,segmentDurationWithParts:Fb};const{log:Nk}=Re,xc=(s,e)=>`${s}-${e}`,Ok=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,wB=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const a=new h3;s&&a.on("warn",s),e&&a.on("info",e),i.forEach(d=>a.addParser(d)),n.forEach(d=>a.addTagMapper(d)),a.push(t),a.end();const u=a.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=wk(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}`}),Nk.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},Qc=(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)}})},Mk=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},AB=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];Mk({playlist:t,id:xc(e,t.uri)}),t.resolvedUri=ur(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||Nk.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},CB=s=>{Qc(s,e=>{e.uri&&(e.resolvedUri=ur(s.uri,e.uri))})},kB=(s,e)=>{const t=xc(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:de.location.href,resolvedUri:de.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},Pk=(s,e,t=Ok)=>{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,a={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)a.error=Ks({},t),a.errorType=Re.Error.NetworkRequestFailed;else if(e.aborted)a.errorType=Re.Error.NetworkRequestAborted;else if(e.timedout)a.errorType=Re.Error.NetworkRequestTimeout;else if(u){const c=i?Re.Error.NetworkBodyParserFailed:Re.Error.NetworkBadStatus;a.errorType=c,a.status=e.status,a.headers=e.headers}return a},DB=Yr("CodecUtils"),Fk=function(s){const e=s.attributes||{};if(e.CODECS)return Da(e.CODECS)},Uk=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},LB=(s,e)=>{if(!Uk(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},Rh=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(GA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){DB(`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},r2=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},Th=function(s,e){const t=e.attributes||{},i=Rh(Fk(e)||[]);if(Uk(s,e)&&!i.audio&&!LB(s,e)){const n=Rh(m3(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:RB}=Re,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||[],a=Ak(e)-1;a>-1&&a!==r.length-1&&(t._HLS_part=a),(a>-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 de.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},NB=(s,e)=>{if(!s)return e;const t=qi(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 a;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=ur(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=ur(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=ur(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=ur(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=ur(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=ur(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,xx=(s,e,t=Hk)=>{const i=qi(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=$k(e);const r=qi(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a{jk(a,r.resolvedUri)});for(let a=0;a{if(a.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},a2=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:a,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:a,codecs:u})}),{type:e,isLive:t,renditions:i}};let hc=class extends RB{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Yr("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 n2,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=ur(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:mu({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=wB({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:Re.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:a}=n.RESOLUTION||{};if(r&&a)return!0;const u=Fk(i)||[];return!!Rh(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 a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),Mk({playlist:a,uri:i,id:n});const u=xx(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(bx(this.media(),!!u)),r.parsedPlaylist=a2(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),de.clearTimeout(this.mediaUpdateTimeout),de.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new n2,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(de.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=de.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_(bx(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 a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),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=Sp(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(de.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&&(de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=de.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&&(de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=de.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=de.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:mu({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=Sp(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=a2(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,Pk(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=$k(i),i.segments.forEach(n=>{jk(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||de.location.href;this.main=kB(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 a=i.playlists[r];if(a.attributes["PATHWAY-ID"]===n){const u=a.resolvedUri,c=a.id;if(t){const d=this.createCloneURI_(a.resolvedUri,e),f=xc(n,d),p=this.createCloneAttributes_(n,a.attributes),y=this.createClonePlaylist_(a,f,e,p);i.playlists[r]=y,i.playlists[f]=y,i.playlists[d]=y}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 a in i.mediaGroups[r])if(a===n){for(const u in i.mediaGroups[r][a])i.mediaGroups[r][a][u].playlists.forEach((d,f)=>{const p=i.playlists[d.id],y=p.id,v=p.resolvedUri;delete i.playlists[y],delete i.playlists[v]});delete i.mediaGroups[r][a]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),a=xc(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,a,e,u);i.playlists[n]=c,i.playlists[a]=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 a in n.mediaGroups[r]){if(a===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][a]){const c=n.mediaGroups[r][a][u];n.mediaGroups[r][t][u]=Ks({},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,y)=>{const v=n.playlists[p.id],b=Ok(r,t,u),_=xc(t,b);if(v&&!n.playlists[_]){const S=this.createClonePlaylist_(v,_,e),L=S.resolvedUri;n.playlists[_]=S,n.playlists[L]=S}d.playlists[y]=this.createClonePlaylist_(p,_,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:r,uri:r,id:t};return e.segments&&(a.segments=[]),n&&(a.attributes=n),qi(e,a)}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 Tx=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)},MB=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},PB=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},Gk=function(){const s=function e(t,i){t=qi({timeout:45e3},t);const n=e.beforeRequest||Re.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Re.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||Re.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(Re.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=Re.Vhs.xhr.original===!0?Re.xhr:Re.Vhs.xhr,c=MB(r,t);r.delete(n);const d=u(c||t,function(p,y){return PB(a,d,p,y),Tx(d,p,y,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},BB=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=de.BigInt(s.offset)+de.BigInt(s.length)-de.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},_x=function(s){const e={};return s.byterange&&(e.Range=BB(s.byterange)),e},FB=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?" ":"")},jB=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},Vk=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];qA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},Ep=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},zk=function(s){return s.resolvedUri},qk=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let a=0;aqk(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)},zB=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,qB=(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:cr.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},KB=(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"}},WB=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},YB=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=KB(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=VB(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},Wk=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!YB(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=qB(s,e);if(!u)return a({message:`${s} was not found in the stream`});const c=u.segment,d=WB(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return a({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{Wk({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:a})});return}const f=c.start+d,p=()=>a(null,r.currentTime());r.one("seeked",p),n&&r.pause(),i(f)},nv=(s,e)=>{if(s.readyState===4)return e()},QB=(s,e,t,i)=>{let n=[],r,a=!1;const u=function(p,y,v,b){return y.abort(),a=!0,t(p,y,v,b)},c=function(p,y){if(a)return;if(p)return p.metadata=mu({requestType:i,request:y,error:p}),u(p,y,"",n);const v=y.responseText.substring(n&&n.byteLength||0,y.responseText.length);if(n=E3(n,KA(v,!0)),r=r||oh(n),n.length<10||r&&n.lengthu(p,y,"",n));const b=cb(n);return b==="ts"&&n.length<188?nv(y,()=>u(p,y,"",n)):!b&&n.length<376?nv(y,()=>u(p,y,"",n)):u(null,y,b,n)},f=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:y,loaded:v}){return Tx(p,null,{statusCode:p.status},c)})}},function(p,y){return Tx(f,p,y,c)});return f},{EventTarget:ZB}=Re,o2=function(s,e){if(!Hk(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}`},eF=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=_P(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return Pk(r,e,JB),r},tF=(s,e)=>{Qc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},iF=(s,e,t)=>{let i=!0,n=qi(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=xx(n,r.playlists[0],o2);f&&(n=f,c in n.mediaGroups[a][u]||(n.mediaGroups[a][u][c]=r),n.mediaGroups[a][u][c].playlists[0]=n.playlists[d],i=!1)}}),tF(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},sF=(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,l2=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const a=Zp(r);if(!e[a])break;const u=e[a].sidxInfo;sF(u,r)&&(t[a]=e[a])}}return t},nF=(s,e)=>{let i=l2(s.playlists,e);return Qc(s,(n,r,a,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=qi(i,l2(c,e))}}),i};class Sx extends ZB{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_=Yr("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&&Zp(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){de.clearTimeout(this.mediaRequest_),this.mediaRequest_=de.setTimeout(()=>i(!1),0);return}const r=Sp(e.sidx.resolvedUri),a=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:p}=d;let y;try{y=CP(Wt(d.response).subarray(8))}catch(v){v.metadata=mu({requestType:p,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:y},ob(e,y,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=QB(r,this.vhs_.xhr,(c,d,f,p)=>{if(c)return a(c,d);if(!f||f!=="mp4"){const b=f||"unknown";return a({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:y,length:v}=e.sidx.byterange;if(p.length>=v+y)return a(c,{response:p.subarray(y,y+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:_x({byterange:e.sidx.byterange})},a)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},de.clearTimeout(this.minimumUpdatePeriodTimeout_),de.clearTimeout(this.mediaRequest_),de.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,de.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(),de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(de.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,de.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=de.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_){de.clearTimeout(this.mediaRequest_),this.mediaRequest_=de.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:a}=n;i.metadata=mu({requestType:a,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=Sp(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=SP(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:ur(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:a}=n;return this.error.metadata=mu({requestType:a,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_(){de.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=eF({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:Re.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=iF(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:a}=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:!a,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_&&(de.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_=de.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_=nF(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=de.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},bx(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 pn={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 rF=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(A){var k,C,N,U;if(k=x[A],!!k)if(arguments.length===2)for(N=k.length,C=0;C"u")){for(x in J)J.hasOwnProperty(x)&&(J[x]=[x.charCodeAt(0),x.charCodeAt(1),x.charCodeAt(2),x.charCodeAt(3)]);ae=new Uint8Array([105,115,111,109]),K=new Uint8Array([97,118,99,49]),se=new Uint8Array([0,0,0,1]),X=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]),ee=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]),le={video:X,audio:ee},Q=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),P=new Uint8Array([0,0,0,0,0,0,0,0]),ue=new Uint8Array([0,0,0,0,0,0,0,0]),he=ue,re=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Pe=ue,pe=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(x){var A=[],k=0,C,N,U;for(C=1;C>>1,x.samplingfrequencyindex<<7|x.channelcount<<3,6,1,2]))},f=function(){return u(J.ftyp,ae,se,ae,K)},F=function(x){return u(J.hdlr,le[x])},p=function(x){return u(J.mdat,x)},B=function(x){var A=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,x.duration>>>24&255,x.duration>>>16&255,x.duration>>>8&255,x.duration&255,85,196,0,0]);return x.samplerate&&(A[12]=x.samplerate>>>24&255,A[13]=x.samplerate>>>16&255,A[14]=x.samplerate>>>8&255,A[15]=x.samplerate&255),u(J.mdhd,A)},$=function(x){return u(J.mdia,B(x),F(x.type),v(x))},y=function(x){return u(J.mfhd,new Uint8Array([0,0,0,0,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&255]))},v=function(x){return u(J.minf,x.type==="video"?u(J.vmhd,pe):u(J.smhd,P),c(),G(x))},b=function(x,A){for(var k=[],C=A.length;C--;)k[C]=O(A[C]);return u.apply(null,[J.moof,y(x)].concat(k))},_=function(x){for(var A=x.length,k=[];A--;)k[A]=I(x[A]);return u.apply(null,[J.moov,L(4294967295)].concat(k).concat(S(x)))},S=function(x){for(var A=x.length,k=[];A--;)k[A]=W(x[A]);return u.apply(null,[J.mvex].concat(k))},L=function(x){var A=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&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(J.mvhd,A)},M=function(x){var A=x.samples||[],k=new Uint8Array(4+A.length),C,N;for(N=0;N>>8),U.push(C[ne].byteLength&255),U=U.concat(Array.prototype.slice.call(C[ne]));for(ne=0;ne>>8),ie.push(N[ne].byteLength&255),ie=ie.concat(Array.prototype.slice.call(N[ne]));if(oe=[J.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,(k.width&65280)>>8,k.width&255,(k.height&65280)>>8,k.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(J.avcC,new Uint8Array([1,k.profileIdc,k.profileCompatibility,k.levelIdc,255].concat([C.length],U,[N.length],ie))),u(J.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],k.sarRatio){var fe=k.sarRatio[0],_e=k.sarRatio[1];oe.push(u(J.pasp,new Uint8Array([(fe&4278190080)>>24,(fe&16711680)>>16,(fe&65280)>>8,fe&255,(_e&4278190080)>>24,(_e&16711680)>>16,(_e&65280)>>8,_e&255])))}return u.apply(null,oe)},A=function(k){return u(J.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(k.channelcount&65280)>>8,k.channelcount&255,(k.samplesize&65280)>>8,k.samplesize&255,0,0,0,0,(k.samplerate&65280)>>8,k.samplerate&255,0,0]),d(k))}})(),R=function(x){var A=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,0,(x.duration&4278190080)>>24,(x.duration&16711680)>>16,(x.duration&65280)>>8,x.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,(x.width&65280)>>8,x.width&255,0,0,(x.height&65280)>>8,x.height&255,0,0]);return u(J.tkhd,A)},O=function(x){var A,k,C,N,U,ie,ne;return A=u(J.tfhd,new Uint8Array([0,0,0,58,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),ie=Math.floor(x.baseMediaDecodeTime/a),ne=Math.floor(x.baseMediaDecodeTime%a),k=u(J.tfdt,new Uint8Array([1,0,0,0,ie>>>24&255,ie>>>16&255,ie>>>8&255,ie&255,ne>>>24&255,ne>>>16&255,ne>>>8&255,ne&255])),U=92,x.type==="audio"?(C=Y(x,U),u(J.traf,A,k,C)):(N=M(x),C=Y(x,N.length+U),u(J.traf,A,k,C,N))},I=function(x){return x.duration=x.duration||4294967295,u(J.trak,R(x),$(x))},W=function(x){var A=new Uint8Array([0,0,0,0,(x.id&4278190080)>>24,(x.id&16711680)>>16,(x.id&65280)>>8,x.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return x.type!=="video"&&(A[A.length-1]=0),u(J.trex,A)},(function(){var x,A,k;k=function(C,N){var U=0,ie=0,ne=0,oe=0;return C.length&&(C[0].duration!==void 0&&(U=1),C[0].size!==void 0&&(ie=2),C[0].flags!==void 0&&(ne=4),C[0].compositionTimeOffset!==void 0&&(oe=8)),[0,0,U|ie|ne|oe,1,(C.length&4278190080)>>>24,(C.length&16711680)>>>16,(C.length&65280)>>>8,C.length&255,(N&4278190080)>>>24,(N&16711680)>>>16,(N&65280)>>>8,N&255]},A=function(C,N){var U,ie,ne,oe,fe,_e;for(oe=C.samples||[],N+=20+16*oe.length,ne=k(oe,N),ie=new Uint8Array(ne.length+oe.length*16),ie.set(ne),U=ne.length,_e=0;_e>>24,ie[U++]=(fe.duration&16711680)>>>16,ie[U++]=(fe.duration&65280)>>>8,ie[U++]=fe.duration&255,ie[U++]=(fe.size&4278190080)>>>24,ie[U++]=(fe.size&16711680)>>>16,ie[U++]=(fe.size&65280)>>>8,ie[U++]=fe.size&255,ie[U++]=fe.flags.isLeading<<2|fe.flags.dependsOn,ie[U++]=fe.flags.isDependedOn<<6|fe.flags.hasRedundancy<<4|fe.flags.paddingValue<<1|fe.flags.isNonSyncSample,ie[U++]=fe.flags.degradationPriority&61440,ie[U++]=fe.flags.degradationPriority&15,ie[U++]=(fe.compositionTimeOffset&4278190080)>>>24,ie[U++]=(fe.compositionTimeOffset&16711680)>>>16,ie[U++]=(fe.compositionTimeOffset&65280)>>>8,ie[U++]=fe.compositionTimeOffset&255;return u(J.trun,ie)},x=function(C,N){var U,ie,ne,oe,fe,_e;for(oe=C.samples||[],N+=20+8*oe.length,ne=k(oe,N),U=new Uint8Array(ne.length+oe.length*8),U.set(ne),ie=ne.length,_e=0;_e>>24,U[ie++]=(fe.duration&16711680)>>>16,U[ie++]=(fe.duration&65280)>>>8,U[ie++]=fe.duration&255,U[ie++]=(fe.size&4278190080)>>>24,U[ie++]=(fe.size&16711680)>>>16,U[ie++]=(fe.size&65280)>>>8,U[ie++]=fe.size&255;return u(J.trun,U)},Y=function(C,N){return C.type==="audio"?x(C,N):A(C,N)}})();var Ee={ftyp:f,mdat:p,moof:b,moov:_,initSegment:function(x){var A=f(),k=_(x),C;return C=new Uint8Array(A.byteLength+k.byteLength),C.set(A),C.set(k,A.byteLength),C}},Ge=function(x){var A,k,C=[],N=[];for(N.byteLength=0,N.nalCount=0,N.duration=0,C.byteLength=0,A=0;A1&&(A=x.shift(),x.byteLength-=A.byteLength,x.nalCount-=A.nalCount,x[0][0].dts=A.dts,x[0][0].pts=A.pts,x[0][0].duration+=A.duration),x},_t=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},mt=function(x,A){var k=_t();return k.dataOffset=A,k.compositionTimeOffset=x.pts-x.dts,k.duration=x.duration,k.size=4*x.length,k.size+=x.byteLength,x.keyFrame&&(k.flags.dependsOn=2,k.flags.isNonSyncSample=0),k},Ze=function(x,A){var k,C,N,U,ie,ne=A||0,oe=[];for(k=0;krt.ONE_SECOND_IN_TS/2))){for(fe=Ni()[x.samplerate],fe||(fe=A[0].data),_e=0;_e=k?x:(A.minSegmentDts=1/0,x.filter(function(C){return C.dts>=k?(A.minSegmentDts=Math.min(A.minSegmentDts,C.dts),A.minSegmentPts=A.minSegmentDts,!0):!1}))},mi=function(x){var A,k,C=[];for(A=0;A=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(x),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},si.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},si.prototype.addText=function(x){this.rows[this.rowIdx]+=x},si.prototype.backspace=function(){if(!this.isEmpty()){var x=this.rows[this.rowIdx];this.rows[this.rowIdx]=x.substr(0,x.length-1)}};var Gt=function(x,A,k){this.serviceNum=x,this.text="",this.currentWindow=new si(-1),this.windows=[],this.stream=k,typeof A=="string"&&this.createTextDecoder(A)};Gt.prototype.init=function(x,A){this.startPts=x;for(var k=0;k<8;k++)this.windows[k]=new si(k),typeof A=="function"&&(this.windows[k].beforeRowOverflow=A)},Gt.prototype.setCurrentWindow=function(x){this.currentWindow=this.windows[x]},Gt.prototype.createTextDecoder=function(x){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(x)}catch(A){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+x+" encoding. "+A})}};var Xt=function(x){x=x||{},Xt.prototype.init.call(this);var A=this,k=x.captionServices||{},C={},N;Object.keys(k).forEach(U=>{N=k[U],/^SERVICE/.test(U)&&(C[U]=N.encoding)}),this.serviceEncodings=C,this.current708Packet=null,this.services={},this.push=function(U){U.type===3?(A.new708Packet(),A.add708Bytes(U)):(A.current708Packet===null&&A.new708Packet(),A.add708Bytes(U))}};Xt.prototype=new Ui,Xt.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Xt.prototype.add708Bytes=function(x){var A=x.ccData,k=A>>>8,C=A&255;this.current708Packet.ptsVals.push(x.pts),this.current708Packet.data.push(k),this.current708Packet.data.push(C)},Xt.prototype.push708Packet=function(){var x=this.current708Packet,A=x.data,k=null,C=null,N=0,U=A[N++];for(x.seq=U>>6,x.sizeCode=U&63;N>5,C=U&31,k===7&&C>0&&(U=A[N++],k=U),this.pushServiceBlock(k,N,C),C>0&&(N+=C-1)},Xt.prototype.pushServiceBlock=function(x,A,k){var C,N=A,U=this.current708Packet.data,ie=this.services[x];for(ie||(ie=this.initService(x,N));N("0"+(Ct&255).toString(16)).slice(-2)).join("")}if(N?(je=[ne,oe],x++):je=[ne],A.textDecoder_&&!C)_e=A.textDecoder_.decode(new Uint8Array(je));else if(N){const Ke=xt(je);_e=String.fromCharCode(parseInt(Ke,16))}else _e=Yi(ie|ne);return fe.pendingNewLine&&!fe.isEmpty()&&fe.newLine(this.getPts(x)),fe.pendingNewLine=!1,fe.addText(_e),x},Xt.prototype.multiByteCharacter=function(x,A){var k=this.current708Packet.data,C=k[x+1],N=k[x+2];return zi(C)&&zi(N)&&(x=this.handleText(++x,A,{isMultiByte:!0})),x},Xt.prototype.setCurrentWindow=function(x,A){var k=this.current708Packet.data,C=k[x],N=C&7;return A.setCurrentWindow(N),x},Xt.prototype.defineWindow=function(x,A){var k=this.current708Packet.data,C=k[x],N=C&7;A.setCurrentWindow(N);var U=A.currentWindow;return C=k[++x],U.visible=(C&32)>>5,U.rowLock=(C&16)>>4,U.columnLock=(C&8)>>3,U.priority=C&7,C=k[++x],U.relativePositioning=(C&128)>>7,U.anchorVertical=C&127,C=k[++x],U.anchorHorizontal=C,C=k[++x],U.anchorPoint=(C&240)>>4,U.rowCount=C&15,C=k[++x],U.columnCount=C&63,C=k[++x],U.windowStyle=(C&56)>>3,U.penStyle=C&7,U.virtualRowCount=U.rowCount+1,x},Xt.prototype.setWindowAttributes=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.winAttr;return C=k[++x],N.fillOpacity=(C&192)>>6,N.fillRed=(C&48)>>4,N.fillGreen=(C&12)>>2,N.fillBlue=C&3,C=k[++x],N.borderType=(C&192)>>6,N.borderRed=(C&48)>>4,N.borderGreen=(C&12)>>2,N.borderBlue=C&3,C=k[++x],N.borderType+=(C&128)>>5,N.wordWrap=(C&64)>>6,N.printDirection=(C&48)>>4,N.scrollDirection=(C&12)>>2,N.justify=C&3,C=k[++x],N.effectSpeed=(C&240)>>4,N.effectDirection=(C&12)>>2,N.displayEffect=C&3,x},Xt.prototype.flushDisplayed=function(x,A){for(var k=[],C=0;C<8;C++)A.windows[C].visible&&!A.windows[C].isEmpty()&&k.push(A.windows[C].getText());A.endPts=x,A.text=k.join(` + +`),this.pushCaption(A),A.startPts=x},Xt.prototype.pushCaption=function(x){x.text!==""&&(this.trigger("data",{startPts:x.startPts,endPts:x.endPts,text:x.text,stream:"cc708_"+x.serviceNum}),x.text="",x.startPts=x.endPts)},Xt.prototype.displayWindows=function(x,A){var k=this.current708Packet.data,C=k[++x],N=this.getPts(x);this.flushDisplayed(N,A);for(var U=0;U<8;U++)C&1<>4,N.offset=(C&12)>>2,N.penSize=C&3,C=k[++x],N.italics=(C&128)>>7,N.underline=(C&64)>>6,N.edgeType=(C&56)>>3,N.fontStyle=C&7,x},Xt.prototype.setPenColor=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.penColor;return C=k[++x],N.fgOpacity=(C&192)>>6,N.fgRed=(C&48)>>4,N.fgGreen=(C&12)>>2,N.fgBlue=C&3,C=k[++x],N.bgOpacity=(C&192)>>6,N.bgRed=(C&48)>>4,N.bgGreen=(C&12)>>2,N.bgBlue=C&3,C=k[++x],N.edgeRed=(C&48)>>4,N.edgeGreen=(C&12)>>2,N.edgeBlue=C&3,x},Xt.prototype.setPenLocation=function(x,A){var k=this.current708Packet.data,C=k[x],N=A.currentWindow.penLoc;return A.currentWindow.pendingNewLine=!0,C=k[++x],N.row=C&15,C=k[++x],N.column=C&63,x},Xt.prototype.reset=function(x,A){var k=this.getPts(x);return this.flushDisplayed(k,A),this.initService(A.serviceNum,x)};var ys={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},ms=function(x){return x===null?"":(x=ys[x]||x,String.fromCharCode(x))},vn=14,Mn=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],vs=function(){for(var x=[],A=vn+1;A--;)x.push({text:"",indent:0,offset:0});return x},Ti=function(x,A){Ti.prototype.init.call(this),this.field_=x||0,this.dataChannel_=A||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(k){var C,N,U,ie,ne;if(C=k.ccData&32639,C===this.lastControlCode_){this.lastControlCode_=null;return}if((C&61440)===4096?this.lastControlCode_=C:C!==this.PADDING_&&(this.lastControlCode_=null),U=C>>>8,ie=C&255,C!==this.PADDING_)if(C===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(C===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(k.pts),this.flushDisplayed(k.pts),N=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=N,this.startPts_=k.pts;else if(C===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(k.pts);else if(C===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(k.pts);else if(C===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(k.pts);else if(C===this.CARRIAGE_RETURN_)this.clearFormatting(k.pts),this.flushDisplayed(k.pts),this.shiftRowsUp_(),this.startPts_=k.pts;else if(C===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(C===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(k.pts),this.displayed_=vs();else if(C===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=vs();else if(C===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(k.pts),this.displayed_=vs()),this.mode_="paintOn",this.startPts_=k.pts;else if(this.isSpecialCharacter(U,ie))U=(U&3)<<8,ne=ms(U|ie),this[this.mode_](k.pts,ne),this.column_++;else if(this.isExtCharacter(U,ie))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),U=(U&3)<<8,ne=ms(U|ie),this[this.mode_](k.pts,ne),this.column_++;else if(this.isMidRowCode(U,ie))this.clearFormatting(k.pts),this[this.mode_](k.pts," "),this.column_++,(ie&14)===14&&this.addFormatting(k.pts,["i"]),(ie&1)===1&&this.addFormatting(k.pts,["u"]);else if(this.isOffsetControlCode(U,ie)){const fe=ie&3;this.nonDisplayed_[this.row_].offset=fe,this.column_+=fe}else if(this.isPAC(U,ie)){var oe=Mn.indexOf(C&7968);if(this.mode_==="rollUp"&&(oe-this.rollUpRows_+1<0&&(oe=this.rollUpRows_-1),this.setRollUp(k.pts,oe)),oe!==this.row_&&oe>=0&&oe<=14&&(this.clearFormatting(k.pts),this.row_=oe),ie&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(k.pts,["u"]),(C&16)===16){const fe=(C&14)>>1;this.column_=fe*4,this.nonDisplayed_[this.row_].indent+=fe}this.isColorPAC(ie)&&(ie&14)===14&&this.addFormatting(k.pts,["i"])}else this.isNormalChar(U)&&(ie===0&&(ie=null),ne=ms(U),ne+=ms(ie),this[this.mode_](k.pts,ne),this.column_+=ne.length)}};Ti.prototype=new Ui,Ti.prototype.flushDisplayed=function(x){const A=C=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+C+"."})},k=[];this.displayed_.forEach((C,N)=>{if(C&&C.text&&C.text.length){try{C.text=C.text.trim()}catch{A(N)}C.text.length&&k.push({text:C.text,line:N+1,position:10+Math.min(70,C.indent*10)+C.offset*2.5})}else C==null&&A(N)}),k.length&&this.trigger("data",{startPts:this.startPts_,endPts:x,content:k,stream:this.name_})},Ti.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=vs(),this.nonDisplayed_=vs(),this.lastControlCode_=null,this.column_=0,this.row_=vn,this.rollUpRows_=2,this.formatting_=[]},Ti.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},Ti.prototype.isSpecialCharacter=function(x,A){return x===this.EXT_&&A>=48&&A<=63},Ti.prototype.isExtCharacter=function(x,A){return(x===this.EXT_+1||x===this.EXT_+2)&&A>=32&&A<=63},Ti.prototype.isMidRowCode=function(x,A){return x===this.EXT_&&A>=32&&A<=47},Ti.prototype.isOffsetControlCode=function(x,A){return x===this.OFFSET_&&A>=33&&A<=35},Ti.prototype.isPAC=function(x,A){return x>=this.BASE_&&x=64&&A<=127},Ti.prototype.isColorPAC=function(x){return x>=64&&x<=79||x>=96&&x<=127},Ti.prototype.isNormalChar=function(x){return x>=32&&x<=127},Ti.prototype.setRollUp=function(x,A){if(this.mode_!=="rollUp"&&(this.row_=vn,this.mode_="rollUp",this.flushDisplayed(x),this.nonDisplayed_=vs(),this.displayed_=vs()),A!==void 0&&A!==this.row_)for(var k=0;k"},"");this[this.mode_](x,k)},Ti.prototype.clearFormatting=function(x){if(this.formatting_.length){var A=this.formatting_.reverse().reduce(function(k,C){return k+""},"");this.formatting_=[],this[this.mode_](x,A)}},Ti.prototype.popOn=function(x,A){var k=this.nonDisplayed_[this.row_].text;k+=A,this.nonDisplayed_[this.row_].text=k},Ti.prototype.rollUp=function(x,A){var k=this.displayed_[this.row_].text;k+=A,this.displayed_[this.row_].text=k},Ti.prototype.shiftRowsUp_=function(){var x;for(x=0;xA&&(k=-1);Math.abs(A-x)>Pi;)x+=k*bs;return x},tn=function(x){var A,k;tn.prototype.init.call(this),this.type_=x||Ts,this.push=function(C){if(C.type==="metadata"){this.trigger("data",C);return}this.type_!==Ts&&C.type!==this.type_||(k===void 0&&(k=C.dts),C.dts=xn(C.dts,k),C.pts=xn(C.pts,k),A=C.dts,this.trigger("data",C))},this.flush=function(){k=A,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){k=void 0,A=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};tn.prototype=new Us;var sn={TimestampRolloverStream:tn,handleRollover:xn},Or=(x,A,k)=>{if(!x)return-1;for(var C=k;C";x.data[0]===bn.Utf8&&(k=js(x.data,0,A),!(k<0)&&(x.mimeType=me(x.data,A,k),A=k+1,x.pictureType=x.data[A],A++,C=js(x.data,0,A),!(C<0)&&(x.description=Bi(x.data,A,C),A=C+1,x.mimeType===N?x.url=me(x.data,A,x.data.length):x.pictureData=x.data.subarray(A,x.data.length))))},"T*":function(x){x.data[0]===bn.Utf8&&(x.value=Bi(x.data,1,x.data.length).replace(/\0*$/,""),x.values=x.value.split("\0"))},TXXX:function(x){var A;x.data[0]===bn.Utf8&&(A=js(x.data,0,1),A!==-1&&(x.description=Bi(x.data,1,A),x.value=Bi(x.data,A+1,x.data.length).replace(/\0*$/,""),x.data=x.value))},"W*":function(x){x.url=me(x.data,0,x.data.length).replace(/\0.*$/,"")},WXXX:function(x){var A;x.data[0]===bn.Utf8&&(A=js(x.data,0,1),A!==-1&&(x.description=Bi(x.data,1,A),x.url=me(x.data,A+1,x.data.length).replace(/\0.*$/,"")))},PRIV:function(x){var A;for(A=0;A>>2;Ct*=4,Ct+=Ke[7]&3,_e.timeStamp=Ct,ne.pts===void 0&&ne.dts===void 0&&(ne.pts=_e.timeStamp,ne.dts=_e.timeStamp),this.trigger("timestamp",_e)}ne.frames.push(_e),oe+=10,oe+=fe}while(oe>>4>1&&(ie+=N[ie]+1),U.pid===0)U.type="pat",x(N.subarray(ie),U),this.trigger("data",U);else if(U.pid===this.pmtPid)for(U.type="pmt",x(N.subarray(ie),U),this.trigger("data",U);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([N,ie,U]):this.processPes_(N,ie,U)},this.processPes_=function(N,U,ie){ie.pid===this.programMapTable.video?ie.streamType=li.H264_STREAM_TYPE:ie.pid===this.programMapTable.audio?ie.streamType=li.ADTS_STREAM_TYPE:ie.streamType=this.programMapTable["timed-metadata"][ie.pid],ie.type="pes",ie.data=N.subarray(U),this.trigger("data",ie)}},rn.prototype=new Gi,rn.STREAM_TYPES={h264:27,adts:15},Bn=function(){var x=this,A=!1,k={data:[],size:0},C={data:[],size:0},N={data:[],size:0},U,ie=function(oe,fe){var _e;const je=oe[0]<<16|oe[1]<<8|oe[2];fe.data=new Uint8Array,je===1&&(fe.packetLength=6+(oe[4]<<8|oe[5]),fe.dataAlignmentIndicator=(oe[6]&4)!==0,_e=oe[7],_e&192&&(fe.pts=(oe[9]&14)<<27|(oe[10]&255)<<20|(oe[11]&254)<<12|(oe[12]&255)<<5|(oe[13]&254)>>>3,fe.pts*=4,fe.pts+=(oe[13]&6)>>>1,fe.dts=fe.pts,_e&64&&(fe.dts=(oe[14]&14)<<27|(oe[15]&255)<<20|(oe[16]&254)<<12|(oe[17]&255)<<5|(oe[18]&254)>>>3,fe.dts*=4,fe.dts+=(oe[18]&6)>>>1)),fe.data=oe.subarray(9+oe[8]))},ne=function(oe,fe,_e){var je=new Uint8Array(oe.size),xt={type:fe},Ke=0,Ct=0,ri=!1,$s;if(!(!oe.data.length||oe.size<9)){for(xt.trackId=oe.data[0].pid,Ke=0;Ke>5,oe=((A[N+6]&3)+1)*1024,fe=oe*ke/Be[(A[N+2]&60)>>>2],A.byteLength-N>>6&3)+1,channelcount:(A[N+2]&1)<<2|(A[N+3]&192)>>>6,samplerate:Be[(A[N+2]&60)>>>2],samplingfrequencyindex:(A[N+2]&60)>>>2,samplesize:16,data:A.subarray(N+7+ie,N+U)}),k++,N+=U}typeof _e=="number"&&(this.skipWarn_(_e,N),_e=null),A=A.subarray(N)}},this.flush=function(){k=0,this.trigger("done")},this.reset=function(){A=void 0,this.trigger("reset")},this.endTimeline=function(){A=void 0,this.trigger("endedtimeline")}},De.prototype=new ce;var et=De,ct;ct=function(x){var A=x.byteLength,k=0,C=0;this.length=function(){return 8*A},this.bitsAvailable=function(){return 8*A+C},this.loadWord=function(){var N=x.byteLength-A,U=new Uint8Array(4),ie=Math.min(4,A);if(ie===0)throw new Error("no bytes available");U.set(x.subarray(N,N+ie)),k=new DataView(U.buffer).getUint32(0),C=ie*8,A-=ie},this.skipBits=function(N){var U;C>N?(k<<=N,C-=N):(N-=C,U=Math.floor(N/8),N-=U*8,A-=U,this.loadWord(),k<<=N,C-=N)},this.readBits=function(N){var U=Math.min(C,N),ie=k>>>32-U;return C-=U,C>0?k<<=U:A>0&&this.loadWord(),U=N-U,U>0?ie<>>N)!==0)return k<<=N,C-=N,N;return this.loadWord(),N+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var N=this.skipLeadingZeros();return this.readBits(N+1)-1},this.readExpGolomb=function(){var N=this.readUnsignedExpGolomb();return 1&N?1+N>>>1:-1*(N>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var $e=ct,it=t,vt=$e,Tt,St,Rt;St=function(){var x=0,A,k;St.prototype.init.call(this),this.push=function(C){var N;k?(N=new Uint8Array(k.byteLength+C.data.byteLength),N.set(k),N.set(C.data,k.byteLength),k=N):k=C.data;for(var U=k.byteLength;x3&&this.trigger("data",k.subarray(x+3)),k=null,x=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},St.prototype=new it,Rt={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Tt=function(){var x=new St,A,k,C,N,U,ie,ne;Tt.prototype.init.call(this),A=this,this.push=function(oe){oe.type==="video"&&(k=oe.trackId,C=oe.pts,N=oe.dts,x.push(oe))},x.on("data",function(oe){var fe={trackId:k,pts:C,dts:N,data:oe,nalUnitTypeCode:oe[0]&31};switch(fe.nalUnitTypeCode){case 5:fe.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:fe.nalUnitType="sei_rbsp",fe.escapedRBSP=U(oe.subarray(1));break;case 7:fe.nalUnitType="seq_parameter_set_rbsp",fe.escapedRBSP=U(oe.subarray(1)),fe.config=ie(fe.escapedRBSP);break;case 8:fe.nalUnitType="pic_parameter_set_rbsp";break;case 9:fe.nalUnitType="access_unit_delimiter_rbsp";break}A.trigger("data",fe)}),x.on("done",function(){A.trigger("done")}),x.on("partialdone",function(){A.trigger("partialdone")}),x.on("reset",function(){A.trigger("reset")}),x.on("endedtimeline",function(){A.trigger("endedtimeline")}),this.flush=function(){x.flush()},this.partialFlush=function(){x.partialFlush()},this.reset=function(){x.reset()},this.endTimeline=function(){x.endTimeline()},ne=function(oe,fe){var _e=8,je=8,xt,Ke;for(xt=0;xt>4;return k=k>=0?k:0,N?k+20:k+10},wi=function(x,A){return x.length-A<10||x[A]!==73||x[A+1]!==68||x[A+2]!==51?A:(A+=Vt(x,A),wi(x,A))},Ys=function(x){var A=wi(x,0);return x.length>=A+2&&(x[A]&255)===255&&(x[A+1]&240)===240&&(x[A+1]&22)===16},ts=function(x){return x[0]<<21|x[1]<<14|x[2]<<7|x[3]},Mt=function(x,A,k){var C,N="";for(C=A;C>5,C=x[A+4]<<3,N=x[A+3]&6144;return N|C|k},Wn=function(x,A){return x[A]===73&&x[A+1]===68&&x[A+2]===51?"timed-metadata":x[A]&!0&&(x[A+1]&240)===240?"audio":null},ca=function(x){for(var A=0;A+5>>2]}return null},ls=function(x){var A,k,C,N;A=10,x[5]&64&&(A+=4,A+=ts(x.subarray(10,14)));do{if(k=ts(x.subarray(A+4,A+8)),k<1)return null;if(N=String.fromCharCode(x[A],x[A+1],x[A+2],x[A+3]),N==="PRIV"){C=x.subarray(A+10,A+k+10);for(var U=0;U>>2;return oe*=4,oe+=ne[7]&3,oe}break}}A+=10,A+=k}while(A=3;){if(x[N]===73&&x[N+1]===68&&x[N+2]===51){if(x.length-N<10||(C=da.parseId3TagSize(x,N),N+C>x.length))break;ie={type:"timed-metadata",data:x.subarray(N,N+C)},this.trigger("data",ie),N+=C;continue}else if((x[N]&255)===255&&(x[N+1]&240)===240){if(x.length-N<7||(C=da.parseAdtsSize(x,N),N+C>x.length))break;ne={type:"audio",data:x.subarray(N,N+C),pts:A,dts:A},this.trigger("data",ne),N+=C;continue}N++}U=x.length-N,U>0?x=x.subarray(N):x=new Uint8Array},this.reset=function(){x=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){x=new Uint8Array,this.trigger("endedtimeline")}},ha.prototype=new pr;var Tu=ha,Wh=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],b0=Wh,T0=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],_0=T0,ko=t,Dl=Ee,Ll=wt,_u=Oi,gr=te,Qr=q,Rl=Ut,Yh=et,S0=gi.H264Stream,E0=Tu,w0=Cs.isLikelyAacData,Zc=Ut.ONE_SECOND_IN_TS,Xh=b0,Qh=_0,Su,Do,Eu,Ka,A0=function(x,A){A.stream=x,this.trigger("log",A)},Zh=function(x,A){for(var k=Object.keys(A),C=0;C=-1e4&&_e<=oe&&(!je||fe>_e)&&(je=Ke,fe=_e)));return je?je.gop:null},this.alignGopsAtStart_=function(ne){var oe,fe,_e,je,xt,Ke,Ct,ri;for(xt=ne.byteLength,Ke=ne.nalCount,Ct=ne.duration,oe=fe=0;oe_e.pts){oe++;continue}fe++,xt-=je.byteLength,Ke-=je.nalCount,Ct-=je.duration}return fe===0?ne:fe===ne.length?null:(ri=ne.slice(fe),ri.byteLength=xt,ri.duration=Ct,ri.nalCount=Ke,ri.pts=ri[0].pts,ri.dts=ri[0].dts,ri)},this.alignGopsAtEnd_=function(ne){var oe,fe,_e,je,xt,Ke;for(oe=N.length-1,fe=ne.length-1,xt=null,Ke=!1;oe>=0&&fe>=0;){if(_e=N[oe],je=ne[fe],_e.pts===je.pts){Ke=!0;break}if(_e.pts>je.pts){oe--;continue}oe===N.length-1&&(xt=fe),fe--}if(!Ke&&xt===null)return null;var Ct;if(Ke?Ct=fe:Ct=xt,Ct===0)return ne;var ri=ne.slice(Ct),$s=ri.reduce(function(Fn,ba){return Fn.byteLength+=ba.byteLength,Fn.duration+=ba.duration,Fn.nalCount+=ba.nalCount,Fn},{byteLength:0,duration:0,nalCount:0});return ri.byteLength=$s.byteLength,ri.duration=$s.duration,ri.nalCount=$s.nalCount,ri.pts=ri[0].pts,ri.dts=ri[0].dts,ri},this.alignGopsWith=function(ne){N=ne}},Su.prototype=new ko,Ka=function(x,A){this.numberOfTracks=0,this.metadataStream=A,x=x||{},typeof x.remux<"u"?this.remuxTracks=!!x.remux:this.remuxTracks=!0,typeof x.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=x.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Ka.prototype.init.call(this),this.push=function(k){if(k.content||k.text)return this.pendingCaptions.push(k);if(k.frames)return this.pendingMetadata.push(k);this.pendingTracks.push(k.track),this.pendingBytes+=k.boxes.byteLength,k.track.type==="video"&&(this.videoTrack=k.track,this.pendingBoxes.push(k.boxes)),k.track.type==="audio"&&(this.audioTrack=k.track,this.pendingBoxes.unshift(k.boxes))}},Ka.prototype=new ko,Ka.prototype.flush=function(x){var A=0,k={captions:[],captionStreams:{},metadata:[],info:{}},C,N,U,ie=0,ne;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(ie=this.videoTrack.timelineStartInfo.pts,Qh.forEach(function(oe){k.info[oe]=this.videoTrack[oe]},this)):this.audioTrack&&(ie=this.audioTrack.timelineStartInfo.pts,Xh.forEach(function(oe){k.info[oe]=this.audioTrack[oe]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?k.type=this.pendingTracks[0].type:k.type="combined",this.emittedTracks+=this.pendingTracks.length,U=Dl.initSegment(this.pendingTracks),k.initSegment=new Uint8Array(U.byteLength),k.initSegment.set(U),k.data=new Uint8Array(this.pendingBytes),ne=0;ne=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Ka.prototype.setRemux=function(x){this.remuxTracks=x},Eu=function(x){var A=this,k=!0,C,N;Eu.prototype.init.call(this),x=x||{},this.baseMediaDecodeTime=x.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var U={};this.transmuxPipeline_=U,U.type="aac",U.metadataStream=new Qr.MetadataStream,U.aacStream=new E0,U.audioTimestampRolloverStream=new Qr.TimestampRolloverStream("audio"),U.timedMetadataTimestampRolloverStream=new Qr.TimestampRolloverStream("timed-metadata"),U.adtsStream=new Yh,U.coalesceStream=new Ka(x,U.metadataStream),U.headOfPipeline=U.aacStream,U.aacStream.pipe(U.audioTimestampRolloverStream).pipe(U.adtsStream),U.aacStream.pipe(U.timedMetadataTimestampRolloverStream).pipe(U.metadataStream).pipe(U.coalesceStream),U.metadataStream.on("timestamp",function(ie){U.aacStream.setTimestamp(ie.timeStamp)}),U.aacStream.on("data",function(ie){ie.type!=="timed-metadata"&&ie.type!=="audio"||U.audioSegmentStream||(N=N||{timelineStartInfo:{baseMediaDecodeTime:A.baseMediaDecodeTime},codec:"adts",type:"audio"},U.coalesceStream.numberOfTracks++,U.audioSegmentStream=new Do(N,x),U.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),U.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),U.adtsStream.pipe(U.audioSegmentStream).pipe(U.coalesceStream),A.trigger("trackinfo",{hasAudio:!!N,hasVideo:!!C}))}),U.coalesceStream.on("data",this.trigger.bind(this,"data")),U.coalesceStream.on("done",this.trigger.bind(this,"done")),Zh(this,U)},this.setupTsPipeline=function(){var U={};this.transmuxPipeline_=U,U.type="ts",U.metadataStream=new Qr.MetadataStream,U.packetStream=new Qr.TransportPacketStream,U.parseStream=new Qr.TransportParseStream,U.elementaryStream=new Qr.ElementaryStream,U.timestampRolloverStream=new Qr.TimestampRolloverStream,U.adtsStream=new Yh,U.h264Stream=new S0,U.captionStream=new Qr.CaptionStream(x),U.coalesceStream=new Ka(x,U.metadataStream),U.headOfPipeline=U.packetStream,U.packetStream.pipe(U.parseStream).pipe(U.elementaryStream).pipe(U.timestampRolloverStream),U.timestampRolloverStream.pipe(U.h264Stream),U.timestampRolloverStream.pipe(U.adtsStream),U.timestampRolloverStream.pipe(U.metadataStream).pipe(U.coalesceStream),U.h264Stream.pipe(U.captionStream).pipe(U.coalesceStream),U.elementaryStream.on("data",function(ie){var ne;if(ie.type==="metadata"){for(ne=ie.tracks.length;ne--;)!C&&ie.tracks[ne].type==="video"?(C=ie.tracks[ne],C.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime):!N&&ie.tracks[ne].type==="audio"&&(N=ie.tracks[ne],N.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime);C&&!U.videoSegmentStream&&(U.coalesceStream.numberOfTracks++,U.videoSegmentStream=new Su(C,x),U.videoSegmentStream.on("log",A.getLogTrigger_("videoSegmentStream")),U.videoSegmentStream.on("timelineStartInfo",function(oe){N&&!x.keepOriginalTimestamps&&(N.timelineStartInfo=oe,U.audioSegmentStream.setEarliestDts(oe.dts-A.baseMediaDecodeTime))}),U.videoSegmentStream.on("processedGopsInfo",A.trigger.bind(A,"gopInfo")),U.videoSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"videoSegmentTimingInfo")),U.videoSegmentStream.on("baseMediaDecodeTime",function(oe){N&&U.audioSegmentStream.setVideoBaseMediaDecodeTime(oe)}),U.videoSegmentStream.on("timingInfo",A.trigger.bind(A,"videoTimingInfo")),U.h264Stream.pipe(U.videoSegmentStream).pipe(U.coalesceStream)),N&&!U.audioSegmentStream&&(U.coalesceStream.numberOfTracks++,U.audioSegmentStream=new Do(N,x),U.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),U.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),U.audioSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"audioSegmentTimingInfo")),U.adtsStream.pipe(U.audioSegmentStream).pipe(U.coalesceStream)),A.trigger("trackinfo",{hasAudio:!!N,hasVideo:!!C})}}),U.coalesceStream.on("data",this.trigger.bind(this,"data")),U.coalesceStream.on("id3Frame",function(ie){ie.dispatchType=U.metadataStream.dispatchType,A.trigger("id3Frame",ie)}),U.coalesceStream.on("caption",this.trigger.bind(this,"caption")),U.coalesceStream.on("done",this.trigger.bind(this,"done")),Zh(this,U)},this.setBaseMediaDecodeTime=function(U){var ie=this.transmuxPipeline_;x.keepOriginalTimestamps||(this.baseMediaDecodeTime=U),N&&(N.timelineStartInfo.dts=void 0,N.timelineStartInfo.pts=void 0,gr.clearDtsInfo(N),ie.audioTimestampRolloverStream&&ie.audioTimestampRolloverStream.discontinuity()),C&&(ie.videoSegmentStream&&(ie.videoSegmentStream.gopCache_=[]),C.timelineStartInfo.dts=void 0,C.timelineStartInfo.pts=void 0,gr.clearDtsInfo(C),ie.captionStream.reset()),ie.timestampRolloverStream&&ie.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(U){N&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(U)},this.setRemux=function(U){var ie=this.transmuxPipeline_;x.remux=U,ie&&ie.coalesceStream&&ie.coalesceStream.setRemux(U)},this.alignGopsWith=function(U){C&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(U)},this.getLogTrigger_=function(U){var ie=this;return function(ne){ne.stream=U,ie.trigger("log",ne)}},this.push=function(U){if(k){var ie=w0(U);ie&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!ie&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),k=!1}this.transmuxPipeline_.headOfPipeline.push(U)},this.flush=function(){k=!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()}},Eu.prototype=new ko;var C0={Transmuxer:Eu},k0=function(x){return x>>>0},D0=function(x){return("00"+x.toString(16)).slice(-2)},Lo={toUnsigned:k0,toHexString:D0},Il=function(x){var A="";return A+=String.fromCharCode(x[0]),A+=String.fromCharCode(x[1]),A+=String.fromCharCode(x[2]),A+=String.fromCharCode(x[3]),A},tf=Il,sf=Lo.toUnsigned,nf=tf,Jc=function(x,A){var k=[],C,N,U,ie,ne;if(!A.length)return null;for(C=0;C1?C+N:x.byteLength,U===A[0]&&(A.length===1?k.push(x.subarray(C+8,ie)):(ne=Jc(x.subarray(C+8,ie),A.slice(1)),ne.length&&(k=k.concat(ne)))),C=ie;return k},wu=Jc,rf=Lo.toUnsigned,Ro=r.getUint64,L0=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4))};return A.version===1?A.baseMediaDecodeTime=Ro(x.subarray(4)):A.baseMediaDecodeTime=rf(x[4]<<24|x[5]<<16|x[6]<<8|x[7]),A},ed=L0,R0=function(x){var A=new DataView(x.buffer,x.byteOffset,x.byteLength),k={version:x[0],flags:new Uint8Array(x.subarray(1,4)),trackId:A.getUint32(4)},C=k.flags[2]&1,N=k.flags[2]&2,U=k.flags[2]&8,ie=k.flags[2]&16,ne=k.flags[2]&32,oe=k.flags[0]&65536,fe=k.flags[0]&131072,_e;return _e=8,C&&(_e+=4,k.baseDataOffset=A.getUint32(12),_e+=4),N&&(k.sampleDescriptionIndex=A.getUint32(_e),_e+=4),U&&(k.defaultSampleDuration=A.getUint32(_e),_e+=4),ie&&(k.defaultSampleSize=A.getUint32(_e),_e+=4),ne&&(k.defaultSampleFlags=A.getUint32(_e)),oe&&(k.durationIsEmpty=!0),!C&&fe&&(k.baseDataOffsetIsMoof=!0),k},td=R0,af=function(x){return{isLeading:(x[0]&12)>>>2,dependsOn:x[0]&3,isDependedOn:(x[1]&192)>>>6,hasRedundancy:(x[1]&48)>>>4,paddingValue:(x[1]&14)>>>1,isNonSyncSample:x[1]&1,degradationPriority:x[2]<<8|x[3]}},Nl=af,Io=Nl,I0=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4)),samples:[]},k=new DataView(x.buffer,x.byteOffset,x.byteLength),C=A.flags[2]&1,N=A.flags[2]&4,U=A.flags[1]&1,ie=A.flags[1]&2,ne=A.flags[1]&4,oe=A.flags[1]&8,fe=k.getUint32(4),_e=8,je;for(C&&(A.dataOffset=k.getInt32(_e),_e+=4),N&&fe&&(je={flags:Io(x.subarray(_e,_e+4))},_e+=4,U&&(je.duration=k.getUint32(_e),_e+=4),ie&&(je.size=k.getUint32(_e),_e+=4),oe&&(A.version===1?je.compositionTimeOffset=k.getInt32(_e):je.compositionTimeOffset=k.getUint32(_e),_e+=4),A.samples.push(je),fe--);fe--;)je={},U&&(je.duration=k.getUint32(_e),_e+=4),ie&&(je.size=k.getUint32(_e),_e+=4),ne&&(je.flags=Io(x.subarray(_e,_e+4)),_e+=4),oe&&(A.version===1?je.compositionTimeOffset=k.getInt32(_e):je.compositionTimeOffset=k.getUint32(_e),_e+=4),A.samples.push(je);return A},Ol=I0,id={tfdt:ed,trun:Ol},sd={parseTfdt:id.tfdt,parseTrun:id.trun},nd=function(x){for(var A=0,k=String.fromCharCode(x[A]),C="";k!=="\0";)C+=k,A++,k=String.fromCharCode(x[A]);return C+=k,C},rd={uint8ToCString:nd},Ml=rd.uint8ToCString,of=r.getUint64,lf=function(x){var A=4,k=x[0],C,N,U,ie,ne,oe,fe,_e;if(k===0){C=Ml(x.subarray(A)),A+=C.length,N=Ml(x.subarray(A)),A+=N.length;var je=new DataView(x.buffer);U=je.getUint32(A),A+=4,ne=je.getUint32(A),A+=4,oe=je.getUint32(A),A+=4,fe=je.getUint32(A),A+=4}else if(k===1){var je=new DataView(x.buffer);U=je.getUint32(A),A+=4,ie=of(x.subarray(A)),A+=8,oe=je.getUint32(A),A+=4,fe=je.getUint32(A),A+=4,C=Ml(x.subarray(A)),A+=C.length,N=Ml(x.subarray(A)),A+=N.length}_e=new Uint8Array(x.subarray(A,x.byteLength));var xt={scheme_id_uri:C,value:N,timescale:U||1,presentation_time:ie,presentation_time_delta:ne,event_duration:oe,id:fe,message_data:_e};return O0(k,xt)?xt:void 0},N0=function(x,A,k,C){return x||x===0?x/A:C+k/A},O0=function(x,A){var k=A.scheme_id_uri!=="\0",C=x===0&&uf(A.presentation_time_delta)&&k,N=x===1&&uf(A.presentation_time)&&k;return!(x>1)&&C||N},uf=function(x){return x!==void 0||x!==null},M0={parseEmsgBox:lf,scaleTime:N0},Pl;typeof window<"u"?Pl=window:typeof s<"u"?Pl=s:typeof self<"u"?Pl=self:Pl={};var kn=Pl,fa=Lo.toUnsigned,No=Lo.toHexString,_s=wu,Wa=tf,Au=M0,ad=td,P0=Ol,Oo=ed,od=r.getUint64,Mo,Cu,ld,ma,Ya,Bl,ud,Zr=kn,cf=Qe.parseId3Frames;Mo=function(x){var A={},k=_s(x,["moov","trak"]);return k.reduce(function(C,N){var U,ie,ne,oe,fe;return U=_s(N,["tkhd"])[0],!U||(ie=U[0],ne=ie===0?12:20,oe=fa(U[ne]<<24|U[ne+1]<<16|U[ne+2]<<8|U[ne+3]),fe=_s(N,["mdia","mdhd"])[0],!fe)?null:(ie=fe[0],ne=ie===0?12:20,C[oe]=fa(fe[ne]<<24|fe[ne+1]<<16|fe[ne+2]<<8|fe[ne+3]),C)},A)},Cu=function(x,A){var k;k=_s(A,["moof","traf"]);var C=k.reduce(function(N,U){var ie=_s(U,["tfhd"])[0],ne=fa(ie[4]<<24|ie[5]<<16|ie[6]<<8|ie[7]),oe=x[ne]||9e4,fe=_s(U,["tfdt"])[0],_e=new DataView(fe.buffer,fe.byteOffset,fe.byteLength),je;fe[0]===1?je=od(fe.subarray(4,12)):je=_e.getUint32(4);let xt;return typeof je=="bigint"?xt=je/Zr.BigInt(oe):typeof je=="number"&&!isNaN(je)&&(xt=je/oe),xt11?(N.codec+=".",N.codec+=No(Ke[9]),N.codec+=No(Ke[10]),N.codec+=No(Ke[11])):N.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(N.codec)?(Ke=xt.subarray(28),Ct=Wa(Ke.subarray(4,8)),Ct==="esds"&&Ke.length>20&&Ke[19]!==0?(N.codec+="."+No(Ke[19]),N.codec+="."+No(Ke[20]>>>2&63).replace(/^0/,"")):N.codec="mp4a.40.2"):N.codec=N.codec.toLowerCase())}var ri=_s(C,["mdia","mdhd"])[0];ri&&(N.timescale=Bl(ri)),k.push(N)}),k},ud=function(x,A=0){var k=_s(x,["emsg"]);return k.map(C=>{var N=Au.parseEmsgBox(new Uint8Array(C)),U=cf(N.message_data);return{cueTime:Au.scaleTime(N.presentation_time,N.timescale,N.presentation_time_delta,A),duration:Au.scaleTime(N.event_duration,N.timescale),frames:U}})};var Po={findBox:_s,parseType:Wa,timescale:Mo,startTime:Cu,compositionStartTime:ld,videoTrackIds:ma,tracks:Ya,getTimescaleFromMediaHeader:Bl,getEmsgID3:ud};const{parseTrun:df}=sd,{findBox:hf}=Po;var ff=kn,B0=function(x){var A=hf(x,["moof","traf"]),k=hf(x,["mdat"]),C=[];return k.forEach(function(N,U){var ie=A[U];C.push({mdat:N,traf:ie})}),C},mf=function(x,A,k){var C=A,N=k.defaultSampleDuration||0,U=k.defaultSampleSize||0,ie=k.trackId,ne=[];return x.forEach(function(oe){var fe=df(oe),_e=fe.samples;_e.forEach(function(je){je.duration===void 0&&(je.duration=N),je.size===void 0&&(je.size=U),je.trackId=ie,je.dts=C,je.compositionTimeOffset===void 0&&(je.compositionTimeOffset=0),typeof C=="bigint"?(je.pts=C+ff.BigInt(je.compositionTimeOffset),C+=ff.BigInt(je.duration)):(je.pts=C+je.compositionTimeOffset,C+=je.duration)}),ne=ne.concat(_e)}),ne},cd={getMdatTrafPairs:B0,parseSamples:mf},dd=Fi.discardEmulationPreventionBytes,yr=Is.CaptionStream,Bo=wu,Yn=ed,Fo=td,{getMdatTrafPairs:hd,parseSamples:ku}=cd,Du=function(x,A){for(var k=x,C=0;C0?Yn(_e[0]).baseMediaDecodeTime:0,xt=Bo(ie,["trun"]),Ke,Ct;A===fe&&xt.length>0&&(Ke=ku(xt,je,oe),Ct=fd(U,Ke,fe),k[fe]||(k[fe]={seiNals:[],logs:[]}),k[fe].seiNals=k[fe].seiNals.concat(Ct.seiNals),k[fe].logs=k[fe].logs.concat(Ct.logs))}),k},pf=function(x,A,k){var C;if(A===null)return null;C=Xa(x,A);var N=C[A]||{};return{seiNals:N.seiNals,logs:N.logs,timescale:k}},Lu=function(){var x=!1,A,k,C,N,U,ie;this.isInitialized=function(){return x},this.init=function(ne){A=new yr,x=!0,ie=ne?ne.isPartial:!1,A.on("data",function(oe){oe.startTime=oe.startPts/N,oe.endTime=oe.endPts/N,U.captions.push(oe),U.captionStreams[oe.stream]=!0}),A.on("log",function(oe){U.logs.push(oe)})},this.isNewInit=function(ne,oe){return ne&&ne.length===0||oe&&typeof oe=="object"&&Object.keys(oe).length===0?!1:C!==ne[0]||N!==oe[C]},this.parse=function(ne,oe,fe){var _e;if(this.isInitialized()){if(!oe||!fe)return null;if(this.isNewInit(oe,fe))C=oe[0],N=fe[C];else if(C===null||!N)return k.push(ne),null}else return null;for(;k.length>0;){var je=k.shift();this.parse(je,oe,fe)}return _e=pf(ne,C,N),_e&&_e.logs&&(U.logs=U.logs.concat(_e.logs)),_e===null||!_e.seiNals?U.logs.length?{logs:U.logs,captions:[],captionStreams:[]}:null:(this.pushNals(_e.seiNals),this.flushStream(),U)},this.pushNals=function(ne){if(!this.isInitialized()||!ne||ne.length===0)return null;ne.forEach(function(oe){A.push(oe)})},this.flushStream=function(){if(!this.isInitialized())return null;ie?A.partialFlush():A.flush()},this.clearParsedCaptions=function(){U.captions=[],U.captionStreams={},U.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;A.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){k=[],C=null,N=null,U?this.clearParsedCaptions():U={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},Uo=Lu;const{parseTfdt:F0}=sd,Os=wu,{getTimescaleFromMediaHeader:md}=Po,{parseSamples:Jr,getMdatTrafPairs:gf}=cd;var pa=function(){let x=9e4;this.init=function(A){const k=Os(A,["moov","trak","mdia","mdhd"])[0];k&&(x=md(k))},this.parseSegment=function(A){const k=[],C=gf(A);let N=0;return C.forEach(function(U){const ie=U.mdat,ne=U.traf,oe=Os(ne,["tfdt"])[0],fe=Os(ne,["tfhd"])[0],_e=Os(ne,["trun"]);if(oe&&(N=F0(oe).baseMediaDecodeTime),_e.length&&fe){const je=Jr(_e,N,fe);let xt=0;je.forEach(function(Ke){const Ct="utf-8",ri=new TextDecoder(Ct),$s=ie.slice(xt,xt+Ke.size);if(Os($s,["vtte"])[0]){xt+=Ke.size;return}Os($s,["vttc"]).forEach(function($l){const ps=Os($l,["payl"])[0],Qa=Os($l,["sttg"])[0],ea=Ke.pts/x,Ta=(Ke.pts+Ke.duration)/x;let Xi,Br;if(ps)try{Xi=ri.decode(ps)}catch(dn){console.error(dn)}if(Qa)try{Br=ri.decode(Qa)}catch(dn){console.error(dn)}Ke.duration&&Xi&&k.push({cueText:Xi,start:ea,end:Ta,settings:Br})}),xt+=Ke.size})}}),k}},Fl=Ws,gd=function(x){var A=x[1]&31;return A<<=8,A|=x[2],A},jo=function(x){return!!(x[1]&64)},Ul=function(x){var A=0;return(x[3]&48)>>>4>1&&(A+=x[4]+1),A},Xn=function(x,A){var k=gd(x);return k===0?"pat":k===A?"pmt":A?"pes":null},$o=function(x){var A=jo(x),k=4+Ul(x);return A&&(k+=x[k]+1),(x[k+10]&31)<<8|x[k+11]},Ho=function(x){var A={},k=jo(x),C=4+Ul(x);if(k&&(C+=x[C]+1),!!(x[C+5]&1)){var N,U,ie;N=(x[C+1]&15)<<8|x[C+2],U=3+N-4,ie=(x[C+10]&15)<<8|x[C+11];for(var ne=12+ie;ne=x.byteLength)return null;var C=null,N;return N=x[k+7],N&192&&(C={},C.pts=(x[k+9]&14)<<27|(x[k+10]&255)<<20|(x[k+11]&254)<<12|(x[k+12]&255)<<5|(x[k+13]&254)>>>3,C.pts*=4,C.pts+=(x[k+13]&6)>>>1,C.dts=C.pts,N&64&&(C.dts=(x[k+14]&14)<<27|(x[k+15]&255)<<20|(x[k+16]&254)<<12|(x[k+17]&255)<<5|(x[k+18]&254)>>>3,C.dts*=4,C.dts+=(x[k+18]&6)>>>1)),C},Dn=function(x){switch(x){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}},Qn=function(x){for(var A=4+Ul(x),k=x.subarray(A),C=0,N=0,U=!1,ie;N3&&(ie=Dn(k[N+3]&31),ie==="slice_layer_without_partitioning_rbsp_idr"&&(U=!0)),U},ga={parseType:Xn,parsePat:$o,parsePmt:Ho,parsePayloadUnitStartIndicator:jo,parsePesType:Ru,parsePesTime:jl,videoPacketContainsKeyFrame:Qn},vr=Ws,Tn=sn.handleRollover,yi={};yi.ts=ga,yi.aac=Cs;var ya=Ut.ONE_SECOND_IN_TS,an=188,Zn=71,yf=function(x,A){for(var k=0,C=an,N,U;C=0;){if(x[C]===Zn&&(x[N]===Zn||N===x.byteLength)){if(U=x.subarray(C,N),ie=yi.ts.parseType(U,A.pid),ie==="pes"&&(ne=yi.ts.parsePesType(U,A.table),oe=yi.ts.parsePayloadUnitStartIndicator(U),ne==="audio"&&oe&&(fe=yi.ts.parsePesTime(U),fe&&(fe.type="audio",k.audio.push(fe),_e=!0))),_e)break;C-=an,N-=an;continue}C--,N--}},us=function(x,A,k){for(var C=0,N=an,U,ie,ne,oe,fe,_e,je,xt,Ke=!1,Ct={data:[],size:0};N=0;){if(x[C]===Zn&&x[N]===Zn){if(U=x.subarray(C,N),ie=yi.ts.parseType(U,A.pid),ie==="pes"&&(ne=yi.ts.parsePesType(U,A.table),oe=yi.ts.parsePayloadUnitStartIndicator(U),ne==="video"&&oe&&(fe=yi.ts.parsePesTime(U),fe&&(fe.type="video",k.video.push(fe),Ke=!0))),Ke)break;C-=an,N-=an;continue}C--,N--}},Ci=function(x,A){if(x.audio&&x.audio.length){var k=A;(typeof k>"u"||isNaN(k))&&(k=x.audio[0].dts),x.audio.forEach(function(U){U.dts=Tn(U.dts,k),U.pts=Tn(U.pts,k),U.dtsTime=U.dts/ya,U.ptsTime=U.pts/ya})}if(x.video&&x.video.length){var C=A;if((typeof C>"u"||isNaN(C))&&(C=x.video[0].dts),x.video.forEach(function(U){U.dts=Tn(U.dts,C),U.pts=Tn(U.pts,C),U.dtsTime=U.dts/ya,U.ptsTime=U.pts/ya}),x.firstKeyFrame){var N=x.firstKeyFrame;N.dts=Tn(N.dts,C),N.pts=Tn(N.pts,C),N.dtsTime=N.dts/ya,N.ptsTime=N.pts/ya}}},va=function(x){for(var A=!1,k=0,C=null,N=null,U=0,ie=0,ne;x.length-ie>=3;){var oe=yi.aac.parseType(x,ie);switch(oe){case"timed-metadata":if(x.length-ie<10){A=!0;break}if(U=yi.aac.parseId3TagSize(x,ie),U>x.length){A=!0;break}N===null&&(ne=x.subarray(ie,ie+U),N=yi.aac.parseAacTimestamp(ne)),ie+=U;break;case"audio":if(x.length-ie<7){A=!0;break}if(U=yi.aac.parseAdtsSize(x,ie),U>x.length){A=!0;break}C===null&&(ne=x.subarray(ie,ie+U),C=yi.aac.parseSampleRate(ne)),k++,ie+=U;break;default:ie++;break}if(A)return null}if(C===null||N===null)return null;var fe=ya/C,_e={audio:[{type:"audio",dts:N,pts:N},{type:"audio",dts:N+k*1024*fe,pts:N+k*1024*fe}]};return _e},Jn=function(x){var A={pid:null,table:null},k={};yf(x,A);for(var C in A.table)if(A.table.hasOwnProperty(C)){var N=A.table[C];switch(N){case vr.H264_STREAM_TYPE:k.video=[],us(x,A,k),k.video.length===0&&delete k.video;break;case vr.ADTS_STREAM_TYPE:k.audio=[],Xs(x,A,k),k.audio.length===0&&delete k.audio;break}}return k},yd=function(x,A){var k=yi.aac.isLikelyAacData(x),C;return k?C=va(x):C=Jn(x),!C||!C.audio&&!C.video?null:(Ci(C,A),C)},xa={inspect:yd,parseAudioPes_:Xs};const vf=function(x,A){A.on("data",function(k){const C=k.initSegment;k.initSegment={data:C.buffer,byteOffset:C.byteOffset,byteLength:C.byteLength};const N=k.data;k.data=N.buffer,x.postMessage({action:"data",segment:k,byteOffset:N.byteOffset,byteLength:N.byteLength},[k.data])}),A.on("done",function(k){x.postMessage({action:"done"})}),A.on("gopInfo",function(k){x.postMessage({action:"gopInfo",gopInfo:k})}),A.on("videoSegmentTimingInfo",function(k){const C={start:{decode:Ut.videoTsToSeconds(k.start.dts),presentation:Ut.videoTsToSeconds(k.start.pts)},end:{decode:Ut.videoTsToSeconds(k.end.dts),presentation:Ut.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Ut.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Ut.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:C})}),A.on("audioSegmentTimingInfo",function(k){const C={start:{decode:Ut.videoTsToSeconds(k.start.dts),presentation:Ut.videoTsToSeconds(k.start.pts)},end:{decode:Ut.videoTsToSeconds(k.end.dts),presentation:Ut.videoTsToSeconds(k.end.pts)},baseMediaDecodeTime:Ut.videoTsToSeconds(k.baseMediaDecodeTime)};k.prependedContentDuration&&(C.prependedContentDuration=Ut.videoTsToSeconds(k.prependedContentDuration)),x.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:C})}),A.on("id3Frame",function(k){x.postMessage({action:"id3Frame",id3Frame:k})}),A.on("caption",function(k){x.postMessage({action:"caption",caption:k})}),A.on("trackinfo",function(k){x.postMessage({action:"trackinfo",trackInfo:k})}),A.on("audioTimingInfo",function(k){x.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Ut.videoTsToSeconds(k.start),end:Ut.videoTsToSeconds(k.end)}})}),A.on("videoTimingInfo",function(k){x.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Ut.videoTsToSeconds(k.start),end:Ut.videoTsToSeconds(k.end)}})}),A.on("log",function(k){x.postMessage({action:"log",log:k})})};class vd{constructor(A,k){this.options=k||{},this.self=A,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new C0.Transmuxer(this.options),vf(this.self,this.transmuxer)}pushMp4Captions(A){this.captionParser||(this.captionParser=new Uo,this.captionParser.init());const k=new Uint8Array(A.data,A.byteOffset,A.byteLength),C=this.captionParser.parse(k,A.trackIds,A.timescales);this.self.postMessage({action:"mp4Captions",captions:C&&C.captions||[],logs:C&&C.logs||[],data:k.buffer},[k.buffer])}initMp4WebVttParser(A){this.webVttParser||(this.webVttParser=new pa);const k=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.webVttParser.init(k)}getMp4WebVttText(A){this.webVttParser||(this.webVttParser=new pa);const k=new Uint8Array(A.data,A.byteOffset,A.byteLength),C=this.webVttParser.parseSegment(k);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:C||[],data:k.buffer},[k.buffer])}probeMp4StartTime({timescales:A,data:k}){const C=Po.startTime(A,k);this.self.postMessage({action:"probeMp4StartTime",startTime:C,data:k},[k.buffer])}probeMp4Tracks({data:A}){const k=Po.tracks(A);this.self.postMessage({action:"probeMp4Tracks",tracks:k,data:A},[A.buffer])}probeEmsgID3({data:A,offset:k}){const C=Po.getEmsgID3(A,k);this.self.postMessage({action:"probeEmsgID3",id3Frames:C,emsgData:A},[A.buffer])}probeTs({data:A,baseStartTime:k}){const C=typeof k=="number"&&!isNaN(k)?k*Ut.ONE_SECOND_IN_TS:void 0,N=xa.inspect(A,C);let U=null;N&&(U={hasVideo:N.video&&N.video.length===2||!1,hasAudio:N.audio&&N.audio.length===2||!1},U.hasVideo&&(U.videoStart=N.video[0].ptsTime),U.hasAudio&&(U.audioStart=N.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:U,data:A},[A.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(A){const k=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.transmuxer.push(k)}reset(){this.transmuxer.reset()}setTimestampOffset(A){const k=A.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Ut.secondsToVideoTs(k)))}setAudioAppendStart(A){this.transmuxer.setAudioAppendStart(Math.ceil(Ut.secondsToVideoTs(A.appendStart)))}setRemux(A){this.transmuxer.setRemux(A.remux)}flush(A){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(A){this.transmuxer.alignGopsWith(A.gopsToAlignWith.slice())}}self.onmessage=function(x){if(x.data.action==="init"&&x.data.options){this.messageHandlers=new vd(self,x.data.options);return}this.messageHandlers||(this.messageHandlers=new vd(self)),x.data&&x.data.action&&x.data.action!=="init"&&this.messageHandlers[x.data.action]&&this.messageHandlers[x.data.action](x.data)}}));var lF=Xk(oF);const uF=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:a,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:a,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)},cF=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},dF=(s,e)=>{e.gopInfo=s.data.gopInfo},Jk=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:a,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:p,onId3:y,onCaptions:v,onDone:b,onEndedTimeline:_,onTransmuxerLog:S,isEndOfTimeline:L,segment:I,triggerSegmentEventFn:R}=s,$={buffer:[]};let B=L;const F=G=>{e.currentTransmux===s&&(G.data.action==="data"&&uF(G,$,a),G.data.action==="trackinfo"&&u(G.data.trackInfo),G.data.action==="gopInfo"&&dF(G,$),G.data.action==="audioTimingInfo"&&c(G.data.audioTimingInfo),G.data.action==="videoTimingInfo"&&d(G.data.videoTimingInfo),G.data.action==="videoSegmentTimingInfo"&&f(G.data.videoSegmentTimingInfo),G.data.action==="audioSegmentTimingInfo"&&p(G.data.audioSegmentTimingInfo),G.data.action==="id3Frame"&&y([G.data.id3Frame],G.data.id3Frame.dispatchType),G.data.action==="caption"&&v(G.data.caption),G.data.action==="endedtimeline"&&(B=!1,_()),G.data.action==="log"&&S(G.data.log),G.data.type==="transmuxed"&&(B||(e.onmessage=null,cF({transmuxedData:$,callback:b}),eD(e))))},M=()=>{const G={message:"Received an error message from the transmuxer worker",metadata:{errorType:Re.Error.StreamingFailedToTransmuxSegment,segmentInfo:au({segment:I})}};b(null,G)};if(e.onmessage=F,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 G=t instanceof ArrayBuffer?t:t.buffer,D=t instanceof ArrayBuffer?0:t.byteOffset;R({type:"segmenttransmuxingstart",segment:I}),e.postMessage({action:"push",data:G,byteOffset:D,byteLength:t.byteLength},[G])}L&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},eD=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Jk(s.currentTransmux))},u2=(s,e)=>{s.postMessage({action:e}),eD(s)},tD=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,u2(e,s);return}e.transmuxQueue.push(u2.bind(null,e,s))},hF=s=>{tD("reset",s)},fF=s=>{tD("endTimeline",s)},iD=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Jk(s);return}s.transmuxer.transmuxQueue.push(s)},mF=s=>{const e=new lF;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 rv={reset:hF,endTimeline:fF,transmux:iD,createTransmuxer:mF};const bc=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=Ks({},s,{endAction:null,transmuxer:null,callback:null}),r=a=>{a.data.action===t&&(e.removeEventListener("message",r),a.data.data&&(a.data.data=new Uint8Array(a.data.data,s.byteOffset||0,s.byteLength||a.data.data.byteLength),s.data&&(s.data=a.data.data)),i(a.data))};if(e.addEventListener("message",r),s.data){const a=s.data instanceof ArrayBuffer;n.byteOffset=a?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[a?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},Ma={FAILURE:2,TIMEOUT:-101,ABORTED:-102},sD="wvtt",Ex=s=>{s.forEach(e=>{e.abort()})},pF=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),gF=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},$b=(s,e)=>{const{requestType:t}=e,i=mu({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:Ma.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:Ma.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:Ma.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:Ma.FAILURE,xhr:e,metadata:i}:null},c2=(s,e,t,i)=>(n,r)=>{const a=r.response,u=$b(n,r);if(u)return t(u,s);if(a.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:Ma.FAILURE,xhr:r},s);const c=new DataView(a),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let p=0;p{e===sD&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},vF=(s,e,t)=>{e===sD&&bc({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},nD=(s,e)=>{const t=cb(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:Ma.FAILURE,metadata:{mediaType:n}})}bc({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"&&yF(s,r.codec))}),e(null))})},xF=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=$b(i,n);if(r)return e(r,s);const a=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=a,e(null,s);s.map.bytes=a,nD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},bF=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const a=$b(n,r);if(a)return e(a,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:rF(r.responseText.substring(s.lastReachedChar||0));return s.stats=pF(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},TF=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{const b=s.map&&s.map.tracks||{},_=!!(b.audio&&b.video);let S=i.bind(null,s,"audio","start");const L=i.bind(null,s,"audio","end");let I=i.bind(null,s,"video","start");const R=i.bind(null,s,"video","end"),$=()=>iD({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:B=>{B.type=B.type==="combined"?"video":B.type,f(s,B)},onTrackInfo:B=>{t&&(_&&(B.isMuxed=!0),t(s,B))},onAudioTimingInfo:B=>{S&&typeof B.start<"u"&&(S(B.start),S=null),L&&typeof B.end<"u"&&L(B.end)},onVideoTimingInfo:B=>{I&&typeof B.start<"u"&&(I(B.start),I=null),R&&typeof B.end<"u"&&R(B.end)},onVideoSegmentTimingInfo:B=>{const F={pts:{start:B.start.presentation,end:B.end.presentation},dts:{start:B.start.decode,end:B.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:F}),n(B)},onAudioSegmentTimingInfo:B=>{const F={pts:{start:B.start.pts,end:B.end.pts},dts:{start:B.start.dts,end:B.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:F}),r(B)},onId3:(B,F)=>{a(s,B,F)},onCaptions:B=>{u(s,[B])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:y,onDone:(B,F)=>{p&&(B.type=B.type==="combined"?"video":B.type,v({type:"segmenttransmuxingcomplete",segment:s}),p(F,s,B))},segment:s,triggerSegmentEventFn:v});bc({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:B=>{s.bytes=e=B.data;const F=B.result;F&&(t(s,{hasAudio:F.hasAudio,hasVideo:F.hasVideo,isMuxed:_}),t=null),$()}})},rD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=new Uint8Array(e);if(HP(b)){s.isFmp4=!0;const{tracks:_}=s.map;if(_.text&&(!_.audio||!_.video)){f(s,{data:b,type:"text"}),vF(s,_.text.codec,p);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=(R,$)=>{f(s,{data:b,type:L.hasAudio&&!L.isMuxed?"audio":"video"}),$&&$.length&&a(s,$),R&&R.length&&u(s,R),p(null,s,{})};bc({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:R,startTime:$})=>{e=R.buffer,s.bytes=b=R,L.hasAudio&&!L.isMuxed&&i(s,"audio","start",$),L.hasVideo&&i(s,"video","start",$),bc({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:$,callback:({emsgData:B,id3Frames:F})=>{if(e=B.buffer,s.bytes=b=B,!_.video||!B.byteLength||!s.transmuxer){I(void 0,F);return}bc({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[_.video.id],callback:M=>{e=M.data.buffer,s.bytes=b=M.data,M.logs.forEach(function(G){y(qi(G,{stream:"mp4CaptionParser"}))}),I(M.captions,F)}})}})}});return}if(!s.transmuxer){p(null,s,{});return}if(typeof s.container>"u"&&(s.container=cb(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),p(null,s,{});return}TF({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})},aD=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},a){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;a(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=au({segment:n}),p={message:d,metadata:{error:new Error(d),errorType:Re.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(Vk({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},_F=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),aD({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:p},b=>{e.bytes=b,v({type:"segmentdecryptioncomplete",segment:e}),rD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})})},SF=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=0,_=!1;return(S,L)=>{if(!_){if(S)return _=!0,Ex(s),p(S,L);if(b+=1,b===s.length){const I=function(){if(L.encryptedBytes)return _F({decryptionWorker:e,segment:L,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v});rD({segment:L,bytes:L.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})};if(L.endOfAllRequests=Date.now(),L.map&&L.map.encryptedBytes&&!L.map.bytes)return v({type:"segmentdecryptionstart",segment:L}),aD({decryptionWorker:e,id:L.requestId+"-init",encryptedBytes:L.map.encryptedBytes,key:L.map.key,segment:L,doneFn:p},R=>{L.map.bytes=R,v({type:"segmentdecryptioncomplete",segment:L}),nD(L,$=>{if($)return Ex(s),p($,L);I()})});I()}}}},EF=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},wF=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>p=>{if(!p.target.aborted)return s.stats=qi(s.stats,gF(p)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(p,s)},AF=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:S,triggerSegmentEventFn:L})=>{const I=[],R=SF({activeXhrs:I,decryptionWorker:t,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:_,onTransmuxerLog:S,triggerSegmentEventFn:L});if(i.key&&!i.key.bytes){const G=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&G.push(i.map.key);const D=qi(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),O=c2(i,G,R,L),W={uri:i.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:W});const Y=s(D,O);I.push(Y)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const Y=qi(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),J=c2(i,[i.map.key],R,L),ae={uri:i.map.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:ae});const se=s(Y,J);I.push(se)}const D=qi(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:_x(i.map),requestType:"segment-media-initialization"}),O=xF({segment:i,finishProcessingFn:R,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const W=s(D,O);I.push(W)}const $=qi(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:_x(i),requestType:"segment"}),B=bF({segment:i,finishProcessingFn:R,responseType:$.responseType,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const F=s($,B);F.addEventListener("progress",wF({segment:i,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b})),I.push(F);const M={};return I.forEach(G=>{G.addEventListener("loadend",EF({loadendState:M,abortFn:n}))}),()=>Ex(I)},_m=Yr("PlaylistSelector"),d2=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||""})},Tc=function(s,e){if(!s)return"";const t=de.getComputedStyle(s);return t?t[e]:""},_c=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})},Hb=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||de.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||de.Number.MAX_VALUE,t-i},CF=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||de.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||de.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let oD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:a,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:a};let d=e.playlists;cr.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(M=>{let G;const D=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.width,O=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.height;return G=M.attributes&&M.attributes.BANDWIDTH,G=G||de.Number.MAX_VALUE,{bandwidth:G,width:D,height:O,playlist:M}});_c(f,(M,G)=>M.bandwidth-G.bandwidth),f=f.filter(M=>!cr.isIncompatible(M.playlist));let p=f.filter(M=>cr.isEnabled(M.playlist));p.length||(p=f.filter(M=>!cr.isDisabled(M.playlist)));const y=p.filter(M=>M.bandwidth*pn.BANDWIDTH_VARIANCEM.bandwidth===v.bandwidth)[0];if(a===!1){const M=b||p[0]||f[0];if(M&&M.playlist){let G="sortedPlaylistReps";return b&&(G="bandwidthBestRep"),p[0]&&(G="enabledPlaylistReps"),_m(`choosing ${d2(M)} using ${G} with options`,c),M.playlist}return _m("could not choose a playlist with options",c),null}const _=y.filter(M=>M.width&&M.height);_c(_,(M,G)=>M.width-G.width);const S=_.filter(M=>M.width===i&&M.height===n);v=S[S.length-1];const L=S.filter(M=>M.bandwidth===v.bandwidth)[0];let I,R,$;L||(I=_.filter(M=>r==="cover"?M.width>i&&M.height>n:M.width>i||M.height>n),R=I.filter(M=>M.width===I[0].width&&M.height===I[0].height),v=R[R.length-1],$=R.filter(M=>M.bandwidth===v.bandwidth)[0]);let B;if(u.leastPixelDiffSelector){const M=_.map(G=>(G.pixelDiff=Math.abs(G.width-i)+Math.abs(G.height-n),G));_c(M,(G,D)=>G.pixelDiff===D.pixelDiff?D.bandwidth-G.bandwidth:G.pixelDiff-D.pixelDiff),B=M[0]}const F=B||$||L||b||p[0]||f[0];if(F&&F.playlist){let M="sortedPlaylistReps";return B?M="leastPixelDiffRep":$?M="resolutionPlusOneRep":L?M="resolutionBestRep":b?M="bandwidthBestRep":p[0]&&(M="enabledPlaylistReps"),_m(`choosing ${d2(F)} using ${M} with options`,c),F.playlist}return _m("could not choose a playlist with options",c),null};const h2=function(){let s=this.useDevicePixelRatio&&de.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),oD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(Tc(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(Tc(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?Tc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},kF=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&&de.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),oD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(Tc(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(Tc(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?Tc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},DF=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:a,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(b=>!cr.isIncompatible(b));let f=d.filter(cr.isEnabled);f.length||(f=d.filter(b=>!cr.isDisabled(b)));const y=f.filter(cr.hasAttribute.bind(null,"BANDWIDTH")).map(b=>{const S=c.getSyncPoint(b,n,u,t)?1:2,I=cr.estimateSegmentRequestTime(r,i,b)*S-a;return{playlist:b,rebufferingImpact:I}}),v=y.filter(b=>b.rebufferingImpact<=0);return _c(v,(b,_)=>Hb(_.playlist,b.playlist)),v.length?v[0]:(_c(y,(b,_)=>b.rebufferingImpact-_.rebufferingImpact),y[0]||null)},LF=function(){const s=this.playlists.main.playlists.filter(cr.isEnabled);return _c(s,(t,i)=>Hb(t,i)),s.filter(t=>!!Th(this.playlists.main,t).video)[0]||null},RF=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 lD(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 a=t,u=t,c=!1;const d=r[i];d&&(a=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:a,language:u},!1).track}}},NF=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=de.WebKitDataCue||de.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(a=>{const u=new i(n.startTime+t,n.endTime+t,a.text);u.line=a.line,u.align="left",u.position=a.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},OF=function(s){Object.defineProperties(s.frame,{id:{get(){return Re.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return Re.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return Re.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},MF=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=de.WebKitDataCue||de.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const p=f.cueTime+t;typeof p!="number"||de.isNaN(p)||p<0||!(p<1/0)||!f.frames||!f.frames.length||f.frames.forEach(y=>{const v=new n(p,p,y.value||y.url||y.data||"");v.frame=y,v.value=y,OF(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const a=r.cues,u=[];for(let f=0;f{const y=f[p.startTime]||[];return y.push(p),f[p.startTime]=y,f},{}),d=Object.keys(c).sort((f,p)=>Number(f)-Number(p));d.forEach((f,p)=>{const y=c[f],v=isFinite(i)?i:f,b=Number(d[p+1])||v;y.forEach(_=>{_.endTime=b})})},PF={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"},BF=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),FF=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=de.WebKitDataCue||de.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(BF.has(r))continue;const a=new i(n.startTime,n.endTime,"");a.id=n.id,a.type="com.apple.quicktime.HLS",a.value={key:PF[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(a.value.data=new Uint8Array(a.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(a)}n.processDateRange()})},f2=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,Re.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},uh=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}},jF=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*lu.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},$F=(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)*lu.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*lu.ONE_SECOND_IN_TS),a=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return a;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),a.splice(c,u-c+1),a},GF=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]},Jd=1,zF=500,m2=s=>typeof s=="number"&&isFinite(s),Sm=1/60,qF=(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,KF=(s,e,t)=>{let i=e-pn.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},Zu=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:a,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,p=u.length-1;let y="mediaIndex/partIndex increment";s.getMediaInfoForTime?y=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(y="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(y+=` with independent ${s.independent}`);const v=typeof d=="number",b=s.segment.uri?"segment":"pre-segment",_=v?Ak({preloadSegment:i})-1:0;return`${b} [${r+c}/${r+p}]`+(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 [${y}] playlist [${a}]`},p2=s=>`${s}TimingInfo`,WF=({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},YF=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)},XF=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(wx({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&YF(s.timelineChangeController_)){if(XF(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},QF=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 a;typeof n=="bigint"||typeof r=="bigint"?a=de.BigInt(r)-de.BigInt(n):typeof n=="number"&&typeof r=="number"&&(a=r-n),typeof a<"u"&&a>e&&(e=a)}),typeof e=="bigint"&&es?Math.round(s)>e+Na:!1,ZF=(s,e)=>{if(e!=="hls")return null;const t=QF({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=g2({segmentDuration:t,maxDuration:i*2}),r=g2({segmentDuration:t,maxDuration:i}),a=`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:a}:null},au=({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 Ax extends Re.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_=Yr(`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_():cl(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(Ks({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():cl(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(Ks({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():cl(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():cl(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return rv.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_&&de.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,de.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_&&rv.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return yn();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=Ep(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=zk(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: ${sv(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 a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,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-=a,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_&&(de.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_&&rv.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 a=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,a)),(n||this.loaderType_==="main")&&(this.gopBuffer_=HF(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,a));for(const u in this.inbandTextTracks_)uh(e,t,this.inbandTextTracks_[u]);uh(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&de.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=de.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&de.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=de.setTimeout(this.monitorBufferTick_.bind(this),zF)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:au({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,a=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&a}chooseNextRequest_(){const e=this.buffered_(),t=sv(e)||0,i=Bb(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.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=VF(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const y=a[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=y.end?y.end:t,y.parts&&y.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let y,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 S=this.getSyncInfoFromMediaSequenceSync_(_);if(!S){const L="No sync info found while using media sequence sync";return this.error({message:L,metadata:{errorType:Re.Error.StreamingFailedToSelectNextSegment,error:new Error(L)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${S.start} --> ${S.end})`),y=S.segmentIndex,v=S.partIndex,b=S.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const S=cr.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});y=S.segmentIndex,v=S.partIndex,b=S.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,u.mediaIndex=y,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=a[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 y=a[u.mediaIndex-1],v=y.parts&&y.parts.length&&y.parts[y.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=y.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>=a.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:a,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],p=typeof u=="number"&&f.parts[u],y={requestId:"segment-loader-"+Math.random(),uri:p&&p.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:p?u:null,isSyncRequest:a,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},v=typeof c<"u"?c:this.isPendingTimestampOffset_;y.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const b=sv(this.sourceUpdater_.audioBuffered());return typeof b=="number"&&(y.audioAppendStart=b-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(y.gopsToAlignWith=jF(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),y}timestampOffsetForSegment_(e){return WF(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=cr.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),a=gB(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=a)return;const u=DF({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-a-u.rebufferingImpact;let f=.5;a<=Na&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[a.stream]=r[a.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[a.stream];u.startTime=Math.min(u.startTime,a.startTime+n),u.endTime=Math.max(u.endTime,a.endTime+n),u.captions.push(a)}),Object.keys(r).forEach(a=>{const{startTime:u,endTime:c,captions:d}=r[a],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${a}`),IF(f,this.vhs_.tech_,a),uh(u,c,f[a]),NF({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_()?!wx({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||wx({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_()){cl(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[p2(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let a;r&&(a=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:a,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=Ep(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(),a=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+uu(r).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+uu(a).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=a.length?a.start(0):0,f=a.length?a.end(a.length-1):0;if(c-u<=Jd&&f-d<=Jd){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${uu(r).join(", ")}, video buffer: ${uu(a).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 y=this.currentTime_()-Jd;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${y}`),this.remove(0,y,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${Jd}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=de.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},Jd*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===Bk){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:Re.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=RF({bytes:c,segments:u})}const a={segmentInfo:au({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),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_()){cl(this),this.loadQueue_.push(()=>{const t=Ks({},e,{forceTimestampOffset:!0});Ks(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,a=i||n&&r;this.logger_(`Requesting +${lD(e.uri)} +${Zu(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=AF({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:a,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_(`${Zu(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:p})=>{const v={segmentInfo:au({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),p&&(v.timingInfo=p),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=KF(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,a={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?a.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(a.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=c}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}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,a=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}a&&e.waitingOnAppends++,u&&e.waitingOnAppends++,a&&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=qF(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:au({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=ZF(e,this.sourceType_);if(t&&(t.severity==="warn"?Re.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 ${Zu(e)}`);return}this.logger_(`Appended ${Zu(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,a=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||a){this.logger_(`bad ${r?"segment":"part"} ${Zu(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())},JF=["video","audio"],Cx=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},e8=(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(),Sc("audio",e),Sc("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||Cx(s,e))){if(i.type!==s){if(t=e8(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,Sc(s,e);return}}},cD=(s,e)=>{const t=e[`${s}Buffer`],i=uD(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},La=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,Er={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(La(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(a){n.logger_(`Error with code ${a.code} `+(a.code===Bk?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(a)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(La(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`];La(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){Re.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){Re.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(La(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){Re.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=uD(s),n=Ic(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(cD(s,e),!!La(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){Re.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=Ic(s);if(!La(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))===r)return;const c={codecsChangeInfo:{from:a,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${a} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=Re.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),Re.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},wr=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),Sc(s,e)},y2=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=fB(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_`])}Sc(s,e)};class dD extends Re.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>Sc("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Yr("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=y2("video",this),this.onAudioUpdateEnd_=y2("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){wr({type:"mediaSource",sourceUpdater:this,action:Er.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){wr({type:e,sourceUpdater:this,action:Er.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){Re.log.error("removeSourceBuffer is not supported!");return}wr({type:"mediaSource",sourceUpdater:this,action:Er.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!Re.browser.IS_FIREFOX&&de.MediaSource&&de.MediaSource.prototype&&typeof de.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return de.SourceBuffer&&de.SourceBuffer.prototype&&typeof de.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){Re.log.error("changeType is not supported!");return}wr({type:e,sourceUpdater:this,action:Er.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 a=t;if(wr({type:n,sourceUpdater:this,action:Er.appendBuffer(r,i||{mediaIndex:-1},a),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 La(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:yn()}videoBuffered(){return La(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:yn()}buffered(){const e=La(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=La(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():pB(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=To){wr({type:"mediaSource",sourceUpdater:this,action:Er.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=To){typeof e!="string"&&(e=void 0),wr({type:"mediaSource",sourceUpdater:this,action:Er.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=To){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}wr({type:"audio",sourceUpdater:this,action:Er.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=To){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}wr({type:"video",sourceUpdater:this,action:Er.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&&(wr({type:"audio",sourceUpdater:this,action:Er.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(wr({type:"video",sourceUpdater:this,action:Er.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&wr({type:"audio",sourceUpdater:this,action:Er.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&wr({type:"video",sourceUpdater:this,action:Er.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),JF.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>cD(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const v2=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),t8=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},x2=new Uint8Array(` + +`.split("").map(s=>s.charCodeAt(0)));class i8 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class s8 extends Ax{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 yn();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return yn([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Ep(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=x2.byteLength+e.bytes.byteLength,a=new Uint8Array(r);a.set(e.bytes),a.set(x2,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}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){uh(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===Ma.TIMEOUT&&this.handleTimeout_(),e.code===Ma.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 a=n.segment;if(a.map&&(a.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof de.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}a.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:Re.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+=a.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new de.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,a=new de.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];a[d]=isNaN(f)?f:Number(f)}),e.cues.push(a)})}parseVTTCues_(e){let t,i=!1;if(typeof de.WebVTT!="function")throw new i8;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof de.TextDecoder=="function"?t=new de.TextDecoder("utf8"):(t=de.WebVTT.StringDecoder(),i=!0);const n=new de.WebVTT.Parser(de,de.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=a=>{e.timestampmap=a},n.onparsingerror=a=>{Re.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=v2(a)),n.parse(a)}let r=e.bytes;i&&(r=v2(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:a}=e.timestampmap,c=r/lu.ONE_SECOND_IN_TS-a+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*lu.ONE_SECOND_IN_TS;const n=t*lu.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/lu.ONE_SECOND_IN_TS}}const n8=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},r8=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 hD{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=` +`,a=i,u=t;this.start_=a,e.forEach((c,d)=>{const f=this.storage_.get(u),p=a,y=p+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),b=new b2({start:p,end:y,appended:v,segmentIndex:d});c.syncInfo=b;let _=a;const S=(c.parts||[]).map((L,I)=>{const R=_,$=_+L.duration,B=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[I]&&f.partsSyncInfo[I].isAppended),F=new b2({start:R,end:$,appended:B,segmentIndex:d,partIndex:I});return _=$,r+=`Media Sequence: ${u}.${I} | Range: ${R} --> ${$} | Appended: ${B} +`,L.syncInfo=F,F});n.set(u,new a8(b,S)),r+=`${lD(c.resolvedUri)} | Media Sequence: ${u} | Range: ${p} --> ${y} | Appended: ${v} +`,u++,a=y}),this.end_=a,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 a=s.getMediaSequenceSync(r);if(!a||!a.isReliable)return null;const u=a.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,a=null;const u=yx(e);n=n||0;for(let c=0;c{let r=null,a=null;n=n||0;const u=yx(e);for(let c=0;c=v)&&(a=v,r={time:y,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 a=null;for(let u=0;u=p)&&(a=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 l8 extends Re.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new hD,i=new T2(t),n=new T2(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=Yr("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return av.find(({name:c})=>c==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,i,n,r);if(!a.length)return null;for(const u of a){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:p}=c;if(f<0)continue;const y=e.segments[f],v=p,b=v+y.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+bh({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const a=[];for(let u=0;uo8){Re.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 a=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),u=e.startOfSegment,c=t.end+a.mapping;else if(a)u=t.start+a.mapping,c=t.end+a.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-bh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+bh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[a]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class u8 extends Re.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 c8=Qk(Zk(function(){var s=(function(){function _(){this.listeners={}}var S=_.prototype;return S.on=function(I,R){this.listeners[I]||(this.listeners[I]=[]),this.listeners[I].push(R)},S.off=function(I,R){if(!this.listeners[I])return!1;var $=this.listeners[I].indexOf(R);return this.listeners[I]=this.listeners[I].slice(0),this.listeners[I].splice($,1),$>-1},S.trigger=function(I){var R=this.listeners[I];if(R)if(arguments.length===2)for(var $=R.length,B=0;B<$;++B)R[B].call(this,arguments[1]);else for(var F=Array.prototype.slice.call(arguments,1),M=R.length,G=0;G>7)*283)^$]=$;for(B=F=0;!I[B];B^=D||1,F=G[F]||1)for(Y=F^F<<1^F<<2^F<<3^F<<4,Y=Y>>8^Y&255^99,I[B]=Y,R[Y]=B,W=M[O=M[D=M[B]]],ae=W*16843009^O*65537^D*257^B*16843008,J=M[Y]*257^Y*16843008,$=0;$<4;$++)S[$][B]=J=J<<24^J>>>8,L[$][Y]=ae=ae<<24^ae>>>8;for($=0;$<5;$++)S[$]=S[$].slice(0),L[$]=L[$].slice(0);return _};let i=null;class n{constructor(S){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,R;const $=this._tables[0][4],B=this._tables[1],F=S.length;let M=1;if(F!==4&&F!==6&&F!==8)throw new Error("Invalid aes key size");const G=S.slice(0),D=[];for(this._key=[G,D],L=F;L<4*F+28;L++)R=G[L-1],(L%F===0||F===8&&L%F===4)&&(R=$[R>>>24]<<24^$[R>>16&255]<<16^$[R>>8&255]<<8^$[R&255],L%F===0&&(R=R<<8^R>>>24^M<<24,M=M<<1^(M>>7)*283)),G[L]=G[L-F]^R;for(I=0;L;I++,L--)R=G[I&3?L:L-4],L<=4||I<4?D[I]=R:D[I]=B[0][$[R>>>24]]^B[1][$[R>>16&255]]^B[2][$[R>>8&255]]^B[3][$[R&255]]}decrypt(S,L,I,R,$,B){const F=this._key[1];let M=S^F[0],G=R^F[1],D=I^F[2],O=L^F[3],W,Y,J;const ae=F.length/4-2;let se,K=4;const X=this._tables[1],ee=X[0],le=X[1],pe=X[2],P=X[3],Q=X[4];for(se=0;se>>24]^le[G>>16&255]^pe[D>>8&255]^P[O&255]^F[K],Y=ee[G>>>24]^le[D>>16&255]^pe[O>>8&255]^P[M&255]^F[K+1],J=ee[D>>>24]^le[O>>16&255]^pe[M>>8&255]^P[G&255]^F[K+2],O=ee[O>>>24]^le[M>>16&255]^pe[G>>8&255]^P[D&255]^F[K+3],K+=4,M=W,G=Y,D=J;for(se=0;se<4;se++)$[(3&-se)+B]=Q[M>>>24]<<24^Q[G>>16&255]<<16^Q[D>>8&255]<<8^Q[O&255]^F[K++],W=M,M=G,G=D,D=O,O=W}}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(S){this.jobs.push(S),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},u=function(_,S,L){const I=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),R=new n(Array.prototype.slice.call(S)),$=new Uint8Array(_.byteLength),B=new Int32Array($.buffer);let F,M,G,D,O,W,Y,J,ae;for(F=L[0],M=L[1],G=L[2],D=L[3],ae=0;ae{const I=_[L];y(I)?S[L]={bytes:I.buffer,byteOffset:I.byteOffset,byteLength:I.byteLength}:S[L]=I}),S};self.onmessage=function(_){const S=_.data,L=new Uint8Array(S.encrypted.bytes,S.encrypted.byteOffset,S.encrypted.byteLength),I=new Uint32Array(S.key.bytes,S.key.byteOffset,S.key.byteLength/4),R=new Uint32Array(S.iv.bytes,S.iv.byteOffset,S.iv.byteLength/4);new c(L,I,R,function($,B){self.postMessage(b({source:S.source,decrypted:B}),[B.buffer])})}}));var d8=Xk(c8);const h8=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},fD=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},kx=(s,e)=>{e.activePlaylistLoader=s,s.load()},f8=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),a=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(a&&c&&a.id===c.id)&&(n.lastGroup_=a,n.lastTrack_=r,fD(t,n),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),kx(a.playlistLoader,n)}},m8=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},p8=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,a=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&a&&d.id===a.id)&&(r.lastGroup_=u,r.lastTrack_=a,fD(i,r),!!u)){if(u.isMainPlaylist){if(!a||!d||a.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 ${a.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){kx(u.playlistLoader,r);return}i.track&&i.track(a),i.resetEverything(),kx(u.playlistLoader,r)}},wp={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),a=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[a];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}Re.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;Re.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},_2={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const a=e.media();r.playlist(a,n),(!i.paused()||a.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]:a}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(a.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))}},g8={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:a},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,p=Kh(f.main);(!a[s]||Object.keys(a[s]).length===0)&&(a[s]={main:{default:{default:!0}}},p&&(a[s].main.default.playlists=f.main.playlists));for(const y in a[s]){u[y]||(u[y]=[]);for(const v in a[s][y]){let b=a[s][y][v],_;if(p?(d(`AUDIO group '${y}' label '${v}' is a main playlist`),b.isMainPlaylist=!0,_=null):i==="vhs-json"&&b.playlists?_=new hc(b.playlists[0],t,r):b.resolvedUri?_=new hc(b.resolvedUri,t,r):b.playlists&&i==="dash"?_=new Sx(b.playlists[0],t,r,f):_=null,b=qi({id:v,playlistLoader:_},b),_2[s](s,b.playlistLoader,e),u[y].push(b),typeof c[v]>"u"){const S=new Re.AudioTrack({id:v,kind:h8(b),enabled:!1,language:b.language,default:b.default,label:v});c[v]=S}}}n.on("error",wp[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:a,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const p in u[s]){c[p]||(c[p]=[]);for(const y in u[s][p]){if(!i.options_.useForcedSubtitles&&u[s][p][y].forced)continue;let v=u[s][p][y],b;if(n==="hls")b=new hc(v.resolvedUri,i,a);else if(n==="dash"){if(!v.playlists.filter(S=>S.excludeUntil!==1/0).length)return;b=new Sx(v.playlists[0],i,a,f)}else n==="vhs-json"&&(b=new hc(v.playlists?v.playlists[0]:v.resolvedUri,i,a));if(v=qi({id:y,playlistLoader:b},v),_2[s](s,v.playlistLoader,e),c[p].push(v),typeof d[y]>"u"){const _=t.addRemoteTextTrack({id:y,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:y},!1).track;d[y]=_}}}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 a in i[s]){n[a]||(n[a]=[]);for(const u in i[s][a]){const c=i[s][a][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=qi(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[a].push(qi({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}}}}},mD=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let a=null;r.attributes[s]&&(a=n[r.attributes[s]]);const u=Object.keys(n);if(!a)if(s==="AUDIO"&&u.length>1&&Kh(e.main))for(let c=0;c"u"?a:t===null||!a?null:a.filter(c=>c.id===t.id)[0]||null},v8={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}},x8=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},b8=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{g8[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:a}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=y8(d,s),e[d].activeTrack=v8[d](d,s),e[d].onGroupChanged=f8(d,s),e[d].onGroupChanging=m8(d,s),e[d].onTrackChanged=p8(d,s),e[d].getActiveGroup=x8(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?(a.setAudio(!1),r.setAudio(!0)):a.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])},T8=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:To,activeTrack:To,getActiveGroup:To,onGroupChanged:To,onTrackChanged:To,lastTrack_:null,logger_:Yr(`MediaGroups[${e}]`)}}),s};class S2{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_=ur(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 _8=class extends Re.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new S2,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_=Yr("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=ur(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,a)=>{if(r){if(a.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(a.status===429){const d=a.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:Re.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 de.URL(e),i=new de.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(de.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new de.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_=de.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){de.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 S2}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&&(ur(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const S8=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},E8=10;let dl;const w8=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],A8=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},C8=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:a,bufferBasedABR:u,log:c}){if(!i)return Re.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=!!dc(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=Bb(e,t),y=u?pn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:pn.MAX_BUFFER_LOW_WATER_LINE;if(ab)&&p>=n){let _=`${d} as forwardBuffer >= bufferLowWaterLine (${p} >= ${n})`;return u&&(_+=` and next bandwidth > current bandwidth (${v} > ${b})`),c(_),!0}return c(`not ${d} as no switching criteria met`),!1};class k8 extends Re.EventTarget{constructor(e){super(),this.fastQualityChange_=S8(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:a,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:p,bufferBasedABR:y,leastPixelDiffSelector:v,captionServices:b,experimentalUseMMS:_}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:S}=e;(S===null||typeof S>"u")&&(S=1/0),dl=a,this.bufferBasedABR=!!y,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=S,this.enableLowInitialPlaylist=d,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:S,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=T8(),_&&de.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new de.ManagedMediaSource,this.usingManagedMediaSource_=!0,Re.log("Using ManagedMediaSource")):de.MediaSource&&(this.mediaSource=new de.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_=yn(),this.hasPlayed_=!1,this.syncController_=new l8(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new d8,this.sourceUpdater_=new dD(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new u8,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:p,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new Sx(t,this.vhs_,qi(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new hc(t,this.vhs_,qi(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Ax(qi(L,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Ax(qi(L,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new s8(qi(L,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise(($,B)=>{function F(){n.off("vttjserror",M),$()}function M(){n.off("vttjsloaded",F),B()}n.one("vttjsloaded",F),n.one("vttjserror",M),n.addWebVttScript_()})}),e);const I=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new _8(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_())),w8.forEach($=>{this[$+"_"]=A8.bind(this,$)}),this.logger_=Yr("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 R=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(R,()=>{const $=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-$,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),a=e&&(e.id||e.uri);if(r&&r!==a){this.logger_(`switch media ${r} -> ${a} from ${t}`);const u={renditionInfo:{id:a,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 a=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);a.length&&this.mediaTypes_[e].activePlaylistLoader.media(a[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=de.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(de.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 a=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)a.push.apply(a,c.playlists);else if(c.uri)a.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;vx(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()),b8({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;vx(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(Ks({},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 a in i.AUDIO)for(const u in i.AUDIO[a])i.AUDIO[a][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"}),dl.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(),a=this.tech_.buffered();return C8({buffered:a,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:E8}))});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(Ks({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(Ks({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(Ks({},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=dl.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return n-r<=Oa;const u=a.end(a.length-1);return u-r<=Oa&&n-u<=Oa}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(g0),a=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return Re.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){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&&(Re.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_:Re.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,y=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=p;return this.switchMedia_(c,"exclude",a||y)}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(a=>{const u=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(a=>{const u=this[`${a}SegmentLoader_`];u&&(e===a||e==="all")&&i.push(u)}),i.forEach(a=>t.forEach(u=>{typeof a[u]=="function"&&a[u]()}))}setCurrentTime(e){const t=dc(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:dl.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=dl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return yn([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const a=dl.Playlist.seekable(i,r,dl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),a=t.end(0);return r>n||i>a?e:yn([[Math.max(i,r),Math.min(n,a)]])}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 [${Ek(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=Th(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||g3),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||hE}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||hE,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 a=(d,f)=>d?gh(f,this.usingManagedMediaSource_):jy(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!a(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=(Da(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,y=(Da(n[f]||"")[0]||{}).type;p&&y&&p.toLowerCase()!==y.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=Th(this.main,n),a=[];r.audio&&!jy(r.audio)&&!gh(r.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${r.audio}`),r.video&&!jy(r.video)&&!gh(r.video,this.usingManagedMediaSource_)&&a.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&a.push(`text codec ${r.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=Rh(Da(e)),r=r2(n),a=n.video&&Da(n.video)[0]||null,u=n.audio&&Da(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=Th(this.mainPlaylistLoader_.main,d),y=r2(p);if(!(!p.audio&&!p.video)){if(y!==r&&f.push(`codec count "${y}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=p.video&&Da(p.video)[0]||null,b=p.audio&&Da(p.audio)[0]||null;v&&a&&v.type.toLowerCase()!==a.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${a.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)),r8(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=pn.GOAL_BUFFER_LENGTH,i=pn.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,pn.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=pn.BUFFER_LOW_WATER_LINE,i=pn.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,pn.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,pn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return pn.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){f2(this.inbandTextTracks_,"com.apple.streaming",this.tech_),FF({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();f2(this.inbandTextTracks_,e,this.tech_),MF({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(Ks({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),a=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(a.push(c),!r.has(c)))return!0}return!!(!a.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(a=>{const u=i[a],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(a=>{const u=this.mediaTypes_[a];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[a,u]of i.entries())n.get(a)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(a));for(const[a,u]of n.entries()){const c=i.get(a);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(a))}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 a="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===a,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 ${a}`)):(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 ${a}`)),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,Re.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:t8(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 D8=(s,e,t)=>i=>{const n=s.main.playlists[e],r=Ub(n),a=g0(n);if(typeof i>"u")return a;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!==a&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class L8{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=Th(n.main(),t),this.playlist=t,this.id=i,this.enabled=D8(e.playlists,t.id,r)}}const R8=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=Kh(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Ub(i)).map((i,n)=>new L8(s,i,i.id)):[]}},E2=["seeking","seeked","pause","playing","error"];class I8 extends Re.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_=Yr("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),a=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},a[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(p=>{a[`${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(E2,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(E2,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=>{a[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&de.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&de.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=de.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=yB(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const a={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:a}),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:uu(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+Oa>=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(yn([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:Oa)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${Ek(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const a=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=a.audioBuffer?a.audioBuffered():null,d=a.videoBuffer?a.videoBuffered():null,f=this.media(),p=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-Na)*2,y=[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 a=Tm(n,t);return a.length>0?(this.logger_(`Stopped at ${t} and seeking to ${a.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)+Oa;const a=!i.endList,u=typeof i.partTargetDuration=="number";return a&&(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:a}}return null}}const N8={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},pD=function(s,e){let t=0,i=0;const n=qi(N8,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},a=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(Ls,s,{get(){return Re.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),pn[s]},set(e){if(Re.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){Re.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}pn[s]=e}})});const yD="videojs-vhs",vD=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),vD(s,e.playlists)};Ls.canPlaySource=function(){return Re.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const j8=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=Rh(Da(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=Ic(i.video),r=Ic(i.audio),a={};for(const u in s)a[u]={},r&&(a[u].audioContentType=r),n&&(a[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(a[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(a[u].url=s[u]);return qi(s,a)},$8=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,a)=>{const u=i.contentProtection[a];return u&&u.pssh&&(r[a]={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=$8(n,Object.keys(e)),a=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),a.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},p=>{if(p){f(p);return}d()})}))}),Promise.race([Promise.all(a),Promise.race(u)])},G8=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=j8(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(Re.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},xD=()=>{if(!de.localStorage)return null;const s=de.localStorage.getItem(yD);if(!s)return null;try{return JSON.parse(s)}catch{return null}},V8=s=>{if(!de.localStorage)return!1;let e=xD();e=e?qi(e,s):s;try{de.localStorage.setItem(yD,JSON.stringify(e))}catch{return!1}return e},z8=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,bD=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},TD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},_D=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},SD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};Ls.supportsNativeHls=(function(){if(!pt||!pt.createElement)return!1;const s=pt.createElement("video");return Re.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})();Ls.supportsNativeDash=(function(){return!pt||!pt.createElement||!Re.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(pt.createElement("video").canPlayType("application/dash+xml"))})();Ls.supportsTypeNatively=s=>s==="hls"?Ls.supportsNativeHls:s==="dash"?Ls.supportsNativeDash:!1;Ls.isSupported=function(){return Re.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Ls.xhr.onRequest=function(s){bD(Ls.xhr,s)};Ls.xhr.onResponse=function(s){TD(Ls.xhr,s)};Ls.xhr.offRequest=function(s){_D(Ls.xhr,s)};Ls.xhr.offResponse=function(s){SD(Ls.xhr,s)};const q8=Re.getComponent("Component");class ED extends q8{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Yr("VhsHandler"),t.options_&&t.options_.playerId){const n=Re.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(pt,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=pt.fullscreenElement||pt.webkitFullscreenElement||pt.mozFullScreenElement||pt.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_=qi(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=xD();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=pn.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===pn.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=z8(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Ls,this.options_.sourceType=zA(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new k8(this.options_);const i=qi({liveRangeSafeTimeDelta:Oa},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=Re.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),r.error(a)});const n=this.options_.bufferBasedABR?Ls.movingAverageBandwidthSelector(.55):Ls.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Ls.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 a=de.navigator.connection||de.navigator.mozConnection||de.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&a){const c=a.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 a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(r+a))},set(){Re.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:()=>uu(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:()=>uu(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&&V8({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{R8(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_=de.URL.createObjectURL(this.playlistController_.mediaSource),(Re.browser.IS_ANY_SAFARI||Re.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=G8({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=Re.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",()=>{vD(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":gD,"mux.js":M8,"mpd-parser":P8,"m3u8-parser":B8,"aes-decrypter":F8}}version(){return this.constructor.version()}canChangeType(){return dD.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_&&de.URL.revokeObjectURL&&(de.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return XB({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return Wk({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=>{bD(this.xhr,e)},this.xhr.onResponse=e=>{TD(this.xhr,e)},this.xhr.offRequest=e=>{_D(this.xhr,e)},this.xhr.offResponse=e=>{SD(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(Ks({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(Ks({},n))})})}}const Ap={name:"videojs-http-streaming",VERSION:gD,canHandleSource(s,e={}){const t=qi(Re.options,e);return!t.vhs.experimentalUseMMS&&!gh("avc1.4d400d,mp4a.40.2",!1)?!1:Ap.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=qi(Re.options,t);return e.vhs=new ED(s,e,i),e.vhs.xhr=Gk(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=zA(s);if(!t)return"";const i=Ap.getOverrideNative(e);return!Ls.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(Re.browser.IS_ANY_SAFARI||Re.browser.IS_IOS),{overrideNative:i=t}=e;return i}},K8=()=>gh("avc1.4d400d,mp4a.40.2",!0);K8()&&Re.getTech("Html5").registerSourceHandler(Ap,0);Re.VhsHandler=ED;Re.VhsSourceHandler=Ap;Re.Vhs=Ls;Re.use||Re.registerComponent("Vhs",Ls);Re.options.vhs=Re.options.vhs||{};(!Re.getPlugin||!Re.getPlugin("reloadSourceOnError"))&&Re.registerPlugin("reloadSourceOnError",O8);const W8="",oc=s=>{const e=s.startsWith("/")?s:`/${s}`;return`${W8}${e}`};async function Y8(s,e){const t=await fetch(oc(s),{...e,credentials:"include",headers:{...e?.headers??{},"Content-Type":e?.headers?.["Content-Type"]??"application/json"}});return t.status===401&&(location.pathname.startsWith("/login")||(location.href="/login")),t}const At=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},X8=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Q8},Q8=Number.MAX_SAFE_INTEGER||9007199254740991;let Ft=(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})({}),Ie=(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})({}),H=(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 Ei={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},It={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ju{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 Z8{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 Ju(e),this.fast_=new Ju(t),this.defaultTTFB_=n,this.ttfb_=new Ju(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Ju(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ju(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ju(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 J8(s,e,t){return(e=t6(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function as(){return as=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):yl}function A2(s,e,t){return e[s]?e[s].bind(e):s6(s,t)}const Lx=Dx();function n6(s,e,t){const i=Dx();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=A2(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Dx()}n.forEach(r=>{Lx[r]=A2(r,s)})}else as(Lx,i);return i}const es=Lx;function Al(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function r6(s){return typeof self<"u"&&s===self.ManagedMediaSource}function wD(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(a=>i.indexOf(a)===-1)}function Rr(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,a="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return a}function An(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(!At(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return qs(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,a=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};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 l6 extends CD{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 a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,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 kD(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||kD(t,e)}}function u6(s,e){const t=kD(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const k2=Math.pow(2,32)-1,c6=[].push,DD={video:1,audio:2,id3:3,text:4};function un(s){return String.fromCharCode.apply(null,s)}function LD(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function ni(s,e){const t=RD(s,e);return t<0?4294967296+t:t}function D2(s,e){let t=ni(s,e);return t*=Math.pow(2,32),t+=ni(s,e+4),t}function RD(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function d6(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 bi(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=bi(s.subarray(n+8,u),e.slice(1));c.length&&c6.apply(t,c)}n=u}return t}function h6(s){const e=[],t=s[0];let i=8;const n=ni(s,i);i+=4;let r=0,a=0;t===0?(r=ni(s,i),a=ni(s,i+4),i+=8):(r=D2(s,i),a=D2(s,i+8),i+=16),i+=2;let u=s.length+a;const c=LD(s,i);i+=2;for(let d=0;d>>31===1)return es.warn("SIDX has hierarchical references (not supported)"),null;const b=ni(s,f);f+=4,e.push({referenceSize:y,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+y-1}}),u+=y,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function ID(s){const e=[],t=bi(s,["moov","trak"]);for(let n=0;n{const r=ni(n,4),a=e[r];a&&(a.default={duration:ni(n,12),flags:ni(n,20)})}),e}function f6(s){const e=s.subarray(8),t=e.subarray(86),i=un(e.subarray(4,8));let n=i,r;const a=i==="enca"||i==="encv";if(a){const d=bi(e,[i])[0].subarray(i==="enca"?28:78);bi(d,["sinf"]).forEach(p=>{const y=bi(p,["schm"])[0];if(y){const v=un(y.subarray(4,8));if(v==="cbcs"||v==="cenc"){const b=bi(p,["frma"])[0];b&&(n=un(b))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=bi(t,["avcC"])[0];c&&c.length>3&&(n+="."+wm(c[1])+wm(c[2])+wm(c[3]),r=Em(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=bi(e,[i])[0],d=bi(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=uv(d,f),f+=2;const p=d[f++];if(p&128&&(f+=2),p&64&&(f+=d[f++]),d[f++]!==4)break;f=uv(d,f);const y=d[f++];if(y===64)n+="."+wm(y);else break;if(f+=12,d[f++]!==5)break;f=uv(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=bi(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],p=d&31,y=ni(c,2),v=(d&32)>>5?"H":"L",b=c[12],_=c.subarray(6,12);n+="."+f+p,n+="."+m6(y).toString(16).toUpperCase(),n+="."+v+b;let S="";for(let L=_.length;L--;){const I=_[L];(I||S)&&(S="."+I.toString(16).toUpperCase()+S)}n+=S}r=Em(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Em(n,t)||n;break}case"vp09":{const c=bi(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],p=c[6]>>4&15;n+="."+ka(d)+"."+ka(f)+"."+ka(p)}break}case"av01":{const c=bi(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,p=c[2]>>>7?"H":"M",y=(c[2]&64)>>6,v=(c[2]&32)>>5,b=d===2&&y?v?12:10:y?10:8,_=(c[2]&16)>>4,S=(c[2]&8)>>3,L=(c[2]&4)>>2,I=c[2]&3;n+="."+d+"."+ka(f)+p+"."+ka(b)+"."+_+"."+S+L+I+"."+ka(1)+"."+ka(1)+"."+ka(1)+"."+0,r=Em("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function Em(s,e){const t=bi(e,["dvvC"]),i=t.length?t[0]:bi(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+ka(n)+"."+ka(r)}}function m6(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function uv(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(a=>a!==0)||(es.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${An(r)} -> ${An(t)}`),i.set(t,8))})}function g6(s){const e=[];return ND(s,t=>e.push(t.subarray(8,24))),e}function ND(s,e){bi(s,["moov","trak"]).forEach(i=>{const n=bi(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let a=bi(r,["enca"]);const u=a.length>0;u||(a=bi(r,["encv"])),a.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);bi(d,["sinf"]).forEach(p=>{const y=OD(p);y&&e(y,u)})})})}function OD(s){const e=bi(s,["schm"])[0];if(e){const t=un(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=bi(s,["schi","tenc"])[0];if(i)return i}}}function y6(s,e,t){const i={},n=bi(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,a=0;const u=bi(s,["sidx"]);for(let c=0;cp+y.info.duration||0,0);a=Math.max(a,f+d.earliestPresentationTime/d.timescale)}}a&&At(a)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=a*i[c].timescale-i[c].start)})}return i}function v6(s){const e={valid:null,remainder:null},t=bi(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 Kr(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function L2(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return bi(i,["moof"]).map(c=>{const d=c.byteOffset-8;bi(c,["traf"]).map(p=>{const y=bi(p,["tfdt"]).map(v=>{const b=v[0];let _=ni(v,4);return b===1&&(_*=Math.pow(2,32),_+=ni(v,8)),_/n})[0];return y!==void 0&&(s=y),bi(p,["tfhd"]).map(v=>{const b=ni(v,4),_=ni(v,0)&16777215,S=(_&1)!==0,L=(_&2)!==0,I=(_&8)!==0;let R=0;const $=(_&16)!==0;let B=0;const F=(_&32)!==0;let M=8;b===r&&(S&&(M+=8),L&&(M+=4),I&&(R=ni(v,M),M+=4),$&&(B=ni(v,M),M+=4),F&&(M+=4),e.type==="video"&&(a=y0(e.codec)),bi(p,["trun"]).map(G=>{const D=G[0],O=ni(G,0)&16777215,W=(O&1)!==0;let Y=0;const J=(O&4)!==0,ae=(O&256)!==0;let se=0;const K=(O&512)!==0;let X=0;const ee=(O&1024)!==0,le=(O&2048)!==0;let pe=0;const P=ni(G,4);let Q=8;W&&(Y=ni(G,Q),Q+=4),J&&(Q+=4);let ue=Y+d;for(let he=0;he>1&63;return t===39||t===40}else return(e&31)===6}function zb(s,e,t,i){const n=MD(s);let r=0;r+=e;let a=0,u=0,c=0;for(;r=n.length)break;c=n[r++],a+=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){es.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(n[f++]===181){const y=LD(n,f);if(f+=2,y===49){const v=ni(n,f);if(f+=4,v===1195456820){const b=n[f++];if(b===3){const _=n[f++],S=31&_,L=64&_,I=L?2+S*3:0,R=new Uint8Array(I);if(L){R[0]=_;for(let $=1;$16){const p=[];for(let b=0;b<16;b++){const _=n[f++].toString(16);p.push(_.length==1?"0"+_:_),(b===3||b===5||b===7||b===9)&&p.push("-")}const y=u-16,v=new Uint8Array(y);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 a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),T6([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t)}function S6(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 a=s.buffer,u=An(new Uint8Array(a,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const y=s.getUint32(28);if(!y||i<32+y*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),$c={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 qb(s,e){const t=$c[e];return!!t&&!!t[s.slice(0,4)]}function Ih(s,e,t=!0){return!s.split(",").some(i=>!Kb(i,e,t))}function Kb(s,e,t=!0){var i;const n=Al(t);return(i=n?.isTypeSupported(Nh(s,e)))!=null?i:!1}function Nh(s,e){return`${e}/mp4;codecs=${s}`}function R2(s){if(s){const e=s.substring(0,4);return $c.video[e]}return 2}function Cp(s){const e=PD();return s.split(",").reduce((t,i)=>{const r=e&&y0(i)?9:$c.video[i];return r?(r*2+t)/(t?3:2):($c.audio[i]+t)/(t?2:1)},0)}const cv={};function w6(s,e=!0){if(cv[s])return cv[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;nw6(t.toLowerCase(),e))}function C6(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)&&(I2(s,"audio")||I2(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 I2(s,e){return qb(s,e)&&Kb(s,e)}function k6(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 D6(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 N2(s){const e=Al(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 Rx(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const L6={supported:!0,powerEfficient:!0,smooth:!0},R6={supported:!1,smooth:!1,powerEfficient:!1},BD={supported:!0,configurations:[],decodingInfoResults:[L6]};function FD(s,e){return{supported:!1,configurations:e,decodingInfoResults:[R6],error:s}}function I6(s,e,t,i,n,r){const a=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((y,v)=>{if(v){const b=e.groups[v];if(!b)throw new Error(`Audio track group ${v} not found`);Object.keys(b.channels).forEach(_=>{y[_]=(y[_]||0)+b.channels[_]})}return y},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(y=>y0(y))||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&&At(f)&&Object.keys(p).some(y=>parseInt(y)>f)}function UD(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(BD);const r=[],a=N6(s),u=a.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=a[f%u]),d){p.audio=c[f%d];const y=p.audio.bitrate;p.video&&y&&(p.video.bitrate-=y)}r.push(p)}if(n){const f=navigator.userAgent;if(n.split(",").some(p=>y0(p))&&PD())return Promise.resolve(FD(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const p=P6(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 N6(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=jD(s),n=s.width||640,r=s.height||480,a=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:Nh(D6(c),"video"),width:n,height:r,bitrate:i,framerate:a};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=jD(s);return n&&s.audioGroups?s.audioGroups.reduce((a,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 y=parseFloat(p.channels||"");n.forEach(v=>{const b={contentType:Nh(v,"audio"),bitrate:t?M6(v,r):r};y&&(b.channels=""+y),f.push(b)})}return f},a):a},[]):[]}function M6(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 jD(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function P6(s){let e="";const{audio:t,video:i}=s;if(i){const n=Rx(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=Rx(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const Ix=["NONE","TYPE-0","TYPE-1",null];function B6(s){return Ix.indexOf(s)>-1}const Dp=["SDR","PQ","HLG"];function F6(s){return!!s&&Dp.indexOf(s)>-1}var Km={No:"",Yes:"YES",v2:"v2"};function O2(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 P2(this._audioGroups,e)}hasSubtitleGroup(e){return P2(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 P2(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function U6(){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 j6(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Dp.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&U6(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const $6=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}},fs=(s,e)=>JSON.stringify(s,$6(e));function H6(s,e,t,i,n){const r=Object.keys(s),a=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=a&&parseInt(a)===2;let f=!1,p=!1,y=1/0,v=1/0,b=1/0,_=1/0,S=0,L=[];const{preferHDR:I,allowedVideoRanges:R}=j6(e,n);for(let G=r.length;G--;){const D=s[r[G]];f||(f=D.channels[2]>0),y=Math.min(y,D.minHeight),v=Math.min(v,D.minFramerate),b=Math.min(b,D.minBitrate),R.filter(W=>D.videoRanges[W]>0).length>0&&(p=!0)}y=At(y)?y:0,v=At(v)?v:0;const $=Math.max(1080,y),B=Math.max(30,v);b=At(b)?b:t,t=Math.max(b,t),p||(e=void 0);const F=r.length>1;return{codecSet:r.reduce((G,D)=>{const O=s[D];if(D===G)return G;if(L=p?R.filter(W=>O.videoRanges[W]>0):[],F){if(O.minBitrate>t)return wa(D,`min bitrate of ${O.minBitrate} > current estimate of ${t}`),G;if(!O.hasDefaultAudio)return wa(D,"no renditions with default or auto-select sound found"),G;if(u&&D.indexOf(u.substring(0,4))%5!==0)return wa(D,`audio codec preference "${u}" not found`),G;if(a&&!d){if(!O.channels[a])return wa(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(O.channels)})`),G}else if((!u||d)&&f&&O.channels[2]===0)return wa(D,"no renditions with stereo sound found"),G;if(O.minHeight>$)return wa(D,`min resolution of ${O.minHeight} > maximum of ${$}`),G;if(O.minFramerate>B)return wa(D,`min framerate of ${O.minFramerate} > maximum of ${B}`),G;if(!L.some(W=>O.videoRanges[W]>0))return wa(D,`no variants with VIDEO-RANGE of ${fs(L)} found`),G;if(c&&D.indexOf(c.substring(0,4))%5!==0)return wa(D,`video codec preference "${c}" not found`),G;if(O.maxScore=Cp(G)||O.fragmentError>s[G].fragmentError)?G:(_=O.minIndex,S=O.maxScore,D)},void 0),videoRanges:L,preferHDR:I,minFramerate:v,minBitrate:b,minIndex:_}}function wa(s,e){es.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function $D(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,a)=>{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:a,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,a),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(y=>{c.channels[y]=(c.channels[y]||0)+p.channels[y]}))}),n},{})}function B2(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 Pa(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 su(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 q6(s,e,t,i,n){const r=e[i],u=e.reduce((y,v,b)=>{const _=v.uri;return(y[_]||(y[_]=[])).push(b),y},{})[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=F2(e,i,y=>{if(y.videoRange!==c||y.frameRate!==d||y.codecSet.substring(0,4)!==f)return!1;const v=y.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Pa(s,b,n)>-1});return p>-1?p:F2(e,i,y=>{const v=y.audioGroups,b=t.filter(_=>!v||v.indexOf(_.groupId)!==-1);return Pa(s,b,n)>-1})}function F2(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:a}=this,{autoLevelEnabled:u,media:c}=a;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,p=r?r.duration:n.duration,y=d-f.loading.start,v=a.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 S=_>-1&&_!==b,L=!!t||S;if(!L&&(c.paused||!c.playbackRate||!c.readyState))return;const I=a.mainForwardBufferInfo;if(!L&&I===null)return;const R=this.bwEstimator.getEstimateTTFB(),$=Math.abs(c.playbackRate);if(y<=Math.max(R,1e3*(p/($*2))))return;const B=I?I.len/$:0,F=f.loading.first?f.loading.first-f.loading.start:-1,M=f.loaded&&F>-1,G=this.getBwEstimate(),D=a.levels,O=D[b],W=Math.max(f.loaded,Math.round(p*(n.bitrate||O.averageBitrate)/8));let Y=M?y-F:y;Y<1&&M&&(Y=Math.min(y,f.loaded*8/G));const J=M?f.loaded*1e3/Y:0,ae=R/1e3,se=J?(W-f.loaded)/J:W*8/G+ae;if(se<=B)return;const K=J?J*8:G,X=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,ee=this.hls.config.abrBandWidthUpFactor;let le=Number.POSITIVE_INFINITY,pe;for(pe=b-1;pe>v;pe--){const he=D[pe].maxBitrate,re=!D[pe].details||X;if(le=this.getTimeToLoadFrag(ae,K,p*he,re),le=se||le>p*10)return;M?this.bwEstimator.sample(y-Math.min(R,F),f.loaded):this.bwEstimator.sampleTTFB(y);const P=D[pe].maxBitrate;this.getBwEstimate()*ee>P&&this.resetEstimator(P);const Q=this.findBestLevel(P,v,pe,0,B,1,1);Q>-1&&(pe=Q),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: ${B.toFixed(3)} s + Estimated load time for current fragment: ${se.toFixed(3)} s + Estimated load time for down switch fragment: ${le.toFixed(3)} s + TTFB estimate: ${F|0} ms + Current BW estimate: ${At(G)?G|0:"Unknown"} bps + New BW estimate: ${this.getBwEstimate()|0} bps + Switching to level ${pe} @ ${P|0} bps`),a.nextLoadLevel=a.nextAutoLevel=pe,this.clearTimer();const ue=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===pe&&pe>0){const he=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${pe>0?"and switching down":""} + Fragment duration: ${n.duration.toFixed(3)} s + Time to underbuffer: ${he.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,pe>v){let re=this.findBestLevel(this.hls.levels[v].bitrate,v,pe,0,he,1,1);re===-1&&(re=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=re,this.resetEstimator(this.hls.levels[re].bitrate)}}};S||se>le*2?ue():this.timer=self.setInterval(ue,le*1e3),a.trigger(H.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 Z8(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.FRAG_LOADING,this.onFragLoading,this),e.on(H.FRAG_LOADED,this.onFragLoaded,this),e.on(H.FRAG_BUFFERED,this.onFragBuffered,this),e.on(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(H.LEVEL_LOADED,this.onLevelLoaded,this),e.on(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(H.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.FRAG_LOADING,this.onFragLoading,this),e.off(H.FRAG_LOADED,this.onFragLoaded,this),e.off(H.FRAG_BUFFERED,this.onFragBuffered,this),e.off(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(H.LEVEL_LOADED,this.onLevelLoaded,this),e.off(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(H.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(H.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 Ie.BUFFER_ADD_CODEC_ERROR:case Ie.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Ie.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const a=performance.now(),u=r?r.stats:i.stats,c=a-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,a=n?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;At(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,a=this.hls.levels[t.level],u=(a.loaded?a.loaded.bytes:0)+n.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:u,duration:c},a.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(H.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 a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/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 a=this.hls.firstLevel,u=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} 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 a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[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:a}=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 S=this.findBestLevel(c,a,n,d,0,f,p);if(S>=0)return this.rebufferNotice=-1,S}let y=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const S=this.bitrateTestDelay;S&&(y=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-S,this.info(`bitrate test took ${Math.round(1e3*S)}ms, set first fragment max fetchDuration to ${Math.round(1e3*y)} ms`),f=p=1)}const v=this.findBestLevel(c,a,n,d,y,f,p);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[a],_=i.loadLevelObj;return _&&b?.bitrate<_.bitrate?a: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,a,u){var c;const d=n+r,f=this.lastLoadedFragLevel,p=f===-1?this.hls.firstLevel:f,{fragCurrent:y,partCurrent:v}=this,{levels:b,allAudioTracks:_,loadLevel:S,config:L}=this.hls;if(b.length===1)return 0;const I=b[p],R=!!((c=this.hls.latestLevelDetails)!=null&&c.live),$=S===-1||f===-1;let B,F="SDR",M=I?.frameRate||0;const{audioPreference:G,videoPreference:D}=L,O=this.audioTracksByGroup||(this.audioTracksByGroup=$D(_));let W=-1;if($){if(this.firstSelection!==-1)return this.firstSelection;const K=this.codecTiers||(this.codecTiers=G6(b,O,t,i)),X=H6(K,F,e,G,D),{codecSet:ee,videoRanges:le,minFramerate:pe,minBitrate:P,minIndex:Q,preferHDR:ue}=X;W=Q,B=ee,F=ue?le[le.length-1]:le[0],M=pe,e=Math.max(e,P),this.log(`picked start tier ${fs(X)}`)}else B=I?.codecSet,F=I?.videoRange;const Y=v?v.duration:y?y.duration:0,J=this.bwEstimator.getEstimateTTFB()/1e3,ae=[];for(let K=i;K>=t;K--){var se;const X=b[K],ee=K>p;if(!X)continue;if(L.useMediaCapabilities&&!X.supportedResult&&!X.supportedPromise){const re=navigator.mediaCapabilities;typeof re?.decodingInfo=="function"&&I6(X,O,F,M,e,G)?(X.supportedPromise=UD(X,O,re,this.supportedCache),X.supportedPromise.then(Pe=>{if(!this.hls)return;X.supportedResult=Pe;const Ee=this.hls.levels,Ge=Ee.indexOf(X);Pe.error?this.warn(`MediaCapabilities decodingInfo error: "${Pe.error}" for level ${Ge} ${fs(Pe)}`):Pe.supported?Pe.decodingInfoResults.some(Ve=>Ve.smooth===!1||Ve.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ge} not smooth or powerEfficient: ${fs(Pe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ge} ${fs(Pe)}`),Ge>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${Ge}`),this.hls.removeLevel(Ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Pe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Pe}`)})):X.supportedResult=BD}if((B&&X.codecSet!==B||F&&X.videoRange!==F||ee&&M>X.frameRate||!ee&&M>0&&Mre.smooth===!1))&&(!$||K!==W)){ae.push(K);continue}const le=X.details,pe=(v?le?.partTarget:le?.averagetargetduration)||Y;let P;ee?P=u*e:P=a*e;const Q=Y&&n>=Y*2&&r===0?X.averageBitrate:X.maxBitrate,ue=this.getTimeToLoadFrag(J,P,Q*pe,le===void 0);if(P>=Q&&(K===f||X.loadError===0&&X.fragmentError===0)&&(ue<=J||!At(ue)||R&&!this.bitrateTestDelay||ue${K} adjustedbw(${Math.round(P)})-bitrate=${Math.round(P-Q)} ttfb:${J.toFixed(1)} avgDuration:${pe.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ue.toFixed(1)} firstSelection:${$} codecSet:${X.codecSet} videoRange:${X.videoRange} hls.loadLevel:${S}`)),$&&(this.firstSelection=K),K}}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 HD={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 a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function W6(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!At(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)&&U2(t,i,r)===0||Y6(r,s,Math.min(n,i))))return r;const a=HD.search(e,U2.bind(null,t,i));return a&&(a!==s||!r)?a:r}function Y6(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 U2(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 X6(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function GD(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 HD.search(i,a=>a.cce?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function Rp(s){switch(s.details){case Ie.FRAG_LOAD_TIMEOUT:case Ie.KEY_LOAD_TIMEOUT:case Ie.LEVEL_LOAD_TIMEOUT:case Ie.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function VD(s){return s.details.startsWith("key")}function zD(s){return VD(s)&&!!s.frag&&!s.frag.decryptdata}function j2(s,e){const t=Rp(e);return s.default[`${t?"timeout":"error"}Retry`]}function Wb(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function $2(s){return Ji(Ji({},s),{errorRetry:null,timeoutRetry:null})}function Ip(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function Nx(s){return s===0&&navigator.onLine===!1}var En={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Cr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Z6 extends Xr{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(H.ERROR,this.onError,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(H.ERROR,this.onError,this),e.off(H.ERROR,this.onErrorOut,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.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(a=>n.indexOf(a.groupId)>=0).some(a=>{var u;return(u=a.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 Ie.FRAG_LOAD_ERROR:case Ie.FRAG_LOAD_TIMEOUT:case Ie.KEY_LOAD_ERROR:case Ie.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case Ie.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Ec();return}case Ie.FRAG_GAP:case Ie.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=En.SendAlternateToPenaltyBox;return}case Ie.LEVEL_EMPTY_ERROR:case Ie.LEVEL_PARSING_ERROR:{var a;const c=t.parent===It.MAIN?t.level:n.loadLevel;t.details===Ie.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case Ie.LEVEL_LOAD_ERROR:case Ie.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case Ie.AUDIO_TRACK_LOAD_ERROR:case Ie.AUDIO_TRACK_LOAD_TIMEOUT:case Ie.SUBTITLE_LOAD_ERROR:case Ie.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===Ei.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Ei.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=En.SendAlternateToPenaltyBox,t.errorAction.flags=Cr.MoveAllAlternatesMatchingHost;return}}return;case Ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:En.SendAlternateToPenaltyBox,flags:Cr.MoveAllAlternatesMatchingHDCP};return;case Ie.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Ie.KEY_SYSTEM_NO_SESSION:t.errorAction={action:En.SendAlternateToPenaltyBox,flags:Cr.MoveAllAlternatesMatchingKey};return;case Ie.BUFFER_ADD_CODEC_ERROR:case Ie.REMUX_ALLOC_ERROR:case Ie.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case Ie.INTERNAL_EXCEPTION:case Ie.BUFFER_APPENDING_ERROR:case Ie.BUFFER_FULL_ERROR:case Ie.LEVEL_SWITCH_ERROR:case Ie.BUFFER_STALLED_ERROR:case Ie.BUFFER_SEEK_OVER_HOLE:case Ie.BUFFER_NUDGE_ON_STALL:t.errorAction=Ec();return}t.type===Ft.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Ec())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=j2(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ip(n,r,Rp(e),e.response))return{action:En.RetryRequest,flags:Cr.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:a}=t.config,u=j2(VD(e)?a:r,e),c=t.levels.reduce((f,p)=>f+p.fragmentError,0);if(n&&(e.details!==Ie.FRAG_GAP&&n.fragmentError++,!zD(e)&&Ip(u,c,Rp(e),e.response)))return{action:En.RetryRequest,flags:Cr.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,a;const d=e.details;n.loadError++,d===Ie.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:p,loadLevel:y,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===Ie.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===Ie.BUFFER_ADD_CODEC_ERROR||d===Ie.BUFFER_APPEND_ERROR))&&p.some(({audioCodec:F})=>n.audioCodec!==F),R=e.sourceBufferName==="video"&&(d===Ie.BUFFER_ADD_CODEC_ERROR||d===Ie.BUFFER_APPEND_ERROR)&&p.some(({codecSet:F,audioCodec:M})=>n.codecSet!==F&&n.audioCodec===M),{type:$,groupId:B}=(a=e.context)!=null?a:{};for(let F=p.length;F--;){const M=(F+y)%p.length;if(M!==y&&M>=v&&M<=b&&p[M].loadError===0){var u,c;const G=p[M];if(d===Ie.FRAG_GAP&&_===It.MAIN&&e.frag){const D=p[M].details;if(D){const O=xu(e.frag,D.fragments,e.frag.start);if(O!=null&&O.gap)continue}}else{if($===Ei.AUDIO_TRACK&&G.hasAudioGroup(B)||$===Ei.SUBTITLE_TRACK&&G.hasSubtitleGroup(B))continue;if(_===It.AUDIO&&(u=n.audioGroups)!=null&&u.some(D=>G.hasAudioGroup(D))||_===It.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(D=>G.hasSubtitleGroup(D))||L&&n.audioCodec===G.audioCodec||R&&n.codecSet===G.codecSet||!L&&n.codecSet!==G.codecSet)continue}f=M;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:En.SendAlternateToPenaltyBox,flags:Cr.None,nextAutoLevel:f}}return{action:En.SendAlternateToPenaltyBox,flags:Cr.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case En.DoNothing:break;case En.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==Ie.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 Cr.None:this.switchLevel(e,r);break;case Cr.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=Ix[Ix.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Cr.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let y=f;y--;)if(this.variantHasKey(d[y],c)){var a,u;this.log(`Banned key found in level ${y} (${d[y].bitrate}bps) or audio group "${(a=d[y].audioGroups)==null?void 0:a.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${An(c.keyId||[])}`),d[y].fragmentError++,d[y].loadError++,this.log(`Removing level ${y} with key error (${e.error})`),this.hls.removeLevel(y)}const p=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||a>=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=ec(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=a||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),Am(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]=H2(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=ec(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},a=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||a;for(let f=0;f=p&&c<=y){r.time.push({startPTS:Math.max(a,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(ap){const v=Math.max(a,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<=p)break}return r}getPartialFragment(e){let t=null,i,n,r,a=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&Am(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=f.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Am(t))}getState(e){const t=ec(e),i=this.fragments[t];return i?i.buffered?Am(i)?cn.PARTIAL:cn.OK:cn.APPENDING:cn.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a=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=ec(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:a}=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[a];this.detectEvictedFragments(a,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=ec(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(a=>{const u=this.fragments[a];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=ec(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=H2(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 Am(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 ec(s){return`${s.type}_${s.level}_${s.sn}`}function H2(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Cl={cbc:0,ctr:1};class eU{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 Cl.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Cl.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 tU(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class iU{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],a=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],p=c[2],y=c[3],v=new Uint32Array(256);let b=0,_=0,S=0;for(S=0;S<256;S++)S<128?v[S]=S<<1:v[S]=S<<1^283;for(S=0;S<256;S++){let L=_^_<<1^_<<2^_<<3^_<<4;L=L>>>8^L&255^99,e[b]=L,t[L]=b;const I=v[b],R=v[I],$=v[R];let B=v[L]*257^L*16843008;n[b]=B<<24|B>>>8,r[b]=B<<16|B>>>16,a[b]=B<<8|B>>>24,u[b]=B,B=$*16843009^R*65537^I*257^b*16843008,d[L]=B<<24|B>>>8,f[L]=B<<16|B>>>16,p[L]=B<<8|B>>>24,y[L]=B,b?(b=I^v[v[v[$^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):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:a,remainderData:u}=this;if(n!==Cl.cbc||t.byteLength!==16)return es.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=Kr(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 iU),d.expandKey(t);const f=a;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 sU(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new eU(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(es.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 a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%rU;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(es.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const G2=Math.pow(2,17);class aU{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 yo({type:Ft.NETWORK_ERROR,details:Ie.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,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){c(z2(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new a(n),f=V2(e);e.loader=d;const p=$2(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:G2};e.stats=d.stats;const v={onSuccess:(b,_,S,L)=>{this.resetLoader(e,d);let I=b.data;S.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,_,S,L)=>{this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ji({url:i,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:S,stats:L}))},onAbort:(b,_,S)=>{this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:S,stats:b}))},onTimeout:(b,_,S)=>{this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:S,stats:b}))}};t&&(v.onProgress=(b,_,S,L)=>t({frag:e,part:null,payload:S,networkDetails:L})),d.load(f,y,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(z2(e,t));return}const d=this.loader=r?new r(n):new a(n),f=V2(e,t);e.loader=d;const p=$2(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:G2};t.stats=d.stats,d.load(f,y,{onSuccess:(v,b,_,S)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const L={frag:e,part:t,payload:v.data,networkDetails:S};i(L),u(L)},onError:(v,b,_,S)=>{this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ji({url:f.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:_,stats:S}))},onAbort:(v,b,_)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:_,stats:v}))},onTimeout:(v,b,_)=>{this.resetLoader(e,d),c(new yo({type:Ft.NETWORK_ERROR,details:Ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${y.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),p=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+p}else i.total=Math.max(i.loaded,i.total);const a=i.loading,u=n.loading;a.start?a.first+=u.first-u.start:(a.start=u.start,a.first=u.first),a.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function V2(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(At(n)&&At(r)){var a;let u=n,c=r;if(s.sn==="initSegment"&&oU((a=s.decryptdata)==null?void 0:a.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 z2(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Ft.MEDIA_ERROR,details:Ie.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new yo(i)}function oU(s){return s==="AES-128"||s==="AES-256"}class yo extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class qD extends Xr{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 Xb{constructor(e,t,i,n=0,r=-1,a=!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=Cm(),this.buffering={audio:Cm(),video:Cm(),audiovideo:Cm()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=a}}function Cm(){return{start:0,executeStart:0,executeEnd:0,end:0}}const q2={length:0,start:()=>0,end:()=>0};class ai{static isBuffered(e,t){if(e){const i=ai.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=ai.getBuffered(e);return ai.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 y=r[p-1].end;e[f].start-yy&&(r[p-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let a=0,u,c=t,d=t;for(let f=0;f=p&&t<=y&&(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 W2(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.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 lU(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 uU=/^(\d+)x(\d+)$/,Y2=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ks{constructor(e,t){typeof e=="string"&&(e=ks.parseAttrList(e,t)),as(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=uU.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(Y2.lastIndex=0;(i=Y2.exec(e))!==null;){const a=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(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=Ox(t,u);else if(!d&&!c)switch(a){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":es.warn(`${e}: attribute ${a} is missing quotes`)}n[a]=u}return n}}const cU="com.apple.hls.interstitial";function dU(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function hU(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class WD{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 a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){es.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=as(new ks({}),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"]);At(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?(es.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(At(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===cU}get isValid(){return!!this.id&&!this._badValueForSameId&&At(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 fU=10;class mU{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?At(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||fU}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 Np(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function X2(s,e){return!s&&!e?!0:!s||!e?!1:Np(s,e)}function wc(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Qb(s){switch(s){case"AES-128":case"AES-256":return Cl.cbc;case"AES-256-CTR":return Cl.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Zb(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Mx(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function pU(s){const e=Mx(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function YD(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function XD(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",a=n[1];r?(i.splice(-1,1),t=Zb(a)):t=pU(a)}}return t}const Op=typeof self<"u"?self:void 0;var Ds={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Cn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Wm(s){switch(s){case Cn.FAIRPLAY:return Ds.FAIRPLAY;case Cn.PLAYREADY:return Ds.PLAYREADY;case Cn.WIDEVINE:return Ds.WIDEVINE;case Cn.CLEARKEY:return Ds.CLEARKEY}}function dv(s){switch(s){case Ds.FAIRPLAY:return Cn.FAIRPLAY;case Ds.PLAYREADY:return Cn.PLAYREADY;case Ds.WIDEVINE:return Cn.WIDEVINE;case Ds.CLEARKEY:return Cn.CLEARKEY}}function ch(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 QD=(function(s){return Op!=null&&(s=Op.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function gU(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 yU(n,e,t,i)}function yU(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 vU(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function ZD(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),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const u=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(u){const c=Zb(u).subarray(0,16);return YD(c),c}}return null}let tc={};class Sl{static clearKeyUriToKeyIdMap(){tc={}}static setKeyIdForUri(e,t){tc[e]=t}static addKeyIdForUri(e){const t=Object.keys(tc).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),tc[e]=i,i}constructor(e,t,i,n=[1],r=null,a){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&&!wc(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(AD(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Np(e.keyFormatVersions,this.keyFormatVersions)&&X2(e.iv,this.iv)&&X2(e.keyId,this.keyId)}isSupported(){if(this.method){if(wc(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Cn.FAIRPLAY:case Cn.WIDEVINE:case Cn.PLAYREADY:case Cn.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(wc(this.method)){let r=this.iv;return r||(typeof e!="number"&&(es.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=bU(e)),new Sl(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=tc[this.uri];if(r&&!Np(this.keyId,r)&&Sl.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=XD(this.uri);if(i)switch(this.keyFormat){case Cn.WIDEVINE:if(this.pssh=i,!this.keyId){const r=S6(i.buffer);if(r.length){var n;const a=r[0];this.keyId=(n=a.kids)!=null&&n.length?a.kids[0]:null}}this.keyId||(this.keyId=Q2(t));break;case Cn.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_6(r,null,i),this.keyId=ZD(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=xU(t),r||(r=Q2(t),r||(r=tc[this.uri])),r&&(this.keyId=r,Sl.setKeyIdForUri(this.uri,r))}return this}}function xU(s){const e=s?.[Cn.WIDEVINE];return e?e.keyId:null}function Q2(s){const e=s?.[Cn.PLAYREADY];if(e){const t=XD(e.uri);if(t)return ZD(t)}return null}function bU(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const Z2=/#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,J2=/#EXT-X-MEDIA:(.*)/g,TU=/^#EXT(?:INF|-X-TARGETDURATION):/m,hv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),_U=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 Ba{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(J2.lastIndex=0;(n=J2.exec(e))!==null;){const d=new ks(n[1],i),f=d.TYPE;if(f){const p=u[f],y=r[f]||[];r[f]=y;const v=d.LANGUAGE,b=d["ASSOC-LANGUAGE"],_=d.CHANNELS,S=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?Ba.resolve(d.URI,t):""};if(b&&(I.assocLang=b),_&&(I.channels=_),S&&(I.characteristics=S),L&&(I.instreamId=L),p!=null&&p.length){const R=Ba.findGroup(p,I.groupId)||p[0];sw(I,R,"audioCodec"),sw(I,R,"textCodec")}y.push(I)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){var u;const c={url:t},d=new mU(t),f=d.fragments,p=[];let y=null,v=0,b=0,_=0,S=0,L=0,I=null,R=new lv(n,c),$,B,F,M=-1,G=!1,D=null,O;if(hv.lastIndex=0,d.m3u8=e,d.hasVariableRefs=K2(e),((u=hv.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;($=hv.exec(e))!==null;){G&&(G=!1,R=new lv(n,c),R.playlistOffset=_,R.setStart(_),R.sn=v,R.cc=S,L&&(R.bitrate=L),R.level=i,y&&(R.initSegment=y,y.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime,y.rawProgramDateTime=null),D&&(R.setByteRange(D),D=null)));const ae=$[1];if(ae){R.duration=parseFloat(ae);const se=(" "+$[2]).slice(1);R.title=se||null,R.tagList.push(se?["INF",ae,se]:["INF",ae])}else if($[3]){if(At(R.duration)){R.playlistOffset=_,R.setStart(_),F&&rw(R,F,d),R.sn=v,R.level=i,R.cc=S,f.push(R);const se=(" "+$[3]).slice(1);R.relurl=Ox(d,se),Px(R,I,p),I=R,_+=R.duration,v++,b=0,G=!0}}else{if($=$[0].match(_U),!$){es.warn("No matches on slow regex match for level playlist!");continue}for(B=1;B<$.length&&$[B]===void 0;B++);const se=(" "+$[B]).slice(1),K=(" "+$[B+1]).slice(1),X=$[B+2]?(" "+$[B+2]).slice(1):null;switch(se){case"BYTERANGE":I?R.setByteRange(K,I):R.setByteRange(K);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=K,R.tagList.push(["PROGRAM-DATE-TIME",K]),M===-1&&(M=f.length);break;case"PLAYLIST-TYPE":d.type&&co(d,se,$),d.type=K.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?co(d,se,$):f.length>0&&aw(d,se,$),v=d.startSN=parseInt(K);break;case"SKIP":{d.skippedSegments&&co(d,se,$);const ee=new ks(K,d),le=ee.decimalInteger("SKIPPED-SEGMENTS");if(At(le)){d.skippedSegments+=le;for(let P=le;P--;)f.push(null);v+=le}const pe=ee.enumeratedString("RECENTLY-REMOVED-DATERANGES");pe&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(pe.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&co(d,se,$),d.targetduration=Math.max(parseInt(K),1);break;case"VERSION":d.version!==null&&co(d,se,$),d.version=parseInt(K);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||co(d,se,$),d.live=!1;break;case"#":(K||X)&&R.tagList.push(X?[K,X]:[K]);break;case"DISCONTINUITY":S++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([se]);break;case"BITRATE":R.tagList.push([se,K]),L=parseInt(K)*1e3,At(L)?R.bitrate=L:L=0;break;case"DATERANGE":{const ee=new ks(K,d),le=new WD(ee,d.dateRanges[ee.ID],d.dateRangeTagCount);d.dateRangeTagCount++,le.isValid||d.skippedSegments?d.dateRanges[le.id]=le:es.warn(`Ignoring invalid DATERANGE tag: "${K}"`),R.tagList.push(["EXT-X-DATERANGE",K]);break}case"DEFINE":{{const ee=new ks(K,d);"IMPORT"in ee?lU(d,ee,a):W2(d,ee,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?co(d,se,$):f.length>0&&aw(d,se,$),d.startCC=S=parseInt(K);break;case"KEY":{const ee=ew(K,t,d);if(ee.isSupported()){if(ee.method==="NONE"){F=void 0;break}F||(F={});const le=F[ee.keyFormat];le!=null&&le.matches(ee)||(le&&(F=as({},F)),F[ee.keyFormat]=ee)}else es.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${K}"`);break}case"START":d.startTimeOffset=tw(K);break;case"MAP":{const ee=new ks(K,d);if(R.duration){const le=new lv(n,c);nw(le,ee,i,F),y=le,R.initSegment=y,y.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime)}else{const le=R.byteRangeEndOffset;if(le){const pe=R.byteRangeStartOffset;D=`${le-pe}@${pe}`}else D=null;nw(R,ee,i,F),y=R,G=!0}y.cc=S;break}case"SERVER-CONTROL":{O&&co(d,se,$),O=new ks(K),d.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),d.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&co(d,se,$);const ee=new ks(K);d.partTarget=ee.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ee=d.partList;ee||(ee=d.partList=[]);const le=b>0?ee[ee.length-1]:void 0,pe=b++,P=new ks(K,d),Q=new l6(P,R,c,pe,le);ee.push(Q),R.duration+=Q.duration;break}case"PRELOAD-HINT":{const ee=new ks(K,d);d.preloadHint=ee;break}case"RENDITION-REPORT":{const ee=new ks(K,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ee);break}default:es.warn(`line parsed but not handled: ${$}`);break}}}I&&!I.relurl?(f.pop(),_-=I.duration,d.partList&&(d.fragmentHint=I)):d.partList&&(Px(R,I,p),R.cc=S,d.fragmentHint=R,F&&rw(R,F,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const W=f.length,Y=f[0],J=f[W-1];if(_+=d.skippedSegments*d.targetduration,_>0&&W&&J){d.averagetargetduration=_/W;const ae=J.sn;d.endSN=ae!=="initSegment"?ae:0,d.live||(J.endList=!0),M>0&&(EU(f,M),Y&&p.unshift(Y))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,p.length&&d.dateRangeTagCount&&Y&&JD(p,d),d.endCC=S,d}}function JD(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 a;if(((a=s[f])==null?void 0:a.sn)=u||i===0){var a;const c=(((a=t[i+1])==null?void 0:a.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 y=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=y;v>d;v--){const b=f[v].programDateTime;if(e>=b&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>qb(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 sw(s,e,t){const i=e[t];i&&(s[t]=i)}function EU(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 Px(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function nw(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 rw(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 co(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function aw(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function fv(s,e){const t=e.startPTS;if(At(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 eL(s,e,t,i,n,r,a){i-t<=0&&(a.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(At(f)){const L=Math.abs(f-t);s&&L>s.totalduration?a.warn(`media timestamps and playlist times differ by ${L}s for level ${e.level} ${s.url}`):At(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,p),i=Math.max(i,p),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const y=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,S=s.fragments;for(S[_]=e,b=_;b>0;b--)fv(S[b],S[b-1]);for(b=_;b=0;f--){const p=n[f].initSegment;if(p){i=p;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;kU(s,e,(f,p,y,v)=>{if((!e.startCC||e.skippedSegments)&&p.cc!==f.cc){const b=f.cc-p.cc;for(let _=y;_{var p;f&&(!f.initSegment||f.initSegment.relurl===((p=i)==null?void 0:p.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=AU(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?eL(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):tL(s,e),a.length&&(e.totalduration=e.edge-a[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 AU(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=as({},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 WD(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fs(i[c].attr)}"`)}),r):i}function CU(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],u=e[n+i];a&&u&&a.index===u.index&&a.fragment.sn===u.fragment.sn?t(a,u):i--}}}function kU(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,a=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[a+d];let p=u[d];if(i&&!p&&f&&(p=e.fragments[d]=f),f&&p){t(f,p,d,u);const y=f.relurl,v=p.relurl;if(y&&DU(y,v)){e.playlistParsingError=ow(`media sequence mismatch ${p.sn}:`,s,e,f,p);return}else if(f.cc!==p.cc){e.playlistParsingError=ow(`discontinuity sequence mismatch (${f.cc}!=${p.cc})`,s,e,f,p);return}}}}function ow(s,e,t,i,n){return new Error(`${s} ${n.url} +Playlist starting @${e.startSN} +${e.m3u8} + +Playlist starting @${t.startSN} +${t.m3u8}`)}function tL(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let a=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 DU(s,e){return s!==e&&e?uw(s)!==uw(e):!1}function uw(s){return s.replace(/\?[^?]*$/,"")}function _h(s,e){for(let i=0,n=s.length;is.startCC)}function cw(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function aL(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:a,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,p=c?c.currentTime:0,y=ai.bufferInfo(d||c,p,a.maxBufferHole),v=!y.len;if(this.log(`Media seeking to ${At(p)?p.toFixed(3):p}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===Xe.ENDED)this.resetLoadingState();else if(u){const b=a.maxFragLookUpTolerance,_=u.start-b,S=u.start+u.duration+b;if(v||Sy.end){const L=p>S;(p<_||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(p,1/0,this.playlistType,!0);const b=this.lastCurrentTime;if(p>b&&(this.lastCurrentTime=p),!this.loadingParts){const _=Math.max(y.end,p),S=this.shouldLoadParts(this.getLevelDetails(),_);S&&(this.log(`LL-Part loading ON after seeking to ${p.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=S)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${p} for seek without enough to start`),this.nextLoadPosition=p,v&&(this.startPosition=p)),v&&this.state===Xe.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 aU(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Yb(e.config)}registerListeners(){const{hls:e}=this;e.on(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(H.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Xe.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=Xe.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=ai.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>n&&a{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state,u=r.frag;if(this.fragContextChanged(u)){(a===Xe.FRAG_LOADING||!this.fragCurrent&&a===Xe.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=Xe.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(H.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===Xe.STOPPED||this.state===Xe.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===cn.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,a?a.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)===cn.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(H.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:a}=i,u=r.decryptdata;if(a&&a.byteLength>0&&u!=null&&u.key&&u.iv&&wc(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),u.key.buffer,u.iv.buffer,Qb(u.method)).catch(d=>{throw n.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(H.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===Xe.STOPPED||this.state===Xe.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!==Xe.STOPPED&&(this.state=Xe.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 a=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(u.message),!a||a.mediaKeys?!1:(this.hls.trigger(H.ERROR,{type:Ft.KEY_SYSTEM_ERROR,details:Ie.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?IU.toString(ai.getBuffered(i)):"(detached)"})`),qs(e)){var n;if(e.type!==It.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(u=>!!a[u])){this.state=Xe.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=Xe.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),u=new Xb(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Xe.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(y=>{if(!this.fragContextChanged(y.frag))return this.hls.trigger(H.KEY_LOADED,y),this.state===Xe.KEY_LOADING&&(this.state=Xe.IDLE),y}),this.hls.trigger(H.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,a.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(qs(e)&&(!c||e.sn!==c.sn)){const y=this.shouldLoadParts(t.details,e.end);y!==this.loadingParts&&(this.log(`LL-Part loading ${y?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=y)}if(i=Math.max(e.start,i||0),this.loadingParts&&qs(e)){const y=a.partList;if(y&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const v=this.getNextPart(y,e,i);if(v>-1){const b=y[v];e=this.fragCurrent=b.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${b.index} (${v}/${y.length-1}) of ${this.fragInfo(e,!1,b)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=b.start+b.duration,this.state=Xe.FRAG_LOADING;let _;return u?_=u.then(S=>!S||this.fragContextChanged(S.frag)?null:this.doFragPartsLoad(e,b,t,n)).catch(S=>this.handleFragLoadError(S)):_=this.doFragPartsLoad(e,b,t,n).catch(S=>this.handleFragLoadError(S)),this.hls.trigger(H.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(y,i))return Promise.resolve(null)}}if(qs(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=a.partList)==null?void 0:d.filter(y=>y.loaded).map(y=>`[${y.start}-${y.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} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),At(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Xe.FRAG_LOADING;const f=this.config.progressive&&e.type!==It.SUBTITLE;let p;return f&&u?p=u.then(y=>!y||this.fragContextChanged(y.frag)?null:this.fragmentLoader.load(e,n)).catch(y=>this.handleFragLoadError(y)):p=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([y])=>(!f&&n&&n(y),y)).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(H.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,a)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=p=>{this.fragmentLoader.loadPart(e,p,n).then(y=>{c[p.index]=y;const v=y.part;this.hls.trigger(H.FRAG_LOADED,y);const b=lw(i.details,e.sn,p.index+1)||nL(d,e.sn,p.index+1);if(b)f(b);else return r({frag:e,part:v,partsLoaded:c})}).catch(a)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Ie.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ft.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(H.ERROR,t)}else this.hls.trigger(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Xe.PARSING){!this.fragCurrent&&this.state!==Xe.STOPPED&&this.state!==Xe.ERROR&&(this.state=Xe.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a);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 a=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){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:a}=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=a>-1?lw(c,r,a):null,f=d?d.fragment:sL(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!==Xe.PARSING)return;const{data1:a,data2:u}=e;let c=a;if(u&&(c=Kr(a,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(H.BUFFER_APPENDING,p),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ai.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=ai.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-u>a&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!At(n))return null;const a=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,a)}getFwdBufferInfoAtPos(e,t,i,n){const r=ai.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const u=Math.max(Math.min(r.nextStart,a.end)-t,n);return ai.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,a=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const p=r.initialLiveManifestSize;if(n=a?y:v)||c.start:e;this.log(`Setting startPosition to ${b} to match start frag at live edge. mainStart: ${y} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=b}}else e<=a&&(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===cn.OK||i===cn.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.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=a.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,a}get primaryPrefetch(){if(dw(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(dw(this.config)&&e.type!==It.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const a=n.event;if(a){if(a.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 a=r.length;a--;){const u=r[a].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,a=!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=W6(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=GD(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:a,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&&(a=a.concat(c),u=c.sn);let y;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;y=xu(r,a,e,_)}else y=a[a.length-1];if(y){const b=y.sn-i.startSN,_=this.fragmentTracker.getState(y);if((_===cn.OK||_===cn.PARTIAL&&y.gap)&&(r=y),r&&y.sn===r.sn&&(!p||f[0].fragment.sn>y.sn||!i.live)&&y.level===r.level){const L=a[b+1];y.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&&qs(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!==Xe.FRAG_LOADING_WAITING_RETRY)&&(this.state=Xe.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 a=t.details===Ie.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=Xe.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:p}=u,y=!!p,v=y&&c===En.RetryRequest,b=y&&!u.resolved&&d===Cr.MoveAllAlternatesMatchingHost,_=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&b&&qs(n)&&!n.endList&&_&&!zD(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||b)&&f=t||i&&!Nx(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Xe.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Xe.PARSING||this.state===Xe.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 a=!r;return a&&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(),a}return!1}resetFragmentErrors(e){e===It.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Xe.STOPPED&&(this.state=Xe.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=ai.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Xe.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Xe.STOPPED&&(this.state=Xe.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 y=n?0:eL(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(H.LEVEL_PTS_UPDATED,{details:r,level:i,drift:y,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(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.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=Xe.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(H.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 dw(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class lL{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=NU(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function NU(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function jU(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const v=new Error(`invalid ADTS sampling index:${a}`);s.emit(H.ERROR,H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.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[a];let p=a;(u===5||u===29)&&(p-=3);const y=[u<<3|(p&14)>>1,(p&1)<<7|c<<3];return es.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${a})`),{config:y,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function cL(s,e){return s[e]===255&&(s[e+1]&246)===240}function dL(s,e){return s[e+1]&1?7:9}function iT(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function $U(s,e){return e+5=s.length)return!1;const i=iT(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Pp(s,n)}return!1}function hL(s,e,t,i,n){if(!s.samplerate){const r=jU(e,t,i,n);if(!r)return;as(s,r)}}function fL(s){return 1024*9e4/s}function VU(s,e){const t=dL(s,e);if(e+t<=s.length){const i=iT(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function mL(s,e,t,i,n){const r=fL(s.samplerate),a=i+n*r,u=VU(e,t);let c;if(u){const{frameLength:p,headerLength:y}=u,v=y+p,b=Math.max(0,t+v-e.length);b?(c=new Uint8Array(v-y),c.set(e.subarray(t+y,e.length),0)):c=e.subarray(t+y,t+v);const _={unit:c,pts:a};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:a},length:d,missing:-1}}function zU(s,e){return tT(s,e)&&v0(s,e+6)+10<=s.length-e}function qU(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function pv(s,e=0,t=1/0){return KU(s,e,t,Uint8Array)}function KU(s,e,t,i){const n=WU(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=YU(s)?s.byteOffset:0,u=(a+s.byteLength)/r,c=(a+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 WU(s){return s instanceof ArrayBuffer?s:s.buffer}function YU(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function XU(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=Rr(pv(s.data,1,i)),r=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;const u=Rr(pv(s.data,3+i,a));let c;return n==="-->"?c=Rr(pv(s.data,4+i+a)):c=qU(s.data.subarray(4+i+a)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function QU(s){if(s.size<2)return;const e=Rr(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function ZU(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=Rr(s.data.subarray(t),!0);t+=i.length+1;const n=Rr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Rr(s.data.subarray(1));return{key:s.type,info:"",data:e}}function JU(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=Rr(s.data.subarray(t),!0);t+=i.length+1;const n=Rr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Rr(s.data);return{key:s.type,info:"",data:e}}function ej(s){return s.type==="PRIV"?QU(s):s.type[0]==="W"?JU(s):s.type==="APIC"?XU(s):ZU(s)}function tj(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=v0(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const km=10,ij=10;function pL(s){let e=0;const t=[];for(;tT(s,e);){const i=v0(s,e+6);s[e+5]>>6&1&&(e+=km),e+=km;const n=e+i;for(;e+ij0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Dr.audioId3,duration:Number.POSITIVE_INFINITY});n{if(At(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Dm=null;const rj=[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],aj=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],oj=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],lj=[0,1,1,4];function yL(s,e,t,i,n){if(t+24>e.length)return;const r=vL(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*a,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 vL(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 a=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=rj[c*14+n-1]*1e3,p=aj[(t===3?0:t===2?1:2)*3+r],y=u===3?1:2,v=oj[t][i],b=lj[i],_=v*8*b,S=Math.floor(v*d/p+a)*b;if(Dm===null){const R=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Dm=R?parseInt(R[1]):0}return Dm&&Dm<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:p,channelCount:y,frameLength:S,samplesPerFrame:_}}}function rT(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function xL(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[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 y=0;p===2?y+=2:(p&1&&p!==1&&(y+=2),p&4&&(y+=2));const v=(e[t+6]<<8|e[t+7])>>12-y&1,_=[2,1,2,3,3,4,4,5][p]+v,S=e[t+5]>>3,L=e[t+5]&7,I=new Uint8Array([r<<6|S<<1|L>>2,(L&3)<<6|p<<3|v<<2|c>>4,c<<4&224]),R=1536/u*9e4,$=i+n*R,B=e.subarray(t,t+f);return s.config=I,s.channelCount=_,s.samplerate=u,s.samples.push({unit:B,pts:$}),f}class hj extends nT{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=Ph(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&sT(t)!==void 0&&TL(e,i)<=16)return!1;for(let n=e.length;i{const a=b6(r);if(fj.test(a.schemeIdUri)){const u=fw(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:Dr.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=fw(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:u,pts:u,type:Dr.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 fw(s,e){return At(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class pj{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Yb(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Cl.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),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).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(a,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 a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}class SL{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 a=r,u=[];let c=0,d,f,p,y=-1,v=0;for(r===-1&&(y=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const b={data:t.subarray(y,f),type:v};u.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(a&&c<=4-a&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-a)),f>0&&(b.data=Kr(b.data,t.subarray(0,f)),b.state=0))}c=0&&r>=0){const b={data:t.subarray(y,n),type:v,state:r};u.push(b)}if(u.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=Kr(b.data,t))}return e.naluState=r,u}}class Sh{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&&es.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 gj extends SL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,u,c=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=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 S=d.data;if(c&&S.length>4){const L=this.readSliceType(S);(L===2||L===4||L===7||L===9)&&(_=!0)}if(_){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=_;break}case 5:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{u=!0,zb(d.data,1,i.pts,t.samples);break}case 7:{var v,b;u=!0,c=!0;const _=d.data,S=this.readSPS(_);if(!e.sps||e.width!==S.width||e.height!==S.height||((v=e.pixelRatio)==null?void 0:v[0])!==S.pixelRatio[0]||((b=e.pixelRatio)==null?void 0:b[1])!==S.pixelRatio[1]){e.width=S.width,e.height=S.height,e.pixelRatio=S.pixelRatio,e.sps=[_];const L=_.subarray(1,4);let I="avc1.";for(let R=0;R<3;R++){let $=L[R].toString(16);$.length<2&&($="0"+$),I+=$}e.codec=I}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(p=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Sh(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let a=0;a{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:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:u=!0,zb(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=as(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),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.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,(p=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,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 Sh(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 Sh(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(),a=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),b=t.readUByte(),_=t.readUByte(),S=t.readUByte(),L=t.readUByte(),I=[],R=[];for(let at=0;at0)for(let at=i;at<8;at++)t.readBits(2);for(let at=0;at1&&t.readEG();for(let ht=0;ht0&&ve<16?(Q=dt[ve-1],ue=qe[ve-1]):ve===255&&(Q=t.readBits(16),ue=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()&&(re=t.readBits(32),Pe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const qe=t.readBoolean(),st=t.readBoolean();let ft=!1;(qe||st)&&(ft=t.readBoolean(),ft&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ft&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let yt=0;yt<=i;yt++){he=t.readBoolean();const nt=he||t.readBoolean();let jt=!1;nt?t.readEG():jt=t.readBoolean();const qt=jt?1:t.readUEG()+1;if(qe)for(let Yt=0;Yt>at&1)<<31-at)>>>0;let bt=Ze.toString(16);return a===1&&bt==="2"&&(bt="6"),{codecString:`hvc1.${_t}${a}.${bt}.${r?"H":"L"}${L}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[p,y,v,b,_,S],general_level_idc:L,bit_depth:Y+8,bit_depth_luma_minus8:Y,bit_depth_chroma_minus8:J,min_spatial_segmentation_idc:P,chroma_format_idc:$,frame_rate:{fixed:he,fps:Pe/re}},width:Ve,height:lt,pixelRatio:[Q,ue]}}readPPS(e){const t=new Sh(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 a=1;return r&&n?a=0:r?a=3:n&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const fn=188;class vl{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=vl.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(fn*5,t-fn)+1,n=0;for(;n1&&(a===0&&u>2||c+fn>i))return a}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=vl.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=vl.createTrack("audio",n),this._id3Track=vl.createTrack("id3"),this._txtTrack=vl.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 a=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=a.pid,p=a.pesData,y=u.pid,v=c.pid,b=u.pesData,_=c.pesData,S=null,L=this.pmtParsed,I=this._pmtId,R=e.length;if(this.remainderData&&(e=Kr(this.remainderData,e),R=e.length,this.remainderData=null),R>4;let W;if(O>1){if(W=M+5+e[M+4],W===M+fn)continue}else W=M+4;switch(D){case f:G&&(p&&(r=ic(p,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,r,!1)),p={data:[],size:0}),p&&(p.data.push(e.subarray(W,M+fn)),p.size+=M+fn-W);break;case y:if(G){if(b&&(r=ic(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(W,M+fn)),b.size+=M+fn-W);break;case v:G&&(_&&(r=ic(_,this.logger))&&this.parseID3PES(c,r),_={data:[],size:0}),_&&(_.data.push(e.subarray(W,M+fn)),_.size+=M+fn-W);break;case 0:G&&(W+=e[W]+1),I=this._pmtId=vj(e,W);break;case I:{G&&(W+=e[W]+1);const Y=xj(e,W,this.typeSupported,i,this.observer,this.logger);f=Y.videoPid,f>0&&(a.pid=f,a.segmentCodec=Y.segmentVideoCodec),y=Y.audioPid,y>0&&(u.pid=y,u.segmentCodec=Y.segmentAudioCodec),v=Y.id3Pid,v>0&&(c.pid=v),S!==null&&!L&&(this.logger.warn(`MPEG-TS PMT found at ${M} after unknown PID '${S}'. Backtracking to sync byte @${$} to parse all TS packets.`),S=null,M=$-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:S=D;break}}else B++;B>0&&Ux(this.observer,new Error(`Found ${B} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=p,u.pesData=b,c.pesData=_;const F={audioTrack:u,videoTrack:a,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(F),F}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,a=i.pesData,u=t.pesData,c=n.pesData;let d;if(a&&(d=ic(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=a,u&&(d=ic(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=ic(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 pj(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new gj:e==="hevc"&&(this.videoParser=new yj))}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,y=n.sample.unit.byteLength;if(p===-1)r=Kr(n.sample.unit,r);else{const v=y-p;n.sample.unit.set(r.subarray(0,p),v),e.samples.push(n.sample),i=n.missing}}let a,u;for(a=i,u=r.length;a0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=as({},t,{type:this._videoTrack?Dr.emsg:Dr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Fx(s,e){return((s[e+1]&31)<<8)+s[e+2]}function vj(s,e){return(s[e+10]&31)<<8|s[e+11]}function xj(s,e,t,i,n,r){const a={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 y=e+5,v=p;for(;v>2;){s[y]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=f,a.segmentAudioCodec="ac3"));const _=s[y+1]+2;y+=_,v-=_}}break;case 194:case 135:return Ux(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=f,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=p+5}return a}function Ux(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(H.ERROR,H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function gv(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function ic(s,e){let t=0,i,n,r,a,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Kr(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&&(a=(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,a-u>60*9e4&&(e.warn(`${Math.round((a-u)/9e4)}s delta between PTS and DTS, align them`),a=u)):u=a),r=i[8];let p=r+9;if(s.size<=p)return null;s.size-=p;const y=new Uint8Array(s.size);for(let v=0,b=c.length;v_){p-=_;continue}else i=i.subarray(p),_-=p,p=0;y.set(i,t),t+=_}return n&&(n-=r+3),{data:y,pts:a,dts:u,len:n}}return null}class bj{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 hl=Math.pow(2,32)-1;class Le{static init(){Le.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 Le.types)Le.types.hasOwnProperty(e)&&(Le.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]);Le.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]);Le.STTS=Le.STSC=Le.STCO=r,Le.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Le.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Le.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Le.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);Le.FTYP=Le.box(Le.types.ftyp,a,c,a,u),Le.DINF=Le.box(Le.types.dinf,Le.box(Le.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.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 Le.box(Le.types.mdia,Le.mdhd(e.timescale||0,e.duration||0),Le.hdlr(e.type),Le.minf(e))}static mfhd(e){return Le.box(Le.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"?Le.box(Le.types.minf,Le.box(Le.types.smhd,Le.SMHD),Le.DINF,Le.stbl(e)):Le.box(Le.types.minf,Le.box(Le.types.vmhd,Le.VMHD),Le.DINF,Le.stbl(e))}static moof(e,t,i){return Le.box(Le.types.moof,Le.mfhd(e),Le.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Le.trak(e[t]);return Le.box.apply(null,[Le.types.moov,Le.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(Le.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Le.trex(e[t]);return Le.box.apply(null,[Le.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(hl+1)),n=Math.floor(t%(hl+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 Le.box(Le.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(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const u=Le.box(Le.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 Le.box(Le.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,Le.box(Le.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Le.box(Le.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 Le.box(Le.types.mp4a,Le.audioStsd(e),Le.box(Le.types.esds,Le.esds(e)))}static mp3(e){return Le.box(Le.types[".mp3"],Le.audioStsd(e))}static ac3(e){return Le.box(Le.types["ac-3"],Le.audioStsd(e),Le.box(Le.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return Le.box(Le.types.stsd,Le.STSD,Le.mp4a(e));if(t==="ac3"&&e.config)return Le.box(Le.types.stsd,Le.STSD,Le.ac3(e));if(t==="mp3"&&e.codec==="mp3")return Le.box(Le.types.stsd,Le.STSD,Le.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return Le.box(Le.types.stsd,Le.STSD,Le.avc1(e));if(t==="hevc"&&e.vps)return Le.box(Le.types.stsd,Le.STSD,Le.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,a=Math.floor(i/(hl+1)),u=Math.floor(i%(hl+1));return Le.box(Le.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,a>>24,a>>16&255,a>>8&255,a&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=Le.sdtp(e),n=e.id,r=Math.floor(t/(hl+1)),a=Math.floor(t%(hl+1));return Le.box(Le.types.traf,Le.box(Le.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),Le.box(Le.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),Le.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Le.box(Le.types.trak,Le.tkhd(e),Le.mdia(e))}static trex(e){const t=e.id;return Le.box(Le.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,a=new Uint8Array(r);let u,c,d,f,p,y;for(t+=8+r,a.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,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*u);return Le.box(Le.types.trun,a)}static initSegment(e){Le.types||Le.init();const t=Le.moov(e);return Kr(Le.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 a=r.length;for(let b=0;b>8,i[b][_].length&255]),a),a+=2,u.set(i[b][_],a),a+=i[b][_].length}const d=Le.box(Le.types.hvcC,u),f=e.width,p=e.height,y=e.pixelRatio[0],v=e.pixelRatio[1];return Le.box(Le.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,Le.box(Le.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Le.box(Le.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,v>>24,v>>16&255,v>>8&255,v&255])))}}Le.types=void 0;Le.HDLR_TYPES=void 0;Le.STTS=void 0;Le.STSC=void 0;Le.STCO=void 0;Le.STSZ=void 0;Le.VMHD=void 0;Le.SMHD=void 0;Le.STSD=void 0;Le.FTYP=void 0;Le.DINF=void 0;const EL=9e4;function aT(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function Tj(s,e,t=1,i=!1){return aT(s,e,1/t,i)}function eh(s,e=!1){return aT(s,1e3,1/EL,e)}function _j(s,e=1){return aT(s,EL,1/e)}function mw(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const Sj=10*1e3,Ej=1024,wj=1152,Aj=1536;let sc=null,yv=null;function pw(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 Ym extends Xr{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,sc===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sc=a?parseInt(a[1]):0}if(yv===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);yv=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&&mw(t)} > ${e&&mw(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,a)=>{let u=a.pts,c=u-r;return c<-4294967296&&(t=!0,u=kr(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,a,u,c){let d,f,p,y,v,b,_=r,S=r;const L=e.pid>-1,I=t.pid>-1,R=t.samples.length,$=e.samples.length>0,B=u&&R>0||R>1;if((!L||$)&&(!I||B)||this.ISGenerated||u){if(this.ISGenerated){var M,G,D,O;const ae=this.videoTrackConfig;(ae&&(t.width!==ae.width||t.height!==ae.height||((M=t.pixelRatio)==null?void 0:M[0])!==((G=ae.pixelRatio)==null?void 0:G[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((O=ae.pixelRatio)==null?void 0:O[1]))||!ae&&B||this.nextAudioTs===null&&$)&&this.resetInitSegment()}this.ISGenerated||(p=this.generateIS(e,t,r,a));const W=this.isVideoContiguous;let Y=-1,J;if(B&&(Y=Cj(t.samples),!W&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,Y>0){this.warn(`Dropped ${Y} out of ${R} video samples due to a missing keyframe`);const ae=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(Y),t.dropped+=Y,S+=(t.samples[0].pts-ae)/t.inputTimeScale,J=S}else Y===-1&&(this.warn(`No keyframe found out of ${R} video samples`),b=!1);if(this.ISGenerated){if($&&B){const ae=this.getVideoStartPts(t.samples),K=(kr(e.samples[0].pts,ae)-ae)/t.inputTimeScale;_+=Math.max(0,K),S+=Math.max(0,-K)}if($){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),p=this.generateIS(e,t,r,a)),f=this.remuxAudio(e,_,this.isAudioContiguous,a,I||B||c===It.AUDIO?S:void 0),B){const ae=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),p=this.generateIS(e,t,r,a)),d=this.remuxVideo(t,S,W,ae)}}else B&&(d=this.remuxVideo(t,S,W,0));d&&(d.firstKeyFrame=Y,d.independent=Y!==-1,d.firstKeyFramePTS=J)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=wL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(y=AL(n,r,this._initPTS))),{audio:f,video:d,initSegment:p,independent:b,text:y,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let a=kr(e,r);if(a0?P-1:P].dts&&(I=!0)}I&&a.sort(function(P,Q){const ue=P.dts-Q.dts,he=P.pts-Q.pts;return ue||he}),b=a[0].dts,_=a[a.length-1].dts;const $=_-b,B=$?Math.round($/(c-1)):v||e.inputTimeScale/30;if(i){const P=b-R,Q=P>B,ue=P<-1;if((Q||ue)&&(Q?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${eh(P,!0)} ms (${P}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${eh(-P,!0)} ms (${P}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ue||R>=a[0].pts||sc)){b=R;const he=a[0].pts-P;if(Q)a[0].dts=b,a[0].pts=he;else{let re=!0;for(let Pe=0;Pehe&&re);Pe++){const Ee=a[Pe].pts;if(a[Pe].dts-=P,a[Pe].pts-=P,Pe0?Q.dts-a[P-1].dts:B;if(re=P>0?Q.pts-a[P-1].pts:B,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ve=Math.floor(Ee.maxBufferHole*r),lt=(n?S+n*r:this.nextAudioTs+f)-Q.pts;lt>Ve?(v=lt-Ge,v<0?v=Ge:Y=!0,this.log(`It is approximately ${lt/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=Ge}else v=Ge}const Pe=Math.round(Q.pts-Q.dts);J=Math.min(J,v),se=Math.max(se,v),ae=Math.min(ae,re),K=Math.max(K,re),u.push(pw(Q.key,v,he,Pe))}if(u.length){if(sc){if(sc<70){const P=u[0].flags;P.dependsOn=2,P.isNonSync=0}}else if(yv&&K-ae0&&(n&&Math.abs(R-(L+I))<9e3||Math.abs(kr(_[0].pts,R)-(L+I))<20*f),_.forEach(function(K){K.pts=kr(K.pts,R)}),!i||L<0){const K=_.length;if(_=_.filter(X=>X.pts>=0),K!==_.length&&this.warn(`Removed ${_.length-K} of ${K} samples (initPTS ${I} / ${a})`),!_.length)return;r===0?L=0:n&&!b?L=Math.max(0,R-I):L=_[0].pts-I}if(e.segmentCodec==="aac"){const K=this.config.maxAudioFramesDrift;for(let X=0,ee=L+I;X<_.length;X++){const le=_[X],pe=le.pts,P=pe-ee,Q=Math.abs(1e3*P/a);if(P<=-K*f&&b)X===0&&(this.warn(`Audio frame @ ${(pe/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*P/a)} ms.`),this.nextAudioTs=L=pe-I,ee=pe);else if(P>=K*f&&Q0){M+=S;try{F=new Uint8Array(M)}catch(Q){this.observer.emit(H.ERROR,H.ERROR,{type:Ft.MUX_ERROR,details:Ie.REMUX_ALLOC_ERROR,fatal:!1,error:Q,bytes:M,reason:`fail allocating audio mdat ${M}`});return}y||(new DataView(F.buffer).setUint32(0,M),F.set(Le.types.mdat,4))}else return;F.set(le,S);const P=le.byteLength;S+=P,v.push(pw(!0,d,P,0)),B=pe}const D=v.length;if(!D)return;const O=v[v.length-1];L=B-I,this.nextAudioTs=L+c*O.duration;const W=y?new Uint8Array(0):Le.moof(e.sequenceNumber++,$/c,as({},e,{samples:v}));e.samples=[];const Y=($-I)/a,J=this.nextAudioTs/a,se={data1:W,data2:F,startPTS:Y,endPTS:J,startDTS:Y,endDTS:J,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,se}}function kr(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function Cj(s){for(let e=0;ea.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class kj extends Xr{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:a}=this.initData=ID(e);if(t)p6(e,t);else{const c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=gw(r,ds.AUDIO,this)),a&&(n=gw(a,ds.VIDEO,this));const u={};r&&a?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?u.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,a){var u,c;let{initPTS:d,lastEndTime:f}=this;const p={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};At(f)||(f=this.lastEndTime=r||0);const y=t.samples;if(!y.length)return p;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let b=this.initData;if((u=b)!=null&&u.length||(this.generateInitSegment(y),b=this.initData),!((c=b)!=null&&c.length))return this.warn("Failed to generate initSegment."),p;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const _=y6(y,b,this),S=b.audio?_[b.audio.id]:null,L=b.video?_[b.video.id]:null,I=Lm(L,1/0),R=Lm(S,1/0),$=Lm(L,0,!0),B=Lm(S,0,!0);let F=r,M=0;const G=S&&(!L||!d&&R0?this.lastEndTime=W:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Y=!!b.audio,J=!!b.video;let ae="";Y&&(ae+="audio"),J&&(ae+="video");const se=(b.audio?b.audio.encrypted:!1)||(b.video?b.video.encrypted:!1),K={data1:y,startPTS:O,startDTS:O,endPTS:W,endDTS:W,type:ae,hasAudio:Y,hasVideo:J,nb:1,dropped:0,encrypted:se};p.audio=Y&&!J?K:void 0,p.video=J?K:void 0;const X=L?.sampleCount;if(X){const ee=L.keyFrameIndex,le=ee!==-1;K.nb=X,K.dropped=ee===0||this.isVideoContiguous?0:le?ee:X,K.independent=le,K.firstKeyFrame=ee,le&&L.keyFrameStart&&(K.firstKeyFramePTS=(L.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(p.independent=le),this.isVideoContiguous||(this.isVideoContiguous=le),K.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ee}/${X} dropped: ${K.dropped} start: ${K.firstKeyFramePTS||"NA"}`)}return p.initSegment=v,p.id3=wL(i,r,d,d),n.samples.length&&(p.text=AL(n,r,d)),p}}function Lm(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function Dj(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 gw(s,e,t){const i=s.codec;return i&&i.length>4?i:e===ds.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?kp(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 vo;try{vo=self.performance.now.bind(self.performance)}catch{vo=Date.now}const Xm=[{demux:mj,remux:kj},{demux:vl,remux:Ym},{demux:cj,remux:Ym},{demux:hj,remux:Ym}];Xm.splice(2,0,{demux:dj,remux:Ym});class yw{constructor(e,t,i,n,r,a){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=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=vo();let a=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:p,accurateTimeOffset:y,timeOffset:v,initSegmentChange:b}=n||u,{audioCodec:_,videoCodec:S,defaultInitPts:L,duration:I,initSegmentData:R}=c,$=Lj(a,t);if($&&wc($.method)){const G=this.getDecrypter(),D=Qb($.method);if(G.isSync()){let O=G.softwareDecrypt(a,$.key.buffer,$.iv.buffer,D);if(i.part>-1){const Y=G.flush();O=Y&&Y.buffer}if(!O)return r.executeEnd=vo(),vv(i);a=new Uint8Array(O)}else return this.asyncResult=!0,this.decryptionPromise=G.webCryptoDecrypt(a,$.key.buffer,$.iv.buffer,D).then(O=>{const W=this.push(O,null,i);return this.decryptionPromise=null,W}),this.decryptionPromise}const B=this.needsProbing(f,p);if(B){const G=this.configureTransmuxer(a);if(G)return this.logger.warn(`[transmuxer] ${G.message}`),this.observer.emit(H.ERROR,H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.FRAG_PARSING_ERROR,fatal:!1,error:G,reason:G.message}),r.executeEnd=vo(),vv(i)}(f||p||b||B)&&this.resetInitSegment(R,_,S,I,t),(f||b||B)&&this.resetInitialTimestamp(L),d||this.resetContiguity();const F=this.transmux(a,$,v,y,i);this.asyncResult=Bh(F);const M=this.currentTransmuxState;return M.contiguous=!0,M.discontinuity=!1,M.trackSwitch=!1,r.executeEnd=vo(),F}flush(e){const t=e.transmuxing;t.executeStart=vo();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:u}=n;if(i){const p=i.flush();p&&a.push(this.push(p.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=vo();const p=[vv(e)];return this.asyncResult?Promise.resolve(p):p}const f=c.flush(u);return Bh(f)?(this.asyncResult=!0,f.then(p=>(this.flushRemux(a,p,e),a))):(this.flushRemux(a,f,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,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,a,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=vo()}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:a,remuxer:u}=this;!a||!u||(a.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 a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let p=0,y=Xm.length;p0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const vv=s=>({remuxResult:{},chunkMeta:s});function Bh(s){return"then"in s&&s.then instanceof Function}class Rj{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 Ij{constructor(e,t,i,n,r,a){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=a}}let vw=0;class CL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=vw++,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 y=(p=this.workerContext)==null?void 0:p.objectURL;y&&self.URL.revokeObjectURL(y);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(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.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 a=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===H.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new eT,this.observer.on(H.FRAG_DECRYPTED,a),this.observer.on(H.ERROR,a);const u=N2(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||PU()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=FU(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=BU());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:fs(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new yw(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new yw(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=vw++;const t=this.hls.config,i=N2(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:fs(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),UU(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,a,u,c,d,f){var p,y;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:b}=this,_=a?a.start:r.start,S=r.decryptdata,L=this.frag,I=!(L&&r.cc===L.cc),R=!(L&&d.level===L.level),$=L?d.sn-L.sn:-1,B=this.part?d.part-this.part.index:-1,F=$===0&&d.id>1&&d.id===L?.stats.chunkCount,M=!R&&($===1||$===0&&(B===1||F&&B<=0)),G=self.performance.now();(R||$||r.stats.parsing.start===0)&&(r.stats.parsing.start=G),a&&(B||!M)&&(a.stats.parsing.start=G);const D=!(L&&((p=r.initSegment)==null?void 0:p.url)===((y=L.initSegment)==null?void 0:y.url)),O=new Ij(I,M,c,R,_,D);if(!M||I||D){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: ${R} + contiguous: ${M} + accurateTimeOffset: ${c} + timeOffset: ${_} + initSegmentChange: ${D}`);const W=new Rj(i,n,t,u,f);this.configureTransmuxer(W)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:S,chunkMeta:d,state:O},e instanceof ArrayBuffer?[e]:[]);else if(b){const W=b.push(e,S,d,O);Bh(W)?W.then(Y=>{this.handleTransmuxComplete(Y)}).catch(Y=>{this.transmuxerError(Y,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(W)}}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);Bh(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(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.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 xw=100;class Nj extends Jb{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(H.LEVEL_LOADED,this.onLevelLoaded,this),e.on(H.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(H.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(H.BUFFER_RESET,this.onBufferReset,this),e.on(H.BUFFER_CREATED,this.onBufferCreated,this),e.on(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(H.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(H.FRAG_LOADING,this.onFragLoading,this),e.on(H.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(H.LEVEL_LOADED,this.onLevelLoaded,this),e.off(H.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(H.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(H.BUFFER_RESET,this.onBufferReset,this),e.off(H.BUFFER_CREATED,this.onBufferCreated,this),e.off(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(H.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(H.FRAG_LOADING,this.onFragLoading,this),e.off(H.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){if(i===It.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:a},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===Xe.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===Xe.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,a=this.getLevelDetails(),u=this.getLoadPosition(),c=GD(a,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===Xe.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Xe.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(xw),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Xe.IDLE):this.state=Xe.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Xe.IDLE:this.doTickIdle();break;case Xe.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=Xe.WAITING_INIT_PTS}break}case Xe.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Xe.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Xe.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Xe.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,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=Xe.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,ds.AUDIO,It.AUDIO));const f=this.getFwdBufferInfo(d,It.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(H.BUFFER_EOS,{type:"audio"}),this.state=Xe.ENDED;return}const p=f.len,y=t.maxBufferLength,v=c.fragments,b=v[0].start,_=this.getLoadPosition(),S=this.flushing?_:f.end;if(this.switchingTrack&&n){const R=_;c.PTSKnown&&Rb||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=b+.05)}if(p>=y&&!this.switchingTrack&&SI.end){const $=this.fragmentTracker.getFragAtPos(S,It.MAIN);$&&$.end>I.end&&(I=$,this.mainFragLoading={frag:$,targetBufferTime:null})}if(L.start>I.end)return}this.loadFragment(L,u,S)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Oh(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!==Xe.STOPPED&&(this.setInterval(xw),this.state=Xe.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(H.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:a,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==Xe.STOPPED&&(this.state=Xe.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[a];let p=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var y;p=this.alignPlaylists(r,f.details,(y=this.levelLastLoaded)==null?void 0:y.details)}r.alignedSliding||(oL(r,d),r.alignedSliding||Mp(r,d),p=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,p),this.hls.trigger(H.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===Xe.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=Xe.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:a,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=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let y=this.transmuxer;y||(y=this.transmuxer=new CL(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 S=n?n.index:-1,L=S!==-1,I=new Xb(i.level,i.sn,i.stats.chunkCount,r.byteLength,S,L);y.push(r,b,p,"",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 lL,complete:!1};_.push(new Uint8Array(r)),this.state!==Xe.STOPPED&&(this.state=Xe.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&&qs(t.frag)&&(this.mainFragLoading=t,this.state===Xe.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(qs(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(H.AUDIO_TRACK_SWITCHED,Ji({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Xe.ERROR;return}switch(t.details){case Ie.FRAG_GAP:case Ie.FRAG_PARSING_ERROR:case Ie.FRAG_DECRYPT_ERROR:case Ie.FRAG_LOAD_ERROR:case Ie.FRAG_LOAD_TIMEOUT:case Ie.KEY_LOAD_ERROR:case Ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(It.AUDIO,t);break;case Ie.AUDIO_TRACK_LOAD_ERROR:case Ie.AUDIO_TRACK_LOAD_TIMEOUT:case Ie.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Xe.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Ei.AUDIO_TRACK&&(this.state=Xe.IDLE);break;case Ie.BUFFER_ADD_CODEC_ERROR:case Ie.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case Ie.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Ie.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ds.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ds.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Xe.ENDED&&(this.state=Xe.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:a}=e,u=this.getCurrentContext(a);if(!u){this.resetWhenMissingContext(a);return}const{frag:c,part:d,level:f}=u,{details:p}=f,{audio:y,text:v,id3:b,initSegment:_}=r;if(this.fragContextChanged(c)||!p){this.fragmentTracker.removeFragment(c);return}if(this.state=Xe.PARSING,this.switchingTrack&&y&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const S=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(f,_.tracks,S,a),n.trigger(H.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:i,tracks:_.tracks})}if(y){const{startPTS:S,endPTS:L,startDTS:I,endDTS:R}=y;d&&(d.elementaryStreams[ds.AUDIO]={startPTS:S,endPTS:L,startDTS:I,endDTS:R}),c.setElementaryStreamInfo(ds.AUDIO,S,L,I,R),this.bufferFragmentData(y,c,d,a)}if(b!=null&&(t=b.samples)!=null&&t.length){const S=as({id:i,frag:c,details:p},b);n.trigger(H.FRAG_PARSING_METADATA,S)}if(v){const S=as({id:i,frag:c,details:p},v);n.trigger(H.FRAG_PARSING_USERDATA,S)}}_bufferInitSegment(e,t,i,n){if(this.state!==Xe.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=It.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(H.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(H.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===cn.NOT_LOADED||n===cn.PARTIAL){var r;if(!qs(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=Xe.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Mp(t.details,a)}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:a,channels:u}=this.bufferedTrack;pu({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:u},e,su)||(Lp(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(H.AUDIO_TRACK_SWITCHED,Ji({},e))}}class oT extends Xr{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 a=0;a=0&&f>t.partTarget&&(c+=1)}const d=i&&O2(i);return new M2(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,a=self.performance.now(),u=r.loading.first?Math.max(0,a-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){wU(i,n,this);const I=n.playlistParsingError;if(I){this.warn(I);const R=this.hls;if(!R.config.ignorePlaylistParsingErrors){var d;const{networkDetails:$}=t;R.trigger(H.ERROR,{type:Ft.NETWORK_ERROR,details:Ie.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:$,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const p=this.hls.mainForwardBufferInfo,y=p?p.end-p.len:0,v=(n.edge-y)*1e3,b=iL(n,v);if(n.requestScheduled+b0){if(D>n.targetduration*3)this.log(`Playlist last advanced ${G.toFixed(2)}s ago. Omitting segment and part directives.`),S=void 0,L=void 0;else if(i!=null&&i.tuneInGoal&&D-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${O} with playlist age: ${n.age}`),O=0;else{const W=Math.floor(O/n.targetduration);if(S+=W,L!==void 0){const Y=Math.round(O%n.targetduration/n.partTarget);L+=Y}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${G.toFixed(2)}s goal: ${O} skip sn ${W} to part ${L}`)}n.tuneInGoal=O}if(_=this.getDeliveryDirectives(n,t.deliveryDirectives,S,L),I||!M){n.requestScheduled=a,this.loadingPlaylist(f,_);return}}else(n.canBlockReload||n.canSkipUntil)&&(_=this.getDeliveryDirectives(n,t.deliveryDirectives,S,L));_&&S!==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(),a=n.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const u=a-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=O2(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=Km.No),new M2(i,n,r)}checkRetry(e){const t=e.details,i=Rp(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===En.RetryRequest||!n.resolved&&r===En.SendAlternateToPenaltyBox);if(c){var d;if(a>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=Wb(u,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function kL(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function jx(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class Oj extends oT{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(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.LEVEL_LOADING,this.onLevelLoading,this),e.on(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(H.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.LEVEL_LOADING,this.onLevelLoading,this),e.off(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(H.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(H.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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.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(y=>!i||i.indexOf(y.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(y=>y.default)&&(this.selectDefaultTrack=!1),u.forEach((y,v)=>{y.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const y=Pa(c,u,su);if(y>-1)r=u[y];else{const v=Pa(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(H.AUDIO_TRACKS_UPDATED,f);const p=this.trackId;if(d!==-1&&p===-1)this.setAudioTrack(d);else if(u.length&&p===-1){var a;const y=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${u.length}`);this.warn(y.message),this.hls.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:y})}}}onError(e,t){t.fatal||!t.context||t.context.type===Ei.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&&pu(e,n,su))return n;const r=Pa(e,this.tracksInGroup,su);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const u=q6(e,t.levels,i,a,su);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const a=Pa(e,i);if(a>-1)return i[a]}}}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(H.AUDIO_TRACK_SWITCHING,Ji({},n)),r))return;const a=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(a)}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 a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.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 bw=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,DL="HlsJsTrackRemovedError";class Pj extends Error{constructor(e){super(e),this.name=DL}}class Bj extends Xr{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(H.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=r6(Al(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(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.BUFFER_RESET,this.onBufferReset,this),e.on(H.BUFFER_APPENDING,this.onBufferAppending,this),e.on(H.BUFFER_CODECS,this.onBufferCodecs,this),e.on(H.BUFFER_EOS,this.onBufferEos,this),e.on(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(H.FRAG_PARSED,this.onFragParsed,this),e.on(H.FRAG_CHANGED,this.onFragChanged,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.BUFFER_RESET,this.onBufferReset,this),e.off(H.BUFFER_APPENDING,this.onBufferAppending,this),e.off(H.BUFFER_CODECS,this.onBufferCodecs,this),e.off(H.BUFFER_EOS,this.onBufferEos,this),e.off(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(H.FRAG_PARSED,this.onFragParsed,this),e.off(H.FRAG_CHANGED,this.onFragChanged,this),e.off(H.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 a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?as(i,n.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=as({},this.tracks[a]),this.removeBuffer(a)),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=Al(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&a instanceof c,Tw(i),Fj(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,a=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&a){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: ${fs(i,(c,d)=>c==="initSegment"?void 0:d)}; +transfer tracks: ${fs(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!wD(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(H.MEDIA_DETACHING,{}),this.onMediaAttaching(H.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 y=this.fragmentTracker,v=f.id;if(y.hasFragments(v)||y.hasParts(v)){const S=ai.getBuffered(p);y.detectEvictedFragments(d,S,v,null,!0)}const b=xv(d),_=[d,p];this.sourceBuffers[b]=_,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:a}=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||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&Tw(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(H.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[xv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Mj(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 a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(a||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const p=t[c],{id:y,codec:v,levelCodec:b,container:_,metadata:S,supplemental:L}=p;let I=n[c];const R=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],$=R!=null&&R.buffer?R:I,B=$?.pendingCodec||$?.codec,F=$?.levelCodec;I||(I=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:L,container:_,levelCodec:b,metadata:S,id:y});const M=qm(B,F),G=M?.replace(bw,"$1");let D=qm(v,b);const O=(f=D)==null?void 0:f.replace(bw,"$1");D&&M&&G!==O&&(c.slice(0,5)==="audio"&&(D=kp(D,this.appendSource)),this.log(`switching codec ${B} to ${D}`),D!==(I.pendingCodec||I.codec)&&(I.pendingCodec=D),I.container=_,this.appendChangeType(c,_,D))}),(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 a=this.tracks[e];if(a){const u=a.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};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 a={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&ai.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:a,frag:e},this.append(a,"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:a,frag:u,part:c,chunkMeta:d,offset:f}=t,p=d.buffering[r],{sn:y,cc:v}=u,b=self.performance.now();p.start=b;const _=u.stats.buffering,S=c?c.stats.buffering:null;_.start===0&&(_.start=b),S&&S.start===0&&(S.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 R=i.video,$=R?.buffer;if($&&y!=="initSegment"){const M=c||u,G=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(R.ending||R.ended)){const O=M.start+M.duration*.05,W=$.buffered,Y=this.currentOp("video");!W.length&&!Y?this.blockAudio(M):!Y&&!ai.isBuffered($,O)&&this.lastVideoAppendEndO||D{var M;p.executeStart=self.performance.now();const G=(M=this.tracks[r])==null?void 0:M.buffer;G&&(I?this.updateTimestampOffset(G,B,.1,r,y,v):f!==void 0&&At(f)&&this.updateTimestampOffset(G,f,1e-6,r,y,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const M=self.performance.now();p.executeEnd=p.end=M,_.first===0&&(_.first=M),S&&S.first===0&&(S.first=M);const G={};this.sourceBuffers.forEach(([D,O])=>{D&&(G[D]=ai.getBuffered(O))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(H.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:G})},onError:M=>{var G;const D={type:Ft.MEDIA_ERROR,parent:u.type,details:Ie.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:M,err:M,fatal:!1},O=(G=this.media)==null?void 0:G.error;if(M.code===DOMException.QUOTA_EXCEEDED_ERR||M.name=="QuotaExceededError"||"quota"in M)D.details=Ie.BUFFER_FULL_ERROR;else if(M.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!O)D.errorAction=Ec(!0);else if(M.name===DL&&this.sourceBufferCount===0)D.errorAction=Ec(!0);else{const W=++this.appendErrors[r];this.warn(`Failed ${W}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${O||"no media error"})`),(W>=this.hls.config.appendErrorMaxRetry||O)&&(D.fatal=!0)}this.hls.trigger(H.ERROR,D)}};this.log(`queuing "${r}" append sn: ${y}${c?" p: "+c.index:""} of ${u.type===It.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append(F,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(H.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(([a])=>{a&&this.append(this.getFlushOp(a,n,r),a)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[ds.AUDIOVIDEO]?r.push("audiovideo"):(a[ds.AUDIO]&&r.push("audio"),a[ds.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(H.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(([a])=>{if(a){const u=this.tracks[a];(!t.type||t.type===a)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${a} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var u;return a&&!((u=this.tracks[a])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(H.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(H.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===Ie.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;At(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,a=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(At(u)&&u>=0){const d=Math.max(u,a),f=Math.floor(r/a)*a-d;this.flushBackBuffer(r,a,f)}const c=n.frontBufferFlushThreshold;if(At(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,a),p=Math.floor(r/a)*a+f;this.flushFrontBuffer(r,a,p)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=ai.getBuffered(r);if(u.length>0&&i>u.start(0)){var a;this.hls.trigger(H.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger(H.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(H.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const a=ai.getBuffered(r),u=a.length;if(u<2)return;const c=a.start(u-1),d=a.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(H.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 At(r)?{duration:r}:null;const a=this.media.duration,u=At(i.duration)?i.duration:0;return n>u&&n>a||!At(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(At(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}) ${fs(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(H.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(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.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 a=r,u=e[a];if(this.isPending(u)){const c=this.getTrackCodec(u,a),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${fs(u)}`);try{const f=i.addSourceBuffer(d),p=xv(a),y=[a,f];t[p]=y,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:a,mimeType:d,parent:u.id});return}this.trackSourceBuffer(a,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Ih(i,"video")&&(n=C6(n,i));const r=qm(n,e.levelCodec);return r?t.slice(0,5)==="audio"?kp(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,a)=>{const u=a.removedRanges;u!=null&&u.length&&this.hls.trigger(H.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(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,a){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,a=this.tracks[e],u=a?.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=At(n.duration)?n.duration:1/0,d=At(r.duration)?r.duration:1/0,f=Math.max(0,t),p=Math.min(i,c,d);p>f&&(!a.ending||a.ended)?(a.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 Pj(`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(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(a=>{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 a=i.bind(this,e);n.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}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 Tw(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Fj(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function xv(s){return s==="audio"?1:0}class lT{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(H.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(H.BUFFER_CODECS,this.onBufferCodecs,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(H.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(H.BUFFER_CODECS,this.onBufferCodecs,this),e.off(H.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&&At(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,lT.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 a=Math.max(t,i);for(let u=0;u=a||c.height>=a)&&n(c,e[u+1])){r=u;break}}return r}}const Uj={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},or=Uj,jj={HLS:"h"},$j=jj;class Va{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Va?i:new Va(i))),this.value=e,this.params=t}}const Hj="Dict";function Gj(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 Vj(s,e,t,i){return new Error(`failed to ${s} "${Gj(e)}" as ${t}`,{cause:i})}function za(s,e,t){return Vj("serialize",s,e,t)}class LL{constructor(e){this.description=e}}const _w="Bare Item",zj="Boolean";function qj(s){if(typeof s!="boolean")throw za(s,zj);return s?"?1":"?0"}function Kj(s){return btoa(String.fromCharCode(...s))}const Wj="Byte Sequence";function Yj(s){if(ArrayBuffer.isView(s)===!1)throw za(s,Wj);return`:${Kj(s)}:`}const Xj="Integer";function Qj(s){return s<-999999999999999||99999999999999912)throw za(s,Jj);const t=e.toString();return t.includes(".")?t:`${t}.0`}const t7="String",i7=/[\x00-\x1f\x7f]+/;function s7(s){if(i7.test(s))throw za(s,t7);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function n7(s){return s.description||s.toString().slice(7,-1)}const r7="Token";function Sw(s){const e=n7(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw za(e,r7);return e}function $x(s){switch(typeof s){case"number":if(!At(s))throw za(s,_w);return Number.isInteger(s)?RL(s):e7(s);case"string":return s7(s);case"symbol":return Sw(s);case"boolean":return qj(s);case"object":if(s instanceof Date)return Zj(s);if(s instanceof Uint8Array)return Yj(s);if(s instanceof LL)return Sw(s);default:throw za(s,_w)}}const a7="Key";function Hx(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw za(s,a7);return s}function uT(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${Hx(e)}`:`;${Hx(e)}=${$x(t)}`).join("")}function NL(s){return s instanceof Va?`${$x(s.value)}${uT(s.params)}`:$x(s)}function o7(s){return`(${s.value.map(NL).join(" ")})${uT(s.params)}`}function l7(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw za(s,Hj);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Va||(r=new Va(r));let a=Hx(n);return r.value===!0?a+=uT(r.params):(a+="=",Array.isArray(r.value)?a+=o7(r):a+=NL(r)),a}).join(`,${i}`)}function OL(s,e){return l7(s,e)}const Aa="CMCD-Object",Bs="CMCD-Request",Zl="CMCD-Session",fl="CMCD-Status",u7={br:Aa,ab:Aa,d:Aa,ot:Aa,tb:Aa,tpb:Aa,lb:Aa,tab:Aa,lab:Aa,url:Aa,pb:Bs,bl:Bs,tbl:Bs,dl:Bs,ltc:Bs,mtp:Bs,nor:Bs,nrr:Bs,rc:Bs,sn:Bs,sta:Bs,su:Bs,ttfb:Bs,ttfbb:Bs,ttlb:Bs,cmsdd:Bs,cmsds:Bs,smrt:Bs,df:Bs,cs:Bs,ts:Bs,cid:Zl,pr:Zl,sf:Zl,sid:Zl,st:Zl,v:Zl,msd:Zl,bs:fl,bsd:fl,cdn:fl,rtp:fl,bg:fl,pt:fl,ec:fl,e:fl},c7={REQUEST:Bs};function d7(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 h7(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?d7(e):{};return i.reduce((r,a)=>{var u;const c=u7[a]||n[a]||c7.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[a]=s[a],r},t)}function f7(s){return["ot","sf","st","e","sta"].includes(s)}function m7(s){return typeof s=="number"?At(s):s!=null&&s!==""&&s!==!1}const ML="event";function p7(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 Qm=s=>Math.round(s),Gx=(s,e)=>Array.isArray(s)?s.map(t=>Gx(t,e)):s instanceof Va&&typeof s.value=="string"?new Va(Gx(s.value,e),s.params):(e.baseUrl&&(s=p7(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Rm=s=>Qm(s/100)*100,g7=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Va&&typeof s.value=="string"?t=new Va([s]):typeof s=="string"&&(t=[s])),Gx(t,e)},y7={br:Qm,d:Qm,bl:Rm,dl:Rm,mtp:Rm,nor:g7,rtp:Rm,tb:Qm},PL="request",BL="response",cT=["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"],v7=["e"],x7=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function x0(s){return x7.test(s)}function b7(s){return cT.includes(s)||v7.includes(s)||x0(s)}const FL=["d","dl","nor","ot","rtp","su"];function T7(s){return cT.includes(s)||FL.includes(s)||x0(s)}const _7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function S7(s){return cT.includes(s)||FL.includes(s)||_7.includes(s)||x0(s)}const E7=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function w7(s){return E7.includes(s)||x0(s)}const A7={[BL]:S7,[ML]:b7,[PL]:T7};function UL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||PL,r=i===1?w7:A7[n];let a=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(a=a.filter(u));const c=n===BL||n===ML;c&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const d=as({},y7,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return a.sort().forEach(p=>{let y=s[p];const v=d[p];if(typeof v=="function"&&(y=v(y,f)),p==="v"){if(i===1)return;y=i}p=="pr"&&y===1||(c&&p==="ts"&&!At(y)&&(y=Date.now()),m7(y)&&(f7(p)&&typeof y=="string"&&(y=new LL(y)),t[p]=y))}),t}function C7(s,e={}){const t={};if(!s)return t;const i=UL(s,e),n=h7(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[a,u])=>{const c=OL(u,{whitespace:!1});return c&&(r[a]=c),r},t)}function k7(s,e,t){return as(s,C7(e,t))}const D7="CMCD";function L7(s,e={}){return s?OL(UL(s,e),{whitespace:!1}):""}function R7(s,e={}){if(!s)return"";const t=L7(s,e);return encodeURIComponent(t)}function I7(s,e={}){if(!s)return"";const t=R7(s,e);return`${D7}=${t}`}const Ew=/CMCD=[^&#]+/;function N7(s,e,t){const i=I7(e,t);if(!i)return s;if(Ew.test(s))return s.replace(Ew,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class O7{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:or.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:a}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(a||r).duration*1e3,ot:c};(c===or.VIDEO||c===or.AUDIO||c==or.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=a?this.getNextPart(a):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(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHED,this.onMediaDetached,this),e.on(H.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHED,this.onMediaDetached,this),e.off(H.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:$j.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){as(t,this.createData());const i=t.ot===or.INIT||t.ot===or.VIDEO||t.ot===or.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((a,u)=>(n.includes(u)&&(a[u]=t[u]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),k7(e.headers,t,r)):e.url=N7(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:a}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===a)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return or.TIMED_TEXT;if(e.sn==="initSegment")return or.INIT;if(t==="audio")return or.AUDIO;if(t==="main")return this.hls.audioTracks.length?or.VIDEO:or.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===or.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===or.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ai.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,a,u){t(r),this.loader.load(r,a,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,a,u){t(r),this.loader.load(r,a,u)}}}}const M7=3e5;class P7 extends Xr{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(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.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===En.SendAlternateToPenaltyBox&&i.flags===Cr.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?a=this.getPathwayForGroupId(u,d,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),t.details===Ie.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: ${a} levels: ${n&&n.length} priorities: ${fs(r)} penalized: ${fs(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]>M7&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,rL(t),this.hls.trigger(H.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:a,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===a))return;const d=this.getLevelsForPathway(u).map(f=>{const p=new ks(f.attrs);p["PATHWAY-ID"]=a;const y=p.AUDIO&&`${p.AUDIO}_clone_${a}`,v=p.SUBTITLES&&`${p.SUBTITLES}_clone_${a}`;y&&(i[p.AUDIO]=y,p.AUDIO=y),v&&(n[p.SUBTITLES]=v,p.SUBTITLES=v);const b=jL(f.uri,p["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new Oh({attrs:p,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 S=1;S{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":S,"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||y.url),S&&this.clonePathways(S);const I={steeringManifest:b,url:n.toString()};this.hls.trigger(H.STEERING_MANIFEST_LOADED,I),L&&this.updatePathwayPriority(L)},onError:(f,p,y,v)=>{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 b=this.timeToLoad*1e3;if(f.code===429){const _=this.loader;if(typeof _?.getResponseHeader=="function"){const S=_.getResponseHeader("Retry-After");S&&(b=parseFloat(S)*1e3)}this.log(`Steering manifest ${p.url} rate limited`);return}this.scheduleRefresh(this.uri||p.url,b)},onTimeout:(f,p,y)=>{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 ww(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const u=as({},a);return u.details=void 0,u.attrs=new ks(u.attrs),u.url=u.attrs.URI=jL(a.url,a.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 jL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let u;e&&(u=a?.[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 Ac extends Xr{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=Ac.CDMCleanupPromise?[Ac.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 a=Object.keys(this.keySystemAccessPromises);a.length||(a=ch(this.config));const u=a.map(dv).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(a=>{const u=Wm(a);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 v=un(new Uint8Array(n)),b=Zb(JSON.parse(v).sinf),_=OD(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=An(c),{keyIdToKeySessionPromise:f,mediaKeySessions:p}=this;let y=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(b,i,n,"encrypted-event-key-match")),y.catch(L=>this.handleError(L));break}}y||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${p.length}.`))}).catch(a=>this.handleError(a))}},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(H.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(H.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(H.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(H.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(H.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(H.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(H.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(H.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(H.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=(a,u,c)=>!!a&&c.indexOf(a)===u,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(p=>a({keySystem:f,mediaKeys:p})).catch(p=>{d.length?c(d):p instanceof Ar?u(p):u(new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.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 QD===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=gU(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],u=(n=a)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fs(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=a=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(y=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(y,e,v):y)));return p.catch(y=>{this.error(`Failed to create media-keys for "${e}"}: ${y}`)}),p})}return u.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${An(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=Im(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 ${An(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})=>dv(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=dv(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=ch(this.config),i=e.map(Wm).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 a.catch(u=>{if(u instanceof Ar){const c=Ji({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new Ar(c,u.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ar){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${An(i.keyId||[])})`:""}`),this.hls.trigger(H.ERROR,e.data)}else this.error(e.message),this.hls.trigger(H.ERROR,{type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Im(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Wm(e.keyFormat),r=n?[n]:ch(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=ch(this.config)),e.length===0)throw new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fs({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,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));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 a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const b=a.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=Im(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 eT,f=e._onmessage=b=>{const _=e.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:S,message:L}=b;this.log(`"${S}" message event for session "${_.sessionId}" message size: ${L.byteLength}`),S==="license-request"||S==="license-renewal"?this.renewLicense(e,L).catch(I=>{d.eventNames().length?d.emit("error",I):this.handleError(I)}):S==="license-release"?e.keySystem===Ds.FAIRPLAY&&this.updateKeySession(e,Mx("acknowledged")).then(()=>this.removeSession(e)).catch(I=>this.handleError(I)):this.warn(`unhandled media key message type "${S}"`)},p=(b,_)=>{_.keyStatus=b;let S;b.startsWith("usable")?d.emit("resolved"):b==="internal-error"||b==="output-restricted"||b==="output-downscaled"?S=Aw(b,_.decryptdata):b==="expired"?S=new Error(`key expired (keyId: ${u})`):b==="released"?S=new Error("key released"):b==="status-pending"||this.warn(`unhandled key status change "${b}" (keyId: ${u})`),S&&(d.eventNames().length?d.emit("error",S):this.handleError(S))},y=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const S=this.getKeyStatuses(e);if(!Object.keys(S).some($=>S[$]!=="status-pending"))return;if(S[u]==="expired"){this.log(`Expired key ${fs(S)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let I=S[u];if(I)p(I,e);else{var R;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(R=e.keyStatusTimeouts)[u]||(R[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const B=this.getKeyStatus(e.decryptdata);if(B&&B!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${B} from other session.`),p(B,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} (${fs(S)}).`)}};qn(e.mediaKeysSession,"message",f),qn(e.mediaKeysSession,"keystatuseschange",y);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 Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.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===Ds.PLAYREADY&&r.length===16){const u=An(r);t[u]=i,YD(r)}const a=An(r);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=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((a,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:(y,v,b,_)=>{a(y.data)},onError:(y,v,b,_)=>{u(new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:Ji({url:c.url,data:void 0},y)},`"${e}" certificate request failed (${r}). Status: ${y.code} (${y.text})`))},onTimeout:(y,v,b)=>{u(new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(y,v,b)=>{u(new Error("aborted"))}};n.load(c,f,p)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.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,y=r.length;p in key message");return Mx(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(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||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 a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);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,a,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 Ar({type:Ft.KEY_SYSTEM_ERROR,details:Ie.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:a,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${a}). 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,a,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,qn(i,"encrypted",this.onMediaEncrypted),qn(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(dr(e,"encrypted",this.onMediaEncrypted),dr(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,Sl.clearKeyUriToKeyIdMap();const r=n.length;Ac.CDMCleanupPromise=Promise.all(n.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).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: ${An(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:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));const{drmSystemOptions:u}=this.config;return(vU(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(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.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(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}Ac.CDMCleanupPromise=void 0;function Im(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return An(s.keyId)}function B7(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 Ar 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 Aw(s,e){const t=s==="output-restricted",i=t?Ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ar({type:Ft.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class F7{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(H.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(H.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(H.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,a=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*a/r,d=this.hls;if(d.trigger(H.FPS_DROP,{currentDropped:a,currentDecoded:u,totalDroppedFrames:i}),c>0&&a>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(H.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 $L(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 HL(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){es.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){es.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function fc(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 Vx(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=j7(s.cues,e,t);for(let a=0;as[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,a=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function Zm(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=Zm(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.LEVEL_LOADING,this.onLevelLoading,this),e.on(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(H.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(H.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.LEVEL_LOADING,this.onLevelLoading,this),e.off(H.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(H.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(H.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;Zm(i.textTracks).forEach(a=>{fc(a)})}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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.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(a=>n?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(f=>f.default)&&(this.selectDefaultTrack=!1),a.forEach((f,p)=>{f.id=p});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=Pa(u,a);if(f>-1)r=a[f];else{const p=Pa(u,this.tracks);r=this.tracks[p]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(H.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=Pa(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),a=e.details,u=a?.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&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(H.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Zm(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>jx(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||!At(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(H.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:a,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(H.SUBTITLE_TRACK_SWITCH,{id:a,groupId:u,name:c,type:d,url:f});const p=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(p)}}function H7(){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 Eh(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Cc=.025;let Bp=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function G7(s,e,t){return`${s.identifier}-${t+1}-${Eh(e)}`}class V7{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 bv(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=bv(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=At(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 bv(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 z7(this)}}function bv(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function lc(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class q7{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(H.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const a=()=>{this.hasDetails=!0};r.once(H.LEVEL_LOADED,a),r.once(H.AUDIO_TRACK_LOADED,a),r.once(H.SUBTITLE_TRACK_LOADED,a),r.on(H.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(H.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(H.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=GL(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=ai.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=ai.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: ${lc(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Cw=.033;class K7 extends Xr{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)):[];a.length&&a.sort((d,f)=>{const p=d.cue.pre,y=d.cue.post,v=f.cue.pre,b=f.cue.post;if(p&&!v)return-1;if(v&&!p||y&&!b)return 1;if(b&&!y)return-1;if(!p&&!v&&!y&&!b){const _=d.startTime,S=f.startTime;if(_!==S)return _-S}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=a,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,a=this.parseSchedule(n,e);(i||t.length||r?.length!==a.length||a.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=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let a=0;a!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,p)=>{const y=f.cue.pre,v=f.cue.post,b=e[p-1]||null,_=f.appendInPlace,S=v?r:f.startOffset,L=f.duration,I=f.timelineOccupancy===Bp.Range?L:0,R=f.resumptionOffset,$=b?.startTime===S,B=S+f.cumulativeDuration;let F=_?B+L:S+R;if(y||!v&&S<=0){const G=d;d+=I,f.timelineStart=B;const D=a;a+=L,i.push({event:f,start:B,end:F,playout:{start:D,end:a},integrated:{start:G,end:d}})}else if(S<=r){if(!$){const O=S-c;if(O>Cw){const W=c,Y=d;d+=O;const J=a;a+=O;const ae={previousEvent:e[p-1]||null,nextEvent:f,start:W,end:W+O,playout:{start:J,end:a},integrated:{start:Y,end:d}};i.push(ae)}else O>0&&b&&(b.cumulativeDuration+=O,i[i.length-1].end=S)}v&&(F=B),f.timelineStart=B;const G=d;d+=I;const D=a;a+=L,i.push({event:f,start:B,end:F,playout:{start:D,end:a},integrated:{start:G,end:d}})}else return;const M=f.resumeTime;v||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),a===p?u.cumulativeDuration=r:(r=0,a=p),!f&&u.snapOptions.in&&(u.resumeAnchor=xu(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+1Cc?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(a=>{const u=t[a].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`),!1;const d=xu(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=a==="audio"?.175:0;return Math.abs(d.start-i){const S=y.data,L=S?.ASSETS;if(!Array.isArray(L)){const I=this.assignAssetListError(e,Ie.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),b.url,v,_);this.hls.trigger(H.ERROR,I);return}e.assetListResponse=S,this.hls.trigger(H.ASSET_LIST_LOADED,{event:e,assetListResponse:S,networkDetails:_})},onError:(y,v,b,_)=>{const S=this.assignAssetListError(e,Ie.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${y.code} ${y.text} (${v.url})`),v.url,_,b);this.hls.trigger(H.ERROR,S)},onTimeout:(y,v,b)=>{const _=this.assignAssetListError(e,Ie.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,y,b);this.hls.trigger(H.ERROR,_)}};return u.load(c,f,p),this.hls.trigger(H.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,a){return e.error=i,{type:Ft.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:a,stats:r}}}function kw(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Nm(s,e){return`[${s}] Advancing timeline position to ${e}`}class Y7 extends Xr{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 a=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),a&&i=u.end){var c;const v=this.findItemIndex(u);let b=this.schedule.findItemIndexAtTime(i);if(b===-1&&(b=v+(a?-1:1),this.log(`seeked ${a?"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),!a&&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,p=d.duration||0;if(a&&i=f+p){var y;(y=u.event)!=null&&y.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 a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const a=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(_=>sa(_))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let y=null,v=null;a&&(y=this.updateItem(a,this.timelinePos),this.itemsMatch(a,y)?this.playingItem=y: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(S=>{this.clearAssetPlayer(S.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const S=_.assetItem.timelineStart,L=_.timelineOffset-S;if(L)try{_.timelineOffset=S}catch(I){Math.abs(L)>Cc&&this.warn(`${I} ("${_.assetId}" ${_.timelineOffset}->${S})`)}}}),p||n){if(this.hls.trigger(H.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(a)&&f.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(y,a),b&&v!==y&&this.trimInPlace(v,b),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new W7(e),this.schedule=new K7(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(H.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(H.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(H.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(H.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(H.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(H.BUFFER_APPENDED,this.onBufferAppended,this),e.on(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(H.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(H.MEDIA_ENDED,this.onMediaEnded,this),e.on(H.ERROR,this.onError,this),e.on(H.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(H.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(H.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(H.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(H.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(H.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(H.BUFFER_CODECS,this.onBufferCodecs,this),e.off(H.BUFFER_APPENDED,this.onBufferAppended,this),e.off(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(H.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(H.MEDIA_ENDED,this.onMediaEnded,this),e.off(H.ERROR,this.onError,this),e.off(H.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){dr(e,"play",this.onPlay),dr(e,"pause",this.onPause),dr(e,"seeking",this.onSeeking),dr(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;qn(i,"seeking",this.onSeeking),qn(i,"timeupdate",this.onTimeupdate),qn(i,"play",this.onPlay),qn(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,y,v,b,_)=>{if(p){let S=p[y].start;const L=p.event;if(L){if(y==="playout"||L.timelineOccupancy!==Bp.Point){const I=i(v);I?.interstitial===L&&(S+=I.assetItem.startOffset+I[_])}}else{const I=b==="bufferedPos"?a():e[b];S+=I-p.start}return S}return 0},r=(p,y)=>{var v;if(p!==0&&y!=="primary"&&(v=e.schedule)!=null&&v.length){var b;const _=e.schedule.findItemIndexAtTime(p),S=(b=e.schedule.items)==null?void 0:b[_];if(S){const L=S[y].start-S.start;return p+L}}return p},a=()=>{const p=e.bufferedPos;return p===Number.MAX_VALUE?u("primary"):Math.max(p,0)},u=p=>{var y,v;return(y=e.primaryDetails)!=null&&y.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[p])||0},c=(p,y)=>{var v,b;const _=e.effectivePlayingItem;if(_!=null&&(v=_.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${p} "${y}"`);const S=e.effectivePlayingItem,L=e.schedule.findItemIndexAtTime(p,y),I=(b=e.schedule.items)==null?void 0:b[L],R=e.getBufferingPlayer(),$=R?.interstitial,B=$?.appendInPlace,F=S&&e.itemsMatch(S,I);if(S&&(B||F)){const M=i(e.playingAsset),G=M?.media||e.primaryMedia;if(G){const D=y==="primary"?G.currentTime:n(S,y,e.playingAsset,"timelinePos","currentTime"),O=p-D,W=(B?D:G.currentTime)+O;if(W>=0&&(!M||B||W<=M.duration)){G.currentTime=W;return}}}if(I){let M=p;if(y!=="primary"){const D=I[y].start,O=p-D;M=I.start+O}const G=!e.isInterstitial(I);if((!e.isInterstitial(S)||S.event.appendInPlace)&&(G||I.event.appendInPlace)){const D=e.media||(B?R?.media:null);D&&(D.currentTime=M)}else if(S){const D=e.findItemIndex(S);if(L>D){const W=e.schedule.findJumpRestrictedIndex(D+1,L);if(W>D){e.setSchedulePosition(W);return}}let O=0;if(G)e.timelinePos=M,e.checkBuffer();else{const W=I.event.assetList,Y=p-(I[y]||I).start;for(let J=W.length;J--;){const ae=W[J];if(ae.duration&&Y>=ae.startOffset&&Y{const p=e.effectivePlayingItem;if(e.isInterstitial(p))return p;const y=t();return e.isInterstitial(y)?y:null},f={get bufferedEnd(){const p=t(),y=e.bufferingItem;if(y&&y===p){var v;return n(y,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-y.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const p=d(),y=e.effectivePlayingItem;return y&&y===p?n(y,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-y.playout.start:0},set currentTime(p){const y=d(),v=e.effectivePlayingItem;v&&v===y&&c(p+v.playout.start,"playout")},get duration(){const p=d();return p?p.playout.end-p.playout.start:0},get assetPlayers(){var p;const y=(p=d())==null?void 0:p.event.assetList;return y?y.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var p;const y=(p=d())==null?void 0:p.event;return y&&e.effectivePlayingAsset?y.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 a()},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,y=p?.event;if(y&&!y.restrictions.skip){const v=e.findItemIndex(p);if(y.appendInPlace){const b=p.playout.start+p.event.duration;c(b+.001,"playout")}else e.advanceAfterAssetEnded(y,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||!At(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} ${fs(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 a=this.hls,u=e!==a,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(a.media)c&&(r=a.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 ${fs(r)}`);else if(!this.detachedData||a.media===t){const b=this.playerQueue;b.length>1&&b.forEach(_=>{if(u&&_.interstitial.appendInPlace!==c){const S=_.interstitial;this.clearInterstitial(_.interstitial,null),S.appendInPlace=!1,S.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${S}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const p=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",y=p&&r?r:t;this.log(`${p?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(y===r&&v){const b=u&&e.assetId===v.assetIdAtEnd;y.overrides={duration:v.duration,endOfStream:!u||b,cueRemoval:!u}}e.attachMedia(y)}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(Nm("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){const a=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(a);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=Tv(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const u=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=Tv(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,u=r.length;if(a>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&sa(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(a)){const f=a.event,p=this.playingAsset,y=p?.identifier,v=y?this.getAssetPlayer(y):null;if(v&&y&&(!this.eventItemsMatch(a,r)||t!==void 0&&y!==f.assetList[t].identifier)){var c;const b=f.findAssetIndex(p);if(this.log(`INTERSTITIAL_ASSET_ENDED ${b+1}/${f.assetList.length} ${lc(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger(H.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:b,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),b);return}this.retreiveMediaSource(y,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${sa(a)}`),f.hasPlayed=!0,this.hls.trigger(H.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,a,u)}return}}this.advanceSchedule(e,n,t,a,u)}advanceSchedule(e,t,i,n,r){const a=this.schedule;if(!a)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const p=f.interstitial,y=a.findEventIndex(p.identifier);(ye+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=a.findAssetIndex(f,this.timelinePos);const b=Tv(f,i-1);if(f.isAssetPastPlayoutLimit(b)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=b}const p=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let y=this.preloadAssets(f,i);if(this.eventItemsMatch(u,p||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${sa(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(H.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(y||(y=this.getAssetPlayer(v.identifier)),y===null||y.destroyed){const b=f.assetList.length;this.warn(`asset ${i+1}/${b} player destroyed ${f}`),y=this.createAssetPlayer(f,v,i),y.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(y,i,t,e,c),this.shouldPlay&&kw(y.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&kw(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(a.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 ${sa(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(Nm("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${sa(e)}`),this.hls.trigger(H.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.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:ai.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(Nm("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(H.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(H.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=Ji(Ji({},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=Ji(Ji({},this.altSelection),{},{audio:i});return}const r=Ji(Ji({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Ji(Ji({},this.altSelection),{},{subtitles:i});return}const r=Ji(Ji({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=B2(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=B2(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,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=ai.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${sa(e)} (was ${sa(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=ai.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 a=this.playingItem,u=this.findItemIndex(a);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=y.event)!=null&&d.appendInPlace&&e+.01>=y.start)&&(c=p),this.isInterstitial(r)){const v=r.event;if(p-u>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(y);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&y.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 a=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 ${sa(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,p)=>{const y=this.getAssetPlayer(f.identifier);y&&(p===d&&y.loadSource(),y.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(H.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 a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(a,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,a=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const y=this.playingItem;!this.isInterstitial(y)&&(y==null||(u=y.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 y=f-c;y>0&&(d=Math.round(y*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(!a&&n){for(let d=t;d{this.hls.trigger(H.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const B=t.duration;B&&${if($.live){var B;const G=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:Ft.OTHER_ERROR,details:Ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:G},O=((B=this.schedule)==null?void 0:B.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,O,i,G.message);return}const F=$.edge-$.fragmentStart,M=t.duration;(_||M===null||F>M)&&(_=!1,this.log(`Interstitial asset "${p}" duration change ${M} > ${F}`),t.duration=F,this.updateSchedule())};b.on(H.LEVEL_UPDATED,($,{details:B})=>S(B)),b.on(H.LEVEL_PTS_UPDATED,($,{details:B})=>S(B)),b.on(H.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const L=($,B)=>{const F=this.getAssetPlayer(p);if(F&&B.tracks){F.off(H.BUFFER_CODECS,L),F.tracks=B.tracks;const M=this.primaryMedia;this.bufferingAsset===F.assetItem&&M&&!F.media&&this.bufferAssetPlayer(F,M)}};b.on(H.BUFFER_CODECS,L);const I=()=>{var $;const B=this.getAssetPlayer(p);if(this.log(`buffered to end of asset ${B}`),!B||!this.schedule)return;const F=this.schedule.findEventIndex(e.identifier),M=($=this.schedule.items)==null?void 0:$[F];this.isInterstitial(M)&&this.advanceAssetBuffering(M,t)};b.on(H.BUFFERED_TO_END,I);const R=$=>()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;this.shouldPlay=!0;const F=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,F,$)};return b.once(H.MEDIA_ENDED,R(i)),b.once(H.PLAYOUT_LIMIT_REACHED,R(1/0)),b.on(H.ERROR,($,B)=>{if(!this.schedule)return;const F=this.getAssetPlayer(p);if(B.details===Ie.BUFFER_STALLED_ERROR){if(F!=null&&F.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(B,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${B.error} ${e}`)}),b.on(H.DESTROYING,()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;const B=new Error(`Asset player destroyed unexpectedly ${p}`),F={fatal:!0,type:Ft.OTHER_ERROR,details:Ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:B};this.handleAssetItemError(F,e,this.schedule.findEventIndex(e.identifier),i,B.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${lc(t)}`),this.hls.trigger(H.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&&sa(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:a,assetItem:u,assetId:c}=e,d=a.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} ${lc(u)}`),this.hls.trigger(H.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:a,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:a}=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=a;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&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(p&&!wD(p,e.tracks)){const y=new Error(`Asset ${lc(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(p)}')`),v={fatal:!0,type:Ft.OTHER_ERROR,details:Ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:y},b=r.findAssetIndex(a);this.handleAssetItemError(v,r,u,b,y.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),a=e.assetList[r];if(a){const u=this.getAssetPlayer(a.identifier);if(u){const c=u.currentTime||n-a.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,S,f,c+f,L,_.URI),f+=L}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const p=this.waitingItem,y=p?.event.identifier===a;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(y){var b;const _=this.schedule.findEventIndex(a),S=(b=this.schedule.items)==null?void 0:b[_];if(S){if(!this.playingItem&&this.timelinePos>S.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(S)}this.setSchedulePosition(_)}else if(v?.identifier===a){const _=r.assetList[0];if(_){const S=this.getAssetPlayer(_.identifier);if(v.appendInPlace){const L=this.primaryMedia;S&&L&&this.bufferAssetPlayer(S,L)}else S&&S.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case Ie.ASSET_LIST_PARSING_ERROR:case Ie.ASSET_LIST_LOAD_ERROR:case Ie.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case Ie.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 X7 extends Jb{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(H.LEVEL_LOADED,this.onLevelLoaded,this),e.on(H.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(H.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(H.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(H.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(H.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(H.LEVEL_LOADED,this.onLevelLoaded,this),e.off(H.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(H.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(H.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(H.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(H.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Xe.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)||(qs(i)&&(this.fragPrevious=i),this.state=Xe.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){a=r[d];break}const c=i.start+i.duration;a?a.end=c:(a={start:u,end:c},r.push(a)),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(a=>{for(let u=0;unew Oh(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new Oh(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!==Xe.STOPPED&&this.setInterval(Dw)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:a,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 [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(i=c.details)!=null&&i.live){if(a.deltaUpdateFailed)return;const p=this.mainDetails;if(!p){this.startFragRequested=!1;return}const y=p.fragments[0];if(!c.details)a.hasProgramDateTime&&p.hasProgramDateTime?(Mp(a,p),d=a.fragmentStart):y&&(d=y.start,Bx(a,d));else{var f;d=this.alignPlaylists(a,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&y&&(d=y.start,Bx(a,d))}p&&!this.startFragRequested&&this.setStartPosition(p,d)}c.details=a,this.levelLastLoaded=c,u===n&&(this.hls.trigger(H.SUBTITLE_TRACK_UPDATED,{details:a,id:u,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Xe.IDLE&&(xu(null,a.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&&wc(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Qb(n.method)).catch(u=>{throw r.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(H.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:a,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=Xe.IDLE})}}doTick(){if(!this.media){this.state=Xe.IDLE;return}if(this.state===Xe.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(),a=ai.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=a,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const p=d.fragments,y=p.length,v=d.edge;let b=null;const _=this.fragPrevious;if(uv-I?0:I;b=xu(_,p,Math.max(p[0].start,u),R),!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 Z7={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},VL=s=>String.fromCharCode(Z7[s]||s),na=15,ho=100,J7={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},e9={17:2,18:4,21:6,22:8,23:10,19:13,20:15},t9={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},i9={25:2,26:4,29:6,30:8,31:10,27:13,28:15},s9=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class n9{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;es.log(`${this.time} [${e}] ${i}`)}}}const Jl=function(e){const t=[];for(let i=0;iho&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ho)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=VL(e);if(this.pos>=ho){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 = "+fs(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+fs(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 Lw{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 _v(i),this.nonDisplayedMemory=new _v(i),this.lastOutputScreen=new _v(i),this.currRollUpRow=this.displayedMemory.rows[na-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[na-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: "+fs(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 Rw{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=l9(),this.logger=void 0;const n=this.logger=new n9;this.channels=[null,new Lw(e,t,n),new Lw(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"["+Jl([t[i],t[i+1]])+"] -> ("+Jl([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(o9(n,r,c)){Om(null,null,c),this.logger.log(3,()=>"Repeated command ("+Jl([n,r])+") is dropped");continue}Om(n,r,this.cmdHistory),a=this.parseCmd(n,r),a||(a=this.parseMidrow(n,r)),a||(a=this.parsePAC(n,r)),a||(a=this.parseBackgroundAttributes(n,r))}else Om(null,null,c);if(!a&&(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?")}!a&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Jl([n,r])+" orig: "+Jl([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,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.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 ("+Jl([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 a=e<=23?1:2;t>=64&&t<=95?i=a===1?J7[e]:t9[e]:i=a===1?e9[e]:i9[e];const u=this.channels[a];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!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 a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+VL(a)+"' in channel "+i),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Jl(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 a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=s9[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(a),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");F=O,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},p,{get:function(){return M},set:function(O){const W=n(O);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");M=W,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},p,{get:function(){return G},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");G=O,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},p,{get:function(){return D},set:function(O){const W=n(O);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");D=W,this.hasBeenReset=!0}})),f.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class u9{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function qL(s){function e(i,n,r,a){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(a||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 c9{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 KL(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const a=n[r].split(t);if(a.length!==2)continue;const u=a[0],c=a[1];e(u,c)}}const zx=new dT(0,0,""),Mm=zx.align==="middle"?"middle":"center";function d9(s,e,t){const i=s;function n(){const u=qL(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 c9;KL(u,function(y,v){let b;switch(y){case"region":for(let _=t.length-1;_>=0;_--)if(t[_].id===v){d.set(y,t[_].region);break}break;case"vertical":d.alt(y,v,["rl","lr"]);break;case"line":b=v.split(","),d.integer(y,b[0]),d.percent(y,b[0])&&d.set("snapToLines",!1),d.alt(y,b[0],["auto"]),b.length===2&&d.alt("lineAlign",b[1],["start",Mm,"end"]);break;case"position":b=v.split(","),d.percent(y,b[0]),b.length===2&&d.alt("positionAlign",b[1],["start",Mm,"end","line-left","line-right","auto"]);break;case"size":d.percent(y,v);break;case"align":d.alt(y,v,["start",Mm,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&zx.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",Mm);let p=d.get("position","auto");p==="auto"&&zx.position===50&&(p=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=p}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=n(),a(),r(s,e)}function WL(s){return s.replace(//gi,` +`)}class h9{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new u9,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,a=0;for(r=WL(r);a")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{d9(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&&(a=!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 f9=/\r\n|\n\r|\n|\r/g,Sv=function(e,t,i=0){return e.slice(i,i+t.length)===t},m9=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(!At(t)||!At(i)||!At(n)||!At(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function hT(s,e,t){return Eh(s.toString())+Eh(e.toString())+Eh(t)}const p9=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(;(a=r)!=null&&a.new;){var a;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function g9(s,e,t,i,n,r,a){const u=new h9,c=Rr(new Uint8Array(s)).trim().replace(f9,` +`).split(` +`),d=[],f=e?_j(e.baseTime,e.timescale):0;let p="00:00.000",y=0,v=0,b,_=!0;u.oncue=function(S){const L=t[i];let I=t.ccOffset;const R=(y-f)/9e4;if(L!=null&&L.new&&(v!==void 0?I=t.ccOffset=L.start:p9(t,i,R)),R){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}I=R-t.presentationOffset}const $=S.endTime-S.startTime,B=kr((S.startTime+I-v)*9e4,n*9e4)/9e4;S.startTime=Math.max(B,0),S.endTime=Math.max(B+$,0);const F=S.text.trim();S.text=decodeURIComponent(encodeURIComponent(F)),S.id||(S.id=hT(S.startTime,S.endTime,F)),S.endTime>0&&d.push(S)},u.onparsingerror=function(S){b=S},u.onflush=function(){if(b){a(b);return}r(d)},c.forEach(S=>{if(_)if(Sv(S,"X-TIMESTAMP-MAP=")){_=!1,S.slice(16).split(",").forEach(L=>{Sv(L,"LOCAL:")?p=L.slice(6):Sv(L,"MPEGTS:")&&(y=parseInt(L.slice(7)))});try{v=m9(p)/1e3}catch(L){b=L}return}else S===""&&(_=!1);u.parse(S+` +`)}),u.flush()}const Ev="stpp.ttml.im1t",YL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,XL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,y9={left:"start",center:"center",right:"end",start:"start",end:"end"};function Iw(s,e,t,i){const n=bi(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>Rr(u)),a=Tj(e.baseTime,1,e.timescale);try{r.forEach(u=>t(v9(u,a)))}catch(u){i(u)}}function v9(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},a=Object.keys(r).reduce((p,y)=>(p[y]=n.getAttribute(`ttp:${y}`)||r[y],p),{}),u=n.getAttribute("xml:space")!=="preserve",c=Nw(wv(n,"styling","style")),d=Nw(wv(n,"layout","region")),f=wv(n,"body","[begin]");return[].map.call(f,p=>{const y=QL(p,u);if(!y||!p.hasAttribute("begin"))return null;const v=Cv(p.getAttribute("begin"),a),b=Cv(p.getAttribute("dur"),a);let _=Cv(p.getAttribute("end"),a);if(v===null)throw Ow(p);if(_===null){if(b===null)throw Ow(p);_=v+b}const S=new dT(v-e,_-e,y);S.id=hT(S.startTime,S.endTime,S.text);const L=d[p.getAttribute("region")],I=c[p.getAttribute("style")],R=x9(L,I,c),{textAlign:$}=R;if($){const B=y9[$];B&&(S.lineAlign=B),S.align=$}return as(S,R),S}).filter(p=>p!==null)}function wv(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Nw(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function QL(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?QL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function x9(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((u,c)=>{const d=Av(e,i,c)||Av(s,i,c)||Av(n,i,c);return d&&(u[c]=d),u},{})}function Av(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Ow(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Cv(s,e){if(!s)return null;let t=qL(s);return t===null&&(YL.test(s)?t=b9(s,e):XL.test(s)&&(t=T9(s,e))),t}function b9(s,e){const t=YL.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 T9(s,e){const t=XL.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 Pm{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 _9{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=Pw(),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(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(H.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(H.FRAG_LOADING,this.onFragLoading,this),e.on(H.FRAG_LOADED,this.onFragLoaded,this),e.on(H.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(H.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(H.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(H.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(H.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(H.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(H.FRAG_LOADING,this.onFragLoading,this),e.off(H.FRAG_LOADED,this.onFragLoaded,this),e.off(H.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(H.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(H.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(H.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(H.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Pm(this,"textTrack1"),t=new Pm(this,"textTrack2"),i=new Pm(this,"textTrack3"),n=new Pm(this,"textTrack4");this.cea608Parser1=new Rw(1,e,t),this.cea608Parser2=new Rw(3,i,n)}addCues(e,t,i,n,r){let a=!1;for(let u=r.length;u--;){const c=r[u],d=S9(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,d/(i-t)>.5))return}if(a||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(H.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){const{unparsedVttFrags:u}=this;i===It.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:a}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(H.FRAG_LOADED,c):this.hls.trigger(H.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{fc(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Pw(),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===Ev);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(kL(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,u=a?Zm(a.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let p=null;for(let y=0;yd!==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 a=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(H.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}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]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.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:a,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&a&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.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,a="stats"in t;if(r==null||!r.encrypted||a){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===Ev?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(H.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Iw(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(H.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(H.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,u=r.length-1;if(!r[i.cc]&&u===-1){a.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?Kr(i.initSegment.data,new Uint8Array(n)).buffer:n;g9(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(H.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const p=f.message==="Missing initPTS for VTT MPEGTS";p?a.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(p&&u>i.cc)&&c.trigger(H.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Iw(t,this.initPTS[e.cc],()=>{i.textCodec=Ev,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=>HL(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(H.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===It.SUBTITLE&&this.onFragLoaded(H.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;rVx(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>Vx(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=WL(d.trim()),b=hT(e,t,v);s!=null&&(p=s.cues)!=null&&p.getCueById(b)||(a=new f(e,t,v),a.id=b,a.line=y+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((y,v)=>y.line==="auto"||v.line==="auto"?0:y.line>8&&v.line>8?v.line-y.line:y.line-v.line),n.forEach(y=>HL(s,y))),n}};function A9(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const C9=/(\d+)-(\d+)\/(\d+)/;class Bw{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||R9,this.controller=new self.AbortController,this.stats=new Vb}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=k9(e,this.controller.signal),a=e.responseType==="arraybuffer",u=a?"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&&At(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Bh(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(p=>{var y;this.response=this.loader=p;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)),!p.ok){const{status:_,statusText:S}=p;throw new I9(S||"fetch, bad network response",_,p)}n.loading.first=v,n.total=L9(p.headers)||n.total;const b=(y=this.callbacks)==null?void 0:y.onProgress;return b&&At(t.highWaterMark)?this.loadProgressively(p,n,e,t.highWaterMark,b):a?p.arrayBuffer():e.responseType==="json"?p.json():p.text()}).then(p=>{var y,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 _=p[u];_&&(n.loaded=n.total=_);const S={url:b.url,data:p,code:b.status},L=(y=this.callbacks)==null?void 0:y.onProgress;L&&!At(t.highWaterMark)&&L(n,e,p,b),(v=this.callbacks)==null||v.onSuccess(S,n,e,b)}).catch(p=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=p&&p.code||0,b=p?p.message:null;(y=this.callbacks)==null||y.onError({code:v,text:b},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 a=new lL,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,p=f.length;return t.loaded+=p,p=n&&r(t,i,a.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function k9(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(as({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function D9(s){const e=C9.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function L9(s){const e=s.get("Content-Range");if(e){const i=D9(e);if(At(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function R9(s,e){return new self.Request(s.url,e)}class I9 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const N9=/^age:\s*[\d.]+\s*$/im;class JL{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 Vb,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(a=>{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(a=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:a.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:a}=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&&At(r)?r:a,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 a,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 S=(a=this.callbacks)==null?void 0:a.onProgress;S&&S(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 p=r.loadPolicy.errorRetry,y=i.retry,v={url:e.url,data:void 0,code:d};if(Ip(p,y,!1,v))this.retry(p);else{var c;es.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(Ip(e,t,!0))this.retry(e);else{var i;es.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=Wb(e,i.retry),i.retry++,es.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&&N9.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},M9=Ji(Ji({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:JL,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:K6,bufferController:Bj,capLevelController:lT,errorController:Z6,fpsController:F7,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:QD,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},P9()),{},{subtitleStreamController:X7,subtitleTrackController:$7,timelineController:_9,audioStreamController:Nj,audioTrackController:Oj,emeController:Ac,cmcdController:O7,contentSteeringController:P7,interstitialsController:Y7});function P9(){return{cueHandler:w9,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 B9(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=qx(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const u=`${a==="level"?"playlist":a}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const p=`${a}Loading${f}`,y=e[p];if(y!==void 0&&c){d.push(p);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=y,v.maxTimeToFirstByteMs=y;break;case"MaxRetry":v.errorRetry.maxNumRetry=y,v.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":v.errorRetry.retryDelayMs=y,v.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=y,v.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${fs(e[u])}`)}),Ji(Ji({},i),e)}function qx(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(qx):Object.keys(s).reduce((e,t)=>(e[t]=qx(s[t]),e),{}):s}function F9(s,e){const t=s.loader;t!==Bw&&t!==JL?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):A9()&&(s.loader=Bw,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Jm=2,U9=.1,j9=.05,$9=100;class H9 extends qD{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(H.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.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($9),this.mediaSource=t.mediaSource;const i=this.media=t.media;qn(i,"playing",this.onMediaPlaying),qn(i,"waiting",this.onMediaWaiting),qn(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(dr(i,"playing",this.onMediaPlaying),dr(i,"waiting",this.onMediaWaiting),dr(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 a=this.media;if(!a)return;const{seeking:u}=a,c=this.seeking&&!u,d=!this.seeking&&u,f=a.paused&&!u||a.ended||a.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&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(H.MEDIA_ENDED,{stalled:!1}));return}if(!ai.getBuffered(a).length){this.nudgeRetry=0;return}const p=ai.bufferInfo(a,e,0),y=p.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const F=Fw(this.hls.inFlightFragments,e),M=p.len>Jm,G=!y||F||y-e>Jm&&!v.getPartialFragment(e);if(M||G)return;this.moved=!1}const b=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(p.len>0)&&!y)return;const M=Math.max(y,p.start||0)-e,D=!!(b!=null&&b.live)?b.targetduration*2:Jm,O=Bm(e,v);if(M>0&&(M<=D||O)){a.paused||this._trySkipBufferHole(O);return}}const _=r.detectStallWithCurrentTimeMs,S=self.performance.now(),L=this.waiting;let I=this.stalled;if(I===null)if(L>0&&S-L<_)I=this.stalled=L;else{this.stalled=S;return}const R=S-I;if(!u&&(R>=_||L)&&this.hls){var $;if((($=this.mediaSource)==null?void 0:$.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-(b?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(H.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(p),!this.media||!this.hls)return}const B=ai.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(B,R,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(H.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=ai.bufferedInfo(ai.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=ai.timeRangesToArray(n),u=ai.bufferedInfo(a,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 y=Bm(e,this.fragmentTracker);y&&"fragment"in y?y=y.fragment:y||(y=void 0);const v=ai.bufferInfo(this.media,e,0);this.hls.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,frag:y,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:a,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!a||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=Bm(i,a);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),a=i.getFragAtPos(n,It.MAIN);if(r&&a)return a.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 a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${fs(e)})`);this.warn(a.message),t.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.BUFFER_STALLED_ERROR,fatal:!1,error:a,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 a=n.currentTime,u=ai.bufferInfo(n,a,0),c=a0&&u.len<1&&n.readyState<3,y=c-a;if(y>0&&(f||p)){if(y>r.maxBufferHole){let b=!1;if(a===0){const _=i.getAppendedFrag(0,It.MAIN);_&&c<_.end&&(b=!0)}if(!b&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Fw(this.hls.inFlightFragments,c))return 0;let S=!1,L=e.end;for(;L"u"))return self.VTTCue||self.TextTrackCue}function kv(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,fs(n?Ji({type:n},i):i))}return r}const Fm=(()=>{const s=Kx();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class V9{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(H.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(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(H.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(H.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(H.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(H.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&&fc(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;tFm&&(p=Fm),p-f<=0&&(p=f+G9);for(let v=0;vf.type===Dr.audioId3&&c:n==="video"?d=f=>f.type===Dr.emsg&&u:d=f=>f.type===Dr.audioId3&&c||f.type===Dr.emsg&&u,Vx(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:a}=this.hls.config;if(!r)return;const u=Kx();if(i&&n&&!a){const{fragmentStart:_,fragmentEnd:S}=e;let L=this.assetCue;L?(L.startTime=_,L.endTime=S):u&&(L=this.assetCue=kv(u,_,S,{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 p=this.dateRangeCuesAppended;if(c&&t){var y;if((y=c.cues)!=null&&y.length){const _=Object.keys(p).filter(S=>!f.includes(S));for(let S=_.length;S--;){var v;const L=_[S],I=(v=p[L])==null?void 0:v.cues;delete p[L],I&&Object.keys(I).forEach(R=>{const $=I[R];if($){$.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue($)}catch{}}})}}else p=this.dateRangeCuesAppended={}}const b=e.fragments[e.fragments.length-1];if(!(f.length===0||!At(b?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Y!==L.id){const J=d[Y];if(J.class===L.class&&J.startDate>L.startDate&&(!W||L.startDate.01&&(Y.startTime=I,Y.endTime=F);else if(u){let J=L.attr[W];hU(W)&&(J=AD(J));const se=kv(u,I,F,{key:W,data:J},Dr.dateRange);se&&(se.id=S,this.id3Track.addCue(se),$[W]=se,a&&(W==="X-ASSET-LIST"||W==="X-ASSET-URL")&&se.addEventListener("enter",this.onEventCueEnter))}}p[S]={cues:$,dateRange:L,durationKnown:B}}}}}class z9{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:a}=this.config;if(!r||a===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,a)),y=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(p,Math.max(1,y));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:a,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:a*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,a=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,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(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(H.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(H.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(H.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(H.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===Ie.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 q9 extends oT{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(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(H.LEVEL_LOADED,this.onLevelLoaded,this),e.on(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(H.FRAG_BUFFERED,this.onFragBuffered,this),e.on(H.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(H.LEVEL_LOADED,this.onLevelLoaded,this),e.off(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(H.FRAG_BUFFERED,this.onFragBuffered,this),e.off(H.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={},a={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const p=f.attrs;let{audioCodec:y,videoCodec:v}=f;y&&(f.audioCodec=y=kp(y,i)||void 0),v&&(v=f.videoCodec=k6(v));const{width:b,height:_,unknownCodecs:S}=f,L=S?.length||0;if(u||(u=!!(b&&_)),c||(c=!!v),d||(d=!!y),L||y&&!this.isAudioSupported(y)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${p.CODECS}"`);return}const{CODECS:I,"FRAME-RATE":R,"HDCP-LEVEL":$,"PATHWAY-ID":B,RESOLUTION:F,"VIDEO-RANGE":M}=p,D=`${`${B||"."}-`}${f.bitrate}-${F}-${R}-${I}-${M}-${$}`;if(r[D])if(r[D].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const O=a[D]+=1;f.attrs["PATHWAY-ID"]=new Array(O+1).join(".");const W=this.createLevel(f);r[D]=W,n.push(W)}else r[D].addGroupId("audio",p.AUDIO),r[D].addGroupId("text",p.SUBTITLES);else{const O=this.createLevel(f);r[D]=O,a[D]=1,n.push(O)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new Oh(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=FD(n,[])}return t}isAudioSupported(e){return Ih(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ih(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var a;let u=[],c=[],d=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:I,videoRange:R,width:$,height:B})=>(!!I||!!($&&B))&&F6(R))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let I="no level with compatible codecs found in manifest",R=I;t.levels.length&&(R=`one or more CODECS in variant not supported: ${fs(t.levels.map(B=>B.attrs.CODECS).filter((B,F,M)=>M.indexOf(B)===F))}`,this.warn(R),I+=` (${R})`);const $=new Error(I);this.hls.trigger(H.ERROR,{type:Ft.MEDIA_ERROR,details:Ie.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:$,reason:R})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(I=>!I.audioCodec||this.isAudioSupported(I.audioCodec)),jw(u)),t.subtitles&&(c=t.subtitles,jw(c));const p=d.slice(0);d.sort((I,R)=>{if(I.attrs["HDCP-LEVEL"]!==R.attrs["HDCP-LEVEL"])return(I.attrs["HDCP-LEVEL"]||"")>(R.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&I.height!==R.height)return I.height-R.height;if(I.frameRate!==R.frameRate)return I.frameRate-R.frameRate;if(I.videoRange!==R.videoRange)return Dp.indexOf(I.videoRange)-Dp.indexOf(R.videoRange);if(I.videoCodec!==R.videoCodec){const $=R2(I.videoCodec),B=R2(R.videoCodec);if($!==B)return B-$}if(I.uri===R.uri&&I.codecSet!==R.codecSet){const $=Cp(I.codecSet),B=Cp(R.codecSet);if($!==B)return B-$}return I.averageBitrate!==R.averageBitrate?I.averageBitrate-R.averageBitrate:0});let y=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==p.length)){for(let I=0;I$&&$===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=B)}break}const b=r&&!n,_=this.hls.config,S=!!(_.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:S&&!b&&u.some(I=>!!I.url)};f.end=performance.now(),this.hls.trigger(H.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"),p=e<0;if(this.hls.trigger(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.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,a=t[e],u=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(H.LEVEL_SWITCHING,c);const d=a.details;if(!d||d.live){const f=this.switchParams(a.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===Ei.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,a=t.levelInfo;if(!a){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.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"],a=e.details,u=a?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(H.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,a)=>a!==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));rL(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(H.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(H.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function jw(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function eR(){return self.SourceBuffer||self.WebKitSourceBuffer}function tR(){if(!Al())return!1;const e=eR();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function K9(){if(!tR())return!1;const s=Al();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Nh(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Nh(e,"audio"))))}function W9(){var s;const e=eR();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const Y9=100;class X9 extends Jb{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||!At(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(n,r,It.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(H.MANIFEST_PARSED,this.onManifestParsed,this),e.on(H.LEVEL_LOADING,this.onLevelLoading,this),e.on(H.LEVEL_LOADED,this.onLevelLoaded,this),e.on(H.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(H.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(H.BUFFER_CREATED,this.onBufferCreated,this),e.on(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(H.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(H.MANIFEST_PARSED,this.onManifestParsed,this),e.off(H.LEVEL_LOADED,this.onLevelLoaded,this),e.off(H.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(H.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(H.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(H.BUFFER_CREATED,this.onBufferCreated,this),e.off(H.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(H.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(H.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(Y9),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=Xe.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Xe.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Xe.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=Xe.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Xe.IDLE;break}break}case Xe.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Xe.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 a=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(H.BUFFER_EOS,_),this.state=Xe.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=a.details;if(!d||this.state===Xe.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=Xe.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,p=this.getMaxBufferLength(a.maxBitrate);if(f>=p)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&qs(v)&&this.fragmentTracker.getState(v)!==cn.OK){var b;const S=((b=this.backtrackFragment)!=null?b:v).sn-d.startSN,L=d.fragments[S-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,y)){if(!v.gap){const S=this.audioOnly&&!this.altAudio?ds.AUDIO:ds.VIDEO,L=(S===ds.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,S,It.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,It.MAIN,p)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,a,y))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===cn.NOT_LOADED||n===cn.PARTIAL?qs(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=a-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(H.AUDIO_TRACK_SWITCHED,t)}),i.trigger(H.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(H.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Lp(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,a=!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 a=!0}a&&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===Xe.PARSED&&(this.state=Xe.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),qs(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const a=this.media;a&&(!this._hasEnoughToStart&&ai.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=Xe.ERROR;return}switch(t.details){case Ie.FRAG_GAP:case Ie.FRAG_PARSING_ERROR:case Ie.FRAG_DECRYPT_ERROR:case Ie.FRAG_LOAD_ERROR:case Ie.FRAG_LOAD_TIMEOUT:case Ie.KEY_LOAD_ERROR:case Ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(It.MAIN,t);break;case Ie.LEVEL_LOAD_ERROR:case Ie.LEVEL_LOAD_TIMEOUT:case Ie.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Xe.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Ei.LEVEL&&(this.state=Xe.IDLE);break;case Ie.BUFFER_ADD_CODEC_ERROR:case Ie.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Ie.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 Ie.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Xe.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ds.AUDIO||!this.altAudio){const i=(t===ds.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=Xe.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(H.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===Xe.STOPPED||this.state===Xe.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=a,{video:f,text:p,id3:y,initSegment:v}=n,{details:b}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=Xe.PARSING,v){const S=v.tracks;if(S){const $=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,S,$,r),i.trigger(H.FRAG_PARSING_INIT_SEGMENT,{frag:$,id:t,tracks:S})}const L=v.initPTS,I=v.timescale,R=this.initPTS[u.cc];if(At(L)&&(!R||R.baseTime!==L||R.timescale!==I)){const $=v.trackId;this.initPTS[u.cc]={baseTime:L,timescale:I,trackId:$},i.trigger(H.INIT_PTS_FOUND,{frag:u,id:t,initPTS:L,timescale:I,trackId:$})}}if(f&&b){_&&f.type==="audiovideo"&&this.logMuxedErr(u);const S=b.fragments[u.sn-1-b.startSN],L=u.sn===b.startSN,I=!S||u.cc>S.cc;if(n.independent!==!1){const{startPTS:R,endPTS:$,startDTS:B,endDTS:F}=f;if(c)c.elementaryStreams[f.type]={startPTS:R,endPTS:$,startDTS:B,endDTS:F};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!I&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),G=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,D=f.firstKeyFramePTS?f.firstKeyFramePTS:R;if(!L&&GJm&&(u.gap=!0);u.setElementaryStreamInfo(f.type,R,$,B,F),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:S,endPTS:L,startDTS:I,endDTS:R}=_;c&&(c.elementaryStreams[ds.AUDIO]={startPTS:S,endPTS:L,startDTS:I,endDTS:R}),u.setElementaryStreamInfo(ds.AUDIO,S,L,I,R),this.bufferFragmentData(_,u,c,r)}if(b&&y!=null&&y.samples.length){const S={id:t,frag:u,details:b,samples:y.samples};i.trigger(H.FRAG_PARSING_METADATA,S)}if(b&&p){const S={id:t,frag:u,details:b,samples:p.samples};i.trigger(H.FRAG_PARSING_USERDATA,S)}}logMuxedErr(e){this.warn(`${qs(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==Xe.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=qm(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 y=r.metadata;y&&"channelCount"in y&&(y.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=It.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=It.MAIN;const d=a.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.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(H.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const p=t[d].initSegment;p!=null&&p.byteLength&&this.hls.trigger(H.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,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=Xe.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ai.isBuffered(e,i)?t=this.getAppendedFrag(i):ai.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(H.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(H.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 At(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(At(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?xu(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const a=r+(t-n.start)*1e3;return new Date(a)}}}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 Q9 extends Xr{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=Ie.KEY_LOAD_ERROR,i,n,r){return new yo({type:Ft.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;a.setKeyFormat(u);const c=Wm(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=ch(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,Ie.KEY_LOAD_ERROR,d))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,Ie.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const u=Dv(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: "+An(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,Ie.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 a=g6(t.initSegment.data);if(a.length){let u=a[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${An(u)}`),Sl.setKeyIdForUri(e.decryptdata.uri,u)):(u=Sl.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${An(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!qs(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}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((a,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:(y,v,b,_)=>{const{frag:S,keyInfo:L}=b,I=Dv(L.decryptdata);if(!S.decryptdata||L!==this.keyIdToKeyInfo[I])return u(this.createKeyLoadError(S,Ie.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));L.decryptdata.key=S.decryptdata.key=new Uint8Array(y.data),S.keyLoader=null,L.loader=null,a({frag:S,keyInfo:L})},onError:(y,v,b,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Ie.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),b,Ji({url:c.url,data:void 0},y)))},onTimeout:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Ie.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Ie.INTERNAL_ABORTED,new Error("key loading aborted"),b))}};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 a=Dv(i.decryptdata)||n;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function Dv(s){if(s.keyFormat!==Cn.FAIRPLAY){const e=s.keyId;if(e)return An(e)}return s.uri}function $w(s){const{type:e}=s;switch(e){case Ei.AUDIO_TRACK:return It.AUDIO;case Ei.SUBTITLE_TRACK:return It.SUBTITLE;default:return It.MAIN}}function Lv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Z9{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(H.MANIFEST_LOADING,this.onManifestLoading,this),e.on(H.LEVEL_LOADING,this.onLevelLoading,this),e.on(H.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(H.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(H.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(H.MANIFEST_LOADING,this.onManifestLoading,this),e.off(H.LEVEL_LOADING,this.onLevelLoading,this),e.off(H.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(H.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(H.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}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:Ei.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:a,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:Ei.LEVEL,url:a,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ei.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ei.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[Ei.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[Ei.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===Ei.MANIFEST?r=i.manifestLoadPolicy.default:r=as({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),At((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Ei.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Ei.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Ei.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,p=d.targetduration;if(f&&p){const y=Math.max(f*3,p*.8)*1e3;r=as({},r,{maxTimeToFirstByteMs:Math.min(y,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(d,f,p,y)=>{const v=this.getInternalLoader(p);this.resetInternalLoader(p.type);const b=d.data;f.parsing.start=performance.now(),Ba.isMediaPlaylist(b)||p.type!==Ei.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,p,y||null,v):this.handleMasterPlaylist(d,f,p,y)},onError:(d,f,p,y)=>{this.handleNetworkError(f,p,!1,d,y)},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,a=e.data,u=Lv(e,i),c=Ba.parseMasterPlaylist(a,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:y,startTimeOffset:v,variableList:b}=c;this.variableList=b,f.forEach(I=>{const{unknownCodecs:R}=I;if(R){const{preferManagedMediaSource:$}=this.hls.config;let{audioCodec:B,videoCodec:F}=I;for(let M=R.length;M--;){const G=R[M];Ih(G,"audio",$)?(I.audioCodec=B=B?`${B},${G}`:G,$c.audio[B.substring(0,4)]=2,R.splice(M,1)):Ih(G,"video",$)&&(I.videoCodec=F=F?`${F},${G}`:G,$c.video[F.substring(0,4)]=2,R.splice(M,1))}}});const{AUDIO:_=[],SUBTITLES:S,"CLOSED-CAPTIONS":L}=Ba.parseMasterPlaylistMedia(a,u,c);_.length&&!_.some(R=>!R.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 ks({}),bitrate:0,url:""})),r.trigger(H.MANIFEST_LOADED,{levels:f,audioTracks:_,subtitles:S,captions:L,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:p,sessionKeys:y,startTimeOffset:v,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:u,level:c,type:d}=i,f=Lv(e,i),p=At(c)?c:At(u)?u:0,y=$w(i),v=Ba.parseLevelPlaylist(e.data,f,p,y,0,this.variableList);if(d===Ei.MANIFEST){const b={attrs:new ks({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+iL(v,0),a.trigger(H.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(H.ERROR,{type:Ft.NETWORK_ERROR,details:Ie.MANIFEST_PARSING_ERROR,fatal:t.type===Ei.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 a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Ei.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ei.AUDIO_TRACK||e.type===Ei.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=Ie.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case Ei.MANIFEST:c=i?Ie.MANIFEST_LOAD_TIMEOUT:Ie.MANIFEST_LOAD_ERROR,d=!0;break;case Ei.LEVEL:c=i?Ie.LEVEL_LOAD_TIMEOUT:Ie.LEVEL_LOAD_ERROR,d=!1;break;case Ei.AUDIO_TRACK:c=i?Ie.AUDIO_TRACK_LOAD_TIMEOUT:Ie.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ei.SUBTITLE_TRACK:c=i?Ie.SUBTITLE_TRACK_LOAD_TIMEOUT:Ie.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const p={type:Ft.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const y=t?.url||e.url;p.response=Ji({url:y,data:void 0},n)}this.hls.trigger(H.ERROR,p)}handlePlaylistLoaded(e,t,i,n,r,a){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:p,groupId:y,deliveryDirectives:v}=n,b=Lv(t,n),_=$w(n);let S=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(H.ERROR,{type:Ft.NETWORK_ERROR,details:Ie.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:L,reason:L.message,response:t,context:n,level:S,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(H.ERROR,{type:Ft.NETWORK_ERROR,details:Ie.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:I,reason:I.message,response:t,context:n,level:S,parent:_,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Ei.MANIFEST:case Ei.LEVEL:if(S){if(!f)S=0;else if(f!==u.levels[S]){const I=u.levels.indexOf(f);I>-1&&(S=I)}}u.trigger(H.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:S||0,id:p||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===Ei.MANIFEST});break;case Ei.AUDIO_TRACK:u.trigger(H.AUDIO_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case Ei.SUBTITLE_TRACK:u.trigger(H.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class Lr{static get version(){return Mh}static isMSESupported(){return tR()}static isSupported(){return K9()}static getMediaSource(){return Al()}static get Events(){return H}static get MetadataSchema(){return Dr}static get ErrorTypes(){return Ft}static get ErrorDetails(){return Ie}static get DefaultConfig(){return Lr.defaultConfig?Lr.defaultConfig:M9}static set DefaultConfig(e){Lr.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 eT,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=n6(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=B9(Lr.DefaultConfig,e,t);this.userConfig=e,i.progressive&&F9(i,t);const{abrController:n,bufferController:r,capLevelController:a,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),p=new J6(this),y=i.interstitialsController,v=y?this.interstitialsController=new y(this,Lr):null,b=this.bufferController=new r(this,p),_=this.capLevelController=new a(this),S=new c(this),L=new Z9(this),I=i.contentSteeringController,R=I?new I(this):null,$=this.levelController=new q9(this,R),B=new V9(this),F=new Q9(this.config,this.logger),M=this.streamController=new X9(this,p,F),G=this.gapController=new H9(this,p);_.setStreamController(M),S.setStreamController(M);const D=[L,$,M];v&&D.splice(1,0,v),R&&D.splice(1,0,R),this.networkControllers=D;const O=[f,b,G,_,S,B,p];this.audioTrackController=this.createController(i.audioTrackController,D);const W=i.audioStreamController;W&&D.push(this.audioStreamController=new W(this,p,F)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const Y=i.subtitleStreamController;Y&&D.push(this.subtititleStreamController=new Y(this,p,F)),this.createController(i.timelineController,O),F.emeController=this.emeController=this.createController(i.emeController,O),this.cmcdController=this.createController(i.cmcdController,O),this.latencyController=this.createController(z9,O),this.coreComponents=O,D.push(d);const J=d.onErrorOut;typeof J=="function"&&this.on(H.ERROR,J,d),this.on(H.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===H.ERROR;this.trigger(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.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(H.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(H.ERROR,{type:Ft.OTHER_ERROR,details:Ie.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(H.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(H.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(H.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=Gb.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(H.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=H7()),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){B6(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 a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=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=$D(t);return UD(e,i,navigator.mediaCapabilities)}}Lr.defaultConfig=void 0;function Hw(s,e){const t=s.includes("?")?"&":"?";return`${s}${t}v=${e}`}function iR({src:s,muted:e=np,className:t}){const i=E.useRef(null),[n,r]=E.useState(!1),[a,u]=E.useState(null),[c,d]=E.useState(1),f=E.useMemo(()=>Hw(s,c),[s,c]);return E.useEffect(()=>{let p=!1,y=null,v=null,b=null;const _=i.current;if(!_)return;const S=_;r(!1),u(null),rp(S,{muted:e});const L=()=>{v&&window.clearTimeout(v),b&&window.clearInterval(b),v=null,b=null},I=()=>{p||(L(),d(F=>F+1))};async function R(){const F=Date.now();for(;!p&&Date.now()-F<9e4;){try{const M=Hw(s,Date.now()),G=await fetch(M,{cache:"no-store"});if(G.status===403)return{ok:!1,reason:"private"};if(G.status===404)return{ok:!1,reason:"offline"};if(G.ok&&(await G.text()).includes("#EXTINF"))return{ok:!0}}catch{}await new Promise(M=>setTimeout(M,500))}return{ok:!1}}async function $(){const F=await R();if(!p){if(!F.ok){if(F.reason==="private"||F.reason==="offline"){u(F.reason),r(!0);return}window.setTimeout(()=>{p||I()},800);return}if(S.canPlayType("application/vnd.apple.mpegurl")){S.pause(),S.removeAttribute("src"),S.load(),S.src=f,S.load(),S.play().catch(()=>{});let M=Date.now(),G=-1;const D=()=>{S.currentTime>G+.01&&(G=S.currentTime,M=Date.now())},O=()=>{v||(v=window.setTimeout(()=>{v=null,!p&&Date.now()-M>3500&&I()},800))};return S.addEventListener("timeupdate",D),S.addEventListener("waiting",O),S.addEventListener("stalled",O),S.addEventListener("error",O),b=window.setInterval(()=>{p||!S.paused&&Date.now()-M>6e3&&I()},2e3),()=>{S.removeEventListener("timeupdate",D),S.removeEventListener("waiting",O),S.removeEventListener("stalled",O),S.removeEventListener("error",O)}}if(!Lr.isSupported()){r(!0);return}y=new Lr({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:8}),y.on(Lr.Events.ERROR,(M,G)=>{if(y&&G.fatal){if(G.type===Lr.ErrorTypes.NETWORK_ERROR){y.startLoad();return}if(G.type===Lr.ErrorTypes.MEDIA_ERROR){y.recoverMediaError();return}I()}}),y.loadSource(f),y.attachMedia(S),y.on(Lr.Events.MANIFEST_PARSED,()=>{S.play().catch(()=>{})})}}let B;return(async()=>{const F=await $();typeof F=="function"&&(B=F)})(),()=>{p=!0,L();try{B?.()}catch{}try{y?.destroy()}catch{}}},[s,e,f]),n?g.jsx("div",{className:"text-xs text-gray-400 italic",children:a==="private"?"Private":a==="offline"?"Offline":"–"}):g.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,preload:"auto",crossOrigin:"anonymous",onClick:()=>{const p=i.current;p&&(p.muted=!1,p.play().catch(()=>{}))}})}function J9(){const s=Re;if(s.__gearControlRegistered)return;s.__gearControlRegistered=!0;const e=Re.getComponent("MenuButton"),t=Re.getComponent("MenuItem");class i extends t{_onSelect;constructor(a,u){super(a,u),this._onSelect=u?.onSelect,this.on("click",()=>this._onSelect?.())}}class n extends e{constructor(a,u){super(a,u),this.controlText("Settings");const d=this.el().querySelector(".vjs-icon-placeholder");d&&(d.innerHTML=` + + `),this.player().on("gear:refresh",()=>this.update())}update(){try{super.update?.()}catch{}const a=this.player(),u=String(a.options_?.__gearQuality??"auto"),c=String(a.options_?.__autoAppliedQuality??""),d=this.items||[];for(const f of d){const p=f?.options_?.__kind,y=f?.options_?.__value;p==="quality"&&f.selected?.(String(y)===u)}try{for(const f of d){if(f?.options_?.__kind!=="quality"||String(f?.options_?.__value)!=="auto")continue;const y=f.el?.()?.querySelector?.(".vjs-menu-item-text");y&&(u==="auto"&&c&&c!=="auto"?y.textContent=`Auto (${c})`:y.textContent="Auto")}}catch{}}createItems(){const a=this.player(),u=[],c=a.options_?.gearQualities||["auto","1080p","720p","480p"],d=String(a.options_?.__gearQuality??"auto");for(const f of c){const p=f==="auto"?"Auto":f==="2160p"?"4K":f;u.push(new i(a,{label:p,selectable:!0,selected:d===f,__kind:"quality",__value:f,onSelect:()=>{a.options_.__gearQuality=f,a.trigger({type:"gear:quality",quality:f}),a.trigger("gear:refresh")}}))}return u}}if(Re.getComponent("Component"),Re.registerComponent("GearMenuButton",n),!s.__gearControlCssInjected){s.__gearControlCssInjected=!0;const r=document.createElement("style");r.textContent=` + #player-root .vjs-gear-menu .vjs-icon-placeholder { + display: inline-flex; + align-items: center; + justify-content: center; + } + + /* ✅ Menübreite nicht aufblasen */ + #player-root .vjs-gear-menu .vjs-menu { + min-width: 0 !important; + width: fit-content !important; + } + + /* ✅ die UL auch nicht breit ziehen */ + #player-root .vjs-gear-menu .vjs-menu-content { + width: fit-content !important; + min-width: 0 !important; + padding: 2px 0 !important; + } + + /* ✅ Items kompakter */ + #player-root .vjs-gear-menu .vjs-menu-content .vjs-menu-item { + padding: 4px 10px !important; + line-height: 1.1 !important; + } + + /* ✅ Gear-Button als Anker */ + #player-root .vjs-gear-menu { + position: relative !important; + } + + /* ✅ Popup wirklich über dem Gear-Icon zentrieren */ + #player-root .vjs-gear-menu .vjs-menu { + position: absolute !important; + + left: 0% !important; + right: 0% !important; + + transform: translateX(-50%) !important; + transform-origin: 50% 100% !important; + + z-index: 9999 !important; + } + + /* ✅ Manche Skins setzen am UL noch Layout/Width – neutralisieren */ + #player-root .vjs-gear-menu .vjs-menu-content { + width: max-content !important; + min-width: 0 !important; + } + + /* ✅ Menü horizontal zentrieren über dem Gear-Icon */ + #player-root .vjs-gear-menu .vjs-menu { + z-index: 9999 !important; + } + `,document.head.appendChild(r)}}const Gr=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",fT=s=>s.startsWith("HOT ")?s.slice(4):s,e$=s=>(s||"").trim().toLowerCase(),t$=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n};function i$(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 s$(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 Gw(s){if(!s)return"—";const e=s instanceof Date?s:new Date(s),t=e.getTime();return Number.isFinite(t)?e.toLocaleString(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"—"}const Vw=(...s)=>{for(const e of s){const t=typeof e=="string"?Number(e):e;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t}return null};function n$(s){if(!s||!Number.isFinite(s))return"—";const e=s>=10?0:2;return`${s.toFixed(e)} fps`}function r$(s){return!s||!Number.isFinite(s)?"—":`${Math.round(s)}p`}function a$(s){const e=Gr(s||""),t=fT(e);if(!t)return null;const n=t.replace(/\.[^.]+$/,"").match(/_(\d{1,2})_(\d{1,2})_(\d{4})__(\d{1,2})-(\d{2})-(\d{2})$/);if(!n)return null;const r=Number(n[1]),a=Number(n[2]),u=Number(n[3]),c=Number(n[4]),d=Number(n[5]),f=Number(n[6]);return[r,a,u,c,d,f].every(p=>Number.isFinite(p))?new Date(u,r-1,a,c,d,f):null}const o$=s=>{const e=Gr(s||""),t=fT(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},l$=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 fo(...s){return s.filter(Boolean).join(" ")}function u$(s){const[e,t]=E.useState(!1);return E.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 Um(s){!s||s.__absTimelineShimInstalled||(s.__absTimelineShimInstalled=!0,s.__origCurrentTime=s.currentTime.bind(s),s.__origDuration=s.duration.bind(s),s.__setRelativeTime=e=>{try{s.__origCurrentTime(Math.max(0,e||0))}catch{}},s.currentTime=function(e){const t=Number(this.__timeOffsetSec??0)||0;if(typeof e=="number"&&Number.isFinite(e)){const n=Math.max(0,e);return typeof this.__serverSeekAbs=="function"?(this.__serverSeekAbs(n),n):this.__origCurrentTime(Math.max(0,n-t))}const i=Number(this.__origCurrentTime()??0)||0;return Math.max(0,t+i)},s.duration=function(){const e=Number(this.__fullDurationSec??0)||0;if(e>0)return e;const t=Number(this.__timeOffsetSec??0)||0,i=Number(this.__origDuration()??0)||0;return Math.max(0,t+i)})}function Rv(s){const e=typeof s=="number"&&Number.isFinite(s)&&s>0?Math.round(s):0,t=[2160,1440,1080,720,480,360,240],i=u=>`${u}p`,n=u=>Array.from(new Set(u));if(!e)return["auto",...t.map(i)];const r=t.filter(u=>u<=e+8),a=Array.from(new Set([...r,e])).sort((u,c)=>c-u);return n(["auto",...a.map(i)])}function c$({job:s,expanded:e,onClose:t,onToggleExpand:i,modelKey:n,modelsByKey:r,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onKeep:f,onDelete:p,onToggleHot:y,onToggleFavorite:v,onToggleLike:b,onToggleWatch:_,onStopJob:S,startMuted:L=fO}){const I=E.useMemo(()=>Gr(s.output?.trim()||"")||s.id,[s.output,s.id]),R=E.useMemo(()=>Gr(s.output?.trim()||""),[s.output]),$=E.useMemo(()=>Gr(s.output?.trim()||""),[s.output]),B=E.useMemo(()=>s$(l$(s)),[s]),F=s,M=s.status==="running",[G,D]=E.useState(!1),O=M&&G,W=E.useMemo(()=>($||"").replace(/\.[^.]+$/,""),[$]),Y=E.useMemo(()=>M?s.id:W||s.id,[M,s.id,W]),J=R.startsWith("HOT "),ae=E.useMemo(()=>{const q=(n||"").trim();return q||o$(s.output)},[n,s.output]),se=E.useMemo(()=>fT(R),[R]),K=E.useMemo(()=>{const q=Number(s?.meta?.durationSeconds)||Number(s?.durationSeconds)||0;return q>0?i$(q*1e3):"—"},[s]),X=E.useMemo(()=>{const q=a$(s.output);if(q)return Gw(q);const ce=F.startedAt??F.endedAt??F.createdAt??F.fileCreatedAt??F.ctime??null,ke=ce?new Date(ce):null;return Gw(ke&&Number.isFinite(ke.getTime())?ke:null)},[s.output,F.startedAt,F.endedAt,F.createdAt,F.fileCreatedAt,F.ctime]),ee=E.useMemo(()=>e$((n||ae||"").trim()),[n,ae]),le=E.useMemo(()=>{const q=r?.[ee];return t$(q?.tags)},[r,ee]),pe=E.useMemo(()=>oc(`/api/record/preview?id=${encodeURIComponent(Y)}&file=preview.jpg`),[Y]),P=E.useMemo(()=>oc(`/api/record/preview?id=${encodeURIComponent(Y)}&file=thumbs.jpg`),[Y]),Q=E.useMemo(()=>oc(`/api/record/preview?id=${encodeURIComponent(Y)}&play=1&file=index_hq.m3u8`),[Y]),[ue,he]=E.useState(pe);E.useEffect(()=>{he(pe)},[pe]);const re=E.useMemo(()=>Vw(F.videoHeight,F.height,F.meta?.height),[F.videoHeight,F.height,F.meta?.height]),Pe=E.useMemo(()=>Vw(F.fps,F.frameRate,F.meta?.fps,F.meta?.frameRate),[F.fps,F.frameRate,F.meta?.fps,F.meta?.frameRate]),[Ee,Ge]=E.useState(null),Ve=E.useMemo(()=>r$(Ee??re),[Ee,re]),lt=E.useMemo(()=>n$(Pe),[Pe]);E.useEffect(()=>{const q=ce=>ce.key==="Escape"&&t();return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[t]);const _t=E.useMemo(()=>{const q=`/api/record/preview?id=${encodeURIComponent(Y)}&file=index_hq.m3u8&play=1`;return oc(M?`${q}&t=${Date.now()}`:q)},[Y,M]);E.useEffect(()=>{if(!M){D(!1);return}let q=!0;const ce=new AbortController;return D(!1),(async()=>{for(let De=0;De<120&&q&&!ce.signal.aborted;De++){try{const Be=await Y8(_t,{method:"GET",cache:"no-store",signal:ce.signal,headers:{"cache-control":"no-cache"}});if(Be.ok){const et=await Be.text(),ct=et.includes("#EXTM3U"),$e=/#EXTINF:/i.test(et)||/\.ts(\?|$)/i.test(et)||/\.m4s(\?|$)/i.test(et);if(ct&&$e){q&&D(!0);return}}}catch{}await new Promise(Be=>setTimeout(Be,500))}})(),()=>{q=!1,ce.abort()}},[M,_t]);const mt=E.useCallback(q=>{const ce=String(q.quality||"auto").trim(),ke=typeof q.startSec=="number"&&Number.isFinite(q.startSec)&&q.startSec>0?Math.floor(q.startSec):0,De=new URLSearchParams;q.file&&De.set("file",q.file),q.id&&De.set("id",q.id);const Be=ct=>{const $e=String(ct).match(/(\d{3,4})p/i);return $e?Number($e[1]):0},et=typeof re=="number"&&Number.isFinite(re)&&re>0?Math.round(re):0;if(ce&&ce!=="auto"){De.set("quality",ce);const ct=Be(ce);ke===0&&et&&ct&&ct0&&De.set("t",String(ke)),oc(`/api/record/video?${De.toString()}`)},[re]),[Ze,bt]=E.useState("auto"),[gt,at]=E.useState("auto"),wt=E.useRef(Ze);E.useEffect(()=>{wt.current=Ze},[Ze]);const Et=E.useRef(gt);E.useEffect(()=>{Et.current=gt},[gt]);const Ot=E.useMemo(()=>{if(M)return{src:"",type:""};const q=Gr(s.output?.trim()||"");if(q){const ce=q.toLowerCase().split(".").pop(),ke=ce==="mp4"?"video/mp4":ce==="ts"?"video/mp2t":"application/octet-stream";return{src:mt({file:q,quality:gt}),type:ke}}return{src:mt({id:s.id,quality:gt}),type:"video/mp4"}},[M,s.output,s.id,gt,mt]),ot=E.useRef(null),ht=E.useRef(null),ve=E.useRef(null),dt=E.useRef(!1),[qe,st]=E.useState(!1),[ft,yt]=E.useState(0),nt=E.useCallback(()=>{const q=ht.current;if(!q||q.isDisposed?.())return;const ce=typeof q.videoHeight=="function"?q.videoHeight():0;typeof ce=="number"&&ce>0&&Number.isFinite(ce)&&Ge(ce)},[]),jt=E.useMemo(()=>Gr(s.output?.trim()||"")||s.id,[s.output,s.id]),qt=E.useMemo(()=>{const q=typeof re=="number"&&Number.isFinite(re)&&re>0?Math.round(re):0;return q?`${q}p`:"auto"},[re]),Yt=E.useRef("");E.useEffect(()=>{if(Yt.current!==jt){Yt.current=jt,bt(qt),at(qt),Ge(null);const q=ht.current;if(q&&!q.isDisposed?.())try{q.options_.__gearQuality=qt,q.options_.__autoAppliedQuality=qt,q.trigger?.("gear:refresh")}catch{}}},[jt,qt]);const[,Ut]=E.useState(0);E.useEffect(()=>{if(typeof window>"u")return;const q=window.visualViewport;if(!q)return;const ce=()=>Ut(ke=>ke+1);return ce(),q.addEventListener("resize",ce),q.addEventListener("scroll",ce),window.addEventListener("resize",ce),window.addEventListener("orientationchange",ce),()=>{q.removeEventListener("resize",ce),q.removeEventListener("scroll",ce),window.removeEventListener("resize",ce),window.removeEventListener("orientationchange",ce)}},[]);const[Ni,rt]=E.useState(56),[Dt,ii]=E.useState(null),ci=!e,mi=u$("(min-width: 640px)"),Ht=ci&&mi,Oi="player_window_v1",Ki=420,Lt=280,z=12,V=320,te=200;E.useEffect(()=>{if(!qe)return;const q=ht.current;if(!q||q.isDisposed?.())return;const ce=q.el();if(!ce)return;const ke=ce.querySelector(".vjs-control-bar");if(!ke)return;const De=()=>{const et=Math.round(ke.getBoundingClientRect().height||0);et>0&&rt(et)};De();let Be=null;return typeof ResizeObserver<"u"&&(Be=new ResizeObserver(De),Be.observe(ke)),window.addEventListener("resize",De),()=>{window.removeEventListener("resize",De),Be?.disconnect()}},[qe,e]);const xe=E.useCallback((q,ce,ke)=>{if(M)return;Um(q);const De=!!q.paused?.(),Be=Number(q.currentTime?.()??0)||0,et=Be>0?Math.floor(Be/2)*2:0,ct=Be-et;q.__timeOffsetSec=et,dt.current=!0,at(ke),q.options_.__autoAppliedQuality=ke;const $e=mt({file:ce,quality:ke,startSec:et}),it=Number(s?.meta?.durationSeconds)||Number(F?.meta?.durationSeconds)||Number(s?.durationSeconds)||0;it>0&&(q.__fullDurationSec=it);try{const Tt=q.__onLoadedMetaQSwitch;Tt&&q.off("loadedmetadata",Tt)}catch{}const vt=()=>{if(nt(),!(Number(q.__fullDurationSec)>0))try{const Tt=Number(q.__origDuration?.()??0)||0;Tt>0&&(q.__fullDurationSec=et+Tt)}catch{}try{q.__setRelativeTime?.(ct)}catch{}try{q.trigger?.("timeupdate")}catch{}try{q.trigger?.("gear:refresh")}catch{}if(!De){const Tt=q.play?.();Tt&&typeof Tt.catch=="function"&&Tt.catch(()=>{})}};q.__onLoadedMetaQSwitch=vt,q.one("loadedmetadata",vt);try{q.src({src:$e,type:"video/mp4"})}catch{}try{q.load?.()}catch{}},[M,mt,nt,s,F]);E.useEffect(()=>{const q=ht.current;if(!q||q.isDisposed?.())return;Um(q);const ce=ke=>{const De=String(ke?.quality??"auto").trim();if(M)return;const Be=Gr(s.output?.trim()||"");if(Be){if(bt(De),De==="auto"){try{q.options_.__gearQuality="auto",q.options_.__autoAppliedQuality=Et.current||qt,q.trigger?.("gear:refresh")}catch{}return}try{q.options_.__gearQuality=De,q.options_.__autoAppliedQuality=De,q.trigger?.("gear:refresh")}catch{}xe(q,Be,De)}};return q.on("gear:quality",ce),()=>{try{q.off("gear:quality",ce)}catch{}}},[ft,s.output,M,xe,qt]),E.useEffect(()=>{if(!qe||M||Ze!=="auto")return;const q=ht.current;if(!q||q.isDisposed?.())return;Um(q);const ce=Gr(s.output?.trim()||"");if(!ce)return;const ke=()=>(q.options_?.gearQualities||Rv(Ee??re)).filter(Vt=>Vt&&Vt!=="auto"),De=Jt=>{const Vt=String(Jt).match(/(\d{3,4})p/i);return Vt?Number(Vt[1]):0},Be=Jt=>[...Jt].sort((Vt,wi)=>De(wi)-De(Vt)),et=(Jt,Vt)=>{const wi=Be(Vt),Ys=De(Jt);for(let ts=0;ts0&&Mt{const wi=Be(Vt),Ys=De(Jt);for(let ts=wi.length-1;ts>=0;ts--)if(De(wi[ts])>Ys+8)return wi[ts];return wi[0]||Jt};let $e=0,it=0,vt=0;const Tt=()=>{$e=Date.now()};q.on("waiting",Tt),q.on("stalled",Tt);const St=()=>{try{const Jt=Number(q.__origCurrentTime?.()??0)||0,Vt=q.buffered?.();if(!Vt||Vt.length<=0)return 0;const wi=Vt.end(Vt.length-1);return Math.max(0,(Number(wi)||0)-Jt)}catch{return 0}},Rt=()=>{const Jt=Date.now();if(Jt-it<8e3)return;const Vt=ke();if(!Vt.length)return;const wi=Et.current&&Et.current!=="auto"?Et.current:Vt[0],Ys=St(),ts=Jt-$e<2500;if(Ys<4||ts){const Mt=et(wi,Vt);if(Mt&&Mt!==wi){it=Jt,vt=0;try{q.options_.__autoAppliedQuality=Mt,q.trigger?.("gear:refresh")}catch{}xe(q,ce,Mt)}return}if(Ys>20&&Jt-$e>2e4){if(vt||(vt=Jt),Jt-vt>2e4){const Mt=ct(wi,Vt);if(Mt&&Mt!==wi){it=Jt,vt=Jt;try{q.options_.__autoAppliedQuality=Mt,q.trigger?.("gear:refresh")}catch{}xe(q,ce,Mt)}}}else vt=0},gi=window.setInterval(Rt,2e3);return Rt(),()=>{window.clearInterval(gi);try{q.off("waiting",Tt)}catch{}try{q.off("stalled",Tt)}catch{}}},[qe,M,Ze,s.output,Ee,re,xe]),E.useEffect(()=>st(!0),[]),E.useEffect(()=>{let q=document.getElementById("player-root");q||(q=document.createElement("div"),q.id="player-root");let ce=null;if(mi){const ke=Array.from(document.querySelectorAll("dialog[open]"));ce=ke.length?ke[ke.length-1]:null}ce=ce??document.body,ce.appendChild(q),q.style.position="relative",q.style.zIndex="2147483647",ii(q)},[mi]),E.useEffect(()=>{const q=ht.current;if(!q||q.isDisposed?.()||M)return;Um(q);const ce=Gr(s.output?.trim()||"");if(!ce)return;const ke=Number(s.durationSeconds??F?.meta?.durationSeconds??0)||0;return ke>0&&(q.__fullDurationSec=ke),q.__serverSeekAbs=De=>{const Be=Math.max(0,Number(De)||0),et=wt.current==="auto"?String(Et.current||"auto").trim():String(wt.current||"auto").trim(),ct=Vt=>{const wi=String(Vt).match(/(\d{3,4})p/i);return wi?Number(wi[1]):0},$e=typeof re=="number"&&Number.isFinite(re)&&re>0?Math.round(re):0,it=ct(et);if(!(et!=="auto"&&$e>0&&it>0&&it<$e-8)){const Vt=!!q.paused?.(),wi=Number(q.__timeOffsetSec??0)||0,Ys=String(q.currentSrc?.()||"");if(wi>0||Ys.includes("t=")||Ys.includes("start=")){q.__timeOffsetSec=0;const Mt=mt({file:ce,quality:et}),Ai=()=>{nt();try{q.__origCurrentTime?.(Be);try{q.trigger?.("timeupdate")}catch{}}catch{try{q.currentTime?.(Be)}catch{}}if(!Vt){const _i=q.play?.();_i&&typeof _i.catch=="function"&&_i.catch(()=>{})}};try{q.one("loadedmetadata",Ai)}catch{}try{q.src({src:Mt,type:"video/mp4"})}catch{}try{q.load?.()}catch{}return}try{q.__origCurrentTime?.(Be);try{q.trigger?.("timeupdate")}catch{}}catch{try{q.currentTime?.(Be)}catch{}}return}const Tt=!!q.paused?.(),St=Math.floor(Be/2)*2,Rt=Be-St;q.__timeOffsetSec=St;const gi=mt({file:ce,quality:et,startSec:St}),Jt=()=>{nt(),q.__setRelativeTime?.(Rt);try{q.trigger?.("timeupdate")}catch{}if(!Tt){const Vt=q.play?.();Vt&&typeof Vt.catch=="function"&&Vt.catch(()=>{})}};try{q.one("loadedmetadata",Jt)}catch{}try{q.src({src:gi,type:"video/mp4"})}catch{}try{q.load?.()}catch{}},()=>{try{delete q.__serverSeekAbs}catch{}}},[ft,s.output,M,mt,nt,F,s,re]),E.useLayoutEffect(()=>{if(!qe||!ot.current||ht.current||M)return;const q=document.createElement("video");q.className="video-js vjs-big-play-centered w-full h-full",q.setAttribute("playsinline","true"),ot.current.appendChild(q),ve.current=q,J9();const ce=Rv(re),ke=(()=>{const Be=typeof re=="number"&&Number.isFinite(re)&&re>0?Math.round(re):0;return Be?`${Be}p`:"auto"})();bt(ke),at(ke);const De=Re(q,{autoplay:!0,muted:L,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,liveui:!1,html5:{vhs:{lowLatencyMode:!0}},inactivityTimeout:0,gearQualities:ce,__gearQuality:ke,__autoAppliedQuality:ke,controlBar:{skipButtons:{backward:10,forward:10},volumePanel:{inline:!1},children:["skipBackward","playToggle","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","spacer","playbackRateMenuButton","GearMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});ht.current=De,yt(Be=>Be+1),De.one("loadedmetadata",()=>{nt();try{const Be=typeof De.videoHeight=="function"?De.videoHeight():0,et=Rv(Be);De.options_.gearQualities=et;const ct=String(De.options_.__gearQuality??"auto"),$e=typeof Be=="number"&&Number.isFinite(Be)&&Be>0?`${Math.round(Be)}p`:"auto",it=et.includes(ct)?ct:et.includes($e)?$e:"auto";if(De.options_.__gearQuality=it,bt(it),it!=="auto")at(it),De.options_.__autoAppliedQuality=it;else{const vt=String(Et.current||"auto"),Tt=vt!=="auto"?vt:$e!=="auto"?$e:"auto";at(Tt),De.options_.__autoAppliedQuality=Tt}De.trigger("gear:refresh")}catch{}});try{const Be=De.getChild("controlBar")?.getChild("GearMenuButton");Be?.el&&Be.el().classList.add("vjs-gear-menu")}catch{}return De.userActive(!0),De.on("userinactive",()=>De.userActive(!0)),()=>{try{ht.current&&(ht.current.dispose(),ht.current=null)}finally{ve.current&&(ve.current.remove(),ve.current=null)}}},[qe,L,M,re,nt]),E.useEffect(()=>{const q=ht.current;if(!q||q.isDisposed?.())return;const ce=q.el();ce&&ce.classList.toggle("is-live-download",!!O)},[O]),E.useEffect(()=>{if(!qe)return;const q=ht.current;if(!q||q.isDisposed?.())return;if(dt.current){dt.current=!1;return}const ce=q.currentTime()||0;if(q.muted(L),!Ot.src){try{q.pause(),q.reset?.(),q.error(null)}catch{}return}q.__timeOffsetSec=0;const ke=Number(s.durationSeconds??s.meta?.durationSeconds??0)||0;q.__fullDurationSec=ke,q.src({src:Ot.src,type:Ot.type});const De=()=>{const Be=q.play?.();Be&&typeof Be.catch=="function"&&Be.catch(()=>{})};q.one("loadedmetadata",()=>{if(q.isDisposed?.())return;nt();try{const et=Number(s.durationSeconds??F?.meta?.durationSeconds??0)||0;et>0&&(q.__fullDurationSec=et)}catch{}try{q.playbackRate(1)}catch{}const Be=/mpegurl/i.test(Ot.type);if(ce>0&&!Be)try{const et=Number(q.__timeOffsetSec??0)||0,ct=Math.max(0,ce-et);q.__setRelativeTime?.(ct)}catch{}try{q.trigger?.("timeupdate")}catch{}De()}),De()},[qe,Ot.src,Ot.type,L,nt,s,F]),E.useEffect(()=>{if(!qe)return;const q=ht.current;if(!q||q.isDisposed?.())return;const ce=()=>{s.status==="running"&&D(!1)};return q.on("error",ce),()=>{try{q.off("error",ce)}catch{}}},[qe,s.status]),E.useEffect(()=>{const q=ht.current;!q||q.isDisposed?.()||queueMicrotask(()=>q.trigger("resize"))},[e]);const Me=E.useCallback(()=>{const q=ht.current;if(!(!q||q.isDisposed?.())){try{q.pause(),q.reset?.()}catch{}try{q.src({src:"",type:"video/mp4"}),q.load?.()}catch{}}},[]);E.useEffect(()=>{const q=ce=>{const De=(ce.detail?.file??"").trim();if(!De)return;const Be=Gr(s.output?.trim()||"");Be&&Be===De&&Me()};return window.addEventListener("player:release",q),()=>window.removeEventListener("player:release",q)},[s.output,Me]),E.useEffect(()=>{const q=ce=>{const De=(ce.detail?.file??"").trim();if(!De)return;const Be=Gr(s.output?.trim()||"");Be&&Be===De&&(Me(),t())};return window.addEventListener("player:close",q),()=>window.removeEventListener("player:close",q)},[s.output,Me,t]);const ut=()=>{if(typeof window>"u")return{w:0,h:0,ox:0,oy:0,bottomInset:0};const q=window.visualViewport;if(q&&Number.isFinite(q.width)&&Number.isFinite(q.height)){const Be=Math.floor(q.width),et=Math.floor(q.height),ct=Math.floor(q.offsetLeft||0),$e=Math.floor(q.offsetTop||0),it=Math.max(0,Math.floor(window.innerHeight-(q.height+q.offsetTop)));return{w:Be,h:et,ox:ct,oy:$e,bottomInset:it}}const ce=document.documentElement,ke=ce?.clientWidth||window.innerWidth,De=ce?.clientHeight||window.innerHeight;return{w:ke,h:De,ox:0,oy:0,bottomInset:0}},Pt=E.useCallback((q,ce)=>{if(typeof window>"u")return q;const{w:ke,h:De}=ut(),Be=ke-z*2,et=De-z*2;let ct=q.w,$e=q.h;ce&&Number.isFinite(ce)&&ce>.1?(ct=Math.max(V,ct),$e=ct/ce,$eBe&&(ct=Be,$e=ct/ce),$e>et&&($e=et,ct=$e*ce)):(ct=Math.max(V,Math.min(ct,Be)),$e=Math.max(te,Math.min($e,et)));const it=Math.max(z,Math.min(q.x,ke-ct-z)),vt=Math.max(z,Math.min(q.y,De-$e-z));return{x:it,y:vt,w:ct,h:$e}},[]),Ii=E.useCallback(()=>{if(typeof window>"u")return{x:z,y:z,w:Ki,h:Lt};try{const ct=window.localStorage.getItem(Oi);if(ct){const $e=JSON.parse(ct);if(typeof $e.x=="number"&&typeof $e.y=="number"&&typeof $e.w=="number"&&typeof $e.h=="number")return Pt({x:$e.x,y:$e.y,w:$e.w,h:$e.h},$e.w/$e.h)}}catch{}const{w:q,h:ce}=ut(),ke=Ki,De=Lt,Be=Math.max(z,q-ke-z),et=Math.max(z,ce-De-z);return Pt({x:Be,y:et,w:ke,h:De},ke/De)},[Pt]),[Mi,Fi]=E.useState(()=>Ii()),Ui=Ht&&Mi.w<380,Wi=E.useCallback(q=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Oi,JSON.stringify(q))}catch{}},[]),pi=E.useRef(Mi);E.useEffect(()=>{pi.current=Mi},[Mi]),E.useEffect(()=>{Ht&&Fi(Ii())},[Ht,Ii]),E.useEffect(()=>{if(!Ht)return;const q=()=>Fi(ce=>Pt(ce,ce.w/ce.h));return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[Ht,Pt]);const os=E.useRef(null);E.useEffect(()=>{const q=ht.current;if(!(!q||q.isDisposed?.()))return os.current!=null&&cancelAnimationFrame(os.current),os.current=requestAnimationFrame(()=>{os.current=null;try{q.trigger("resize")}catch{}}),()=>{os.current!=null&&(cancelAnimationFrame(os.current),os.current=null)}},[Ht,Mi.w,Mi.h]);const[Yi,zi]=E.useState(!1),[si,Gt]=E.useState(!1),Xt=E.useRef(null),ys=E.useRef(null),ms=E.useRef(null),vn=E.useCallback(q=>{const{w:ce,h:ke}=ut(),De=z,Be=ce-q.w-z,et=ke-q.h-z,$e=q.x+q.w/2{const ce=ms.current;if(!ce)return;const ke=q.clientX-ce.sx,De=q.clientY-ce.sy,Be=ce.start,et=Pt({x:Be.x+ke,y:Be.y+De,w:Be.w,h:Be.h});ys.current={x:et.x,y:et.y},Xt.current==null&&(Xt.current=requestAnimationFrame(()=>{Xt.current=null;const ct=ys.current;ct&&Fi($e=>({...$e,x:ct.x,y:ct.y}))}))},[Pt]),vs=E.useCallback(()=>{ms.current&&(Gt(!1),Xt.current!=null&&(cancelAnimationFrame(Xt.current),Xt.current=null),ms.current=null,window.removeEventListener("pointermove",Mn),window.removeEventListener("pointerup",vs),Fi(q=>{const ce=vn(Pt(q));return queueMicrotask(()=>Wi(ce)),ce}))},[Mn,vn,Pt,Wi]),Ti=E.useCallback(q=>{if(!Ht||Yi||q.button!==0)return;q.preventDefault(),q.stopPropagation();const ce=pi.current;ms.current={sx:q.clientX,sy:q.clientY,start:ce},Gt(!0),window.addEventListener("pointermove",Mn),window.addEventListener("pointerup",vs)},[Ht,Yi,Mn,vs]),Is=E.useRef(null),Ws=E.useRef(null),Us=E.useRef(null),bs=E.useCallback(q=>{const ce=Us.current;if(!ce)return;const ke=q.clientX-ce.sx,De=q.clientY-ce.sy,Be=ce.ratio,et=ce.dir.includes("w"),ct=ce.dir.includes("e"),$e=ce.dir.includes("n"),it=ce.dir.includes("s");let vt=ce.start.w,Tt=ce.start.h,St=ce.start.x,Rt=ce.start.y;const{w:gi,h:Jt}=ut(),Vt=24,wi=ce.start.x+ce.start.w,Ys=ce.start.y+ce.start.h,ts=Math.abs(gi-z-wi)<=Vt,Mt=Math.abs(Jt-z-Ys)<=Vt,Ai=ls=>{ls=Math.max(V,ls);let Cs=ls/Be;return Cs{ls=Math.max(te,ls);let Cs=ls*Be;return Cs=Math.abs(De)){const Cs=ct?ce.start.w+ke:ce.start.w-ke,{newW:pr,newH:da}=Ai(Cs);vt=pr,Tt=da}else{const Cs=it?ce.start.h+De:ce.start.h-De,{newW:pr,newH:da}=_i(Cs);vt=pr,Tt=da}et&&(St=ce.start.x+(ce.start.w-vt)),$e&&(Rt=ce.start.y+(ce.start.h-Tt))}else if(ct||et){const ls=ct?ce.start.w+ke:ce.start.w-ke,{newW:Cs,newH:pr}=Ai(ls);vt=Cs,Tt=pr,et&&(St=ce.start.x+(ce.start.w-vt)),Rt=Mt?ce.start.y+(ce.start.h-Tt):ce.start.y}else if($e||it){const ls=it?ce.start.h+De:ce.start.h-De,{newW:Cs,newH:pr}=_i(ls);vt=Cs,Tt=pr,$e&&(Rt=ce.start.y+(ce.start.h-Tt)),ts?St=ce.start.x+(ce.start.w-vt):St=ce.start.x}const ca=Pt({x:St,y:Rt,w:vt,h:Tt},Be);Ws.current=ca,Is.current==null&&(Is.current=requestAnimationFrame(()=>{Is.current=null;const ls=Ws.current;ls&&Fi(ls)}))},[Pt]),Pi=E.useCallback(()=>{Us.current&&(zi(!1),Is.current!=null&&(cancelAnimationFrame(Is.current),Is.current=null),Us.current=null,window.removeEventListener("pointermove",bs),window.removeEventListener("pointerup",Pi),Wi(pi.current))},[bs,Wi]),Ts=E.useCallback(q=>ce=>{if(!Ht||ce.button!==0)return;ce.preventDefault(),ce.stopPropagation();const ke=pi.current;Us.current={dir:q,sx:ce.clientX,sy:ce.clientY,start:ke,ratio:ke.w/ke.h},zi(!0),window.addEventListener("pointermove",bs),window.addEventListener("pointerup",Pi)},[Ht,bs,Pi]),[xn,tn]=E.useState(!1),[sn,Or]=E.useState(!1);E.useEffect(()=>{const q=window.matchMedia?.("(hover: hover) and (pointer: fine)"),ce=()=>tn(!!q?.matches);return ce(),q?.addEventListener?.("change",ce),()=>q?.removeEventListener?.("change",ce)},[]);const Mr=Ht&&(sn||si||Yi),[js,bn]=E.useState(!1);if(E.useEffect(()=>{s.status!=="running"&&bn(!1)},[s.id,s.status]),!qe||!Dt)return null;const Pn="inline-flex items-center justify-center rounded-md p-2 transition bg-white/75 text-gray-900 ring-1 ring-black/10 hover:bg-white/90 active:scale-[0.98] dark:bg-black/45 dark:text-white dark:ring-white/10 dark:hover:bg-black/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500",me=String(s.phase??"").toLowerCase(),ye=me==="stopping"||me==="remuxing"||me==="moving",Se=!S||!M||ye||js,Ue=g.jsx("div",{className:"flex items-center gap-1 min-w-0",children:M?g.jsxs(g.Fragment,{children:[g.jsx(ti,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:Se,title:ye||js?"Stoppe…":"Stop","aria-label":ye||js?"Stoppe…":"Stop",onClick:async q=>{if(q.preventDefault(),q.stopPropagation(),!Se)try{bn(!0),await S?.(s.id)}finally{bn(!1)}},className:fo("shadow-none shrink-0",Ht&&Ui&&"px-2"),children:g.jsx("span",{className:"whitespace-nowrap",children:ye||js?"Stoppe…":Ht&&Ui?"Stop":"Stoppen"})}),g.jsx(Ua,{job:s,variant:"overlay",collapseToMenu:!0,busy:ye||js,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?q=>_(q):void 0,onToggleFavorite:v?q=>v(q):void 0,onToggleLike:b?q=>b(q):void 0,order:["watch","favorite","like","details"],className:"gap-1 min-w-0 flex-1"})]}):g.jsx(Ua,{job:s,variant:"overlay",collapseToMenu:!0,isHot:a||J,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?q=>_(q):void 0,onToggleFavorite:v?q=>v(q):void 0,onToggleLike:b?q=>b(q):void 0,onToggleHot:y?async q=>{Me(),await new Promise(ke=>setTimeout(ke,150)),await y(q),await new Promise(ke=>setTimeout(ke,0));const ce=ht.current;if(ce&&!ce.isDisposed?.()){const ke=ce.play?.();ke&&typeof ke.catch=="function"&&ke.catch(()=>{})}}:void 0,onKeep:f?async q=>{Me(),t(),await new Promise(ce=>setTimeout(ce,150)),await f(q)}:void 0,onDelete:p?async q=>{Me(),t(),await new Promise(ce=>setTimeout(ce,150)),await p(q)}:void 0,order:["watch","favorite","like","hot","keep","delete","details"],className:"gap-1 min-w-0 flex-1"})}),Qe=e||Ht,Kt="env(safe-area-inset-bottom)",Zt=`calc(${Ni}px + env(safe-area-inset-bottom))`,hi=M?Kt:Zt,Hi=M?"calc(8px + env(safe-area-inset-bottom))":`calc(${Ni+8}px + env(safe-area-inset-bottom))`,nn=Ht?"top-4":"top-2",Gi=e&&mi,Ns=g.jsx("div",{className:fo("relative overflow-visible",e||Ht?"flex-1 min-h-0":"aspect-video"),onMouseEnter:()=>{!Ht||!xn||Or(!0)},onMouseLeave:()=>{!Ht||!xn||Or(!1)},children:g.jsxs("div",{className:fo("relative w-full h-full",Ht&&"vjs-mini"),children:[M?g.jsxs("div",{className:"absolute inset-0 bg-black",children:[g.jsx(iR,{src:Q,muted:L,className:"w-full h-full object-contain"}),g.jsxs("div",{className:"absolute right-2 bottom-2 z-[60] pointer-events-none 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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]})]}):g.jsx("div",{ref:ot,className:"absolute inset-0"}),g.jsx("div",{className:fo("absolute inset-x-2 z-30",nn),children:g.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-2",children:[g.jsx("div",{className:"min-w-0 pointer-events-auto overflow-visible",children:Gi?null:Ue}),Ht?g.jsxs("button",{type:"button","aria-label":"Player-Fenster verschieben",title:"Ziehen zum Verschieben",onPointerDown:Ti,onClick:q=>{q.preventDefault(),q.stopPropagation()},className:fo(Pn,"px-3 gap-1 cursor-grab active:cursor-grabbing select-none",Mr?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none -translate-y-1",si&&"scale-[0.98] opacity-90"),children:[g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"})]}):null,g.jsxs("div",{className:"shrink-0 flex items-center gap-1 pointer-events-auto",children:[g.jsx("button",{type:"button",className:Pn,onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?g.jsx(TO,{className:"h-5 w-5"}):g.jsx(SO,{className:"h-5 w-5"})}),g.jsx("button",{type:"button",className:Pn,onClick:t,"aria-label":"Schließen",title:"Schließen",children:g.jsx(sb,{className:"h-5 w-5"})})]})]})}),g.jsx("div",{className:fo("player-ui pointer-events-none absolute inset-x-0 z-40","bg-gradient-to-t from-black/70 to-transparent","transition-all duration-200 ease-out",e?"h-28":"h-24"),style:{bottom:hi}}),g.jsxs("div",{className:fo("player-ui pointer-events-none absolute inset-x-2 z-50","flex items-end justify-between gap-2","transition-all duration-200 ease-out"),style:{bottom:Hi},children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white",children:ae}),g.jsx("div",{className:"truncate text-[11px] text-white/80",children:g.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0 align-middle",children:[g.jsx("span",{className:"truncate",children:se||I}),a||J?g.jsx("span",{className:"shrink-0 rounded bg-amber-500/25 px-1.5 py-0.5 font-semibold text-white",children:"HOT"}):null]})})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[Ve!=="—"?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:Ve}):null,M?null:g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:K}),B!=="—"?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:B}):null]})]})]})}),li=g.jsx("div",{className:"w-[360px] shrink-0 border-r border-white/10 bg-black/40 text-white",children:g.jsxs("div",{className:"h-full p-4 flex flex-col gap-3 overflow-y-auto",children:[g.jsx("div",{className:"rounded-lg overflow-hidden ring-1 ring-white/10 bg-black/30",children:g.jsx("div",{className:"relative aspect-video",children:g.jsx("img",{src:ue,alt:"Vorschau",className:"absolute inset-0 h-full w-full object-cover",loading:"lazy",onError:()=>{ue!==P&&he(P)}})})}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("div",{className:"text-lg font-semibold truncate",children:ae}),g.jsx("div",{className:"text-xs text-white/70 break-all",children:se||I})]}),g.jsx("div",{className:"pointer-events-auto",children:g.jsxs("div",{className:"flex items-center justify-center gap-2 flex-wrap",children:[M?g.jsx(ti,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:Se,title:ye||js?"Stoppe…":"Stop","aria-label":ye||js?"Stoppe…":"Stop",onClick:async q=>{if(q.preventDefault(),q.stopPropagation(),!Se)try{bn(!0),await S?.(s.id)}finally{bn(!1)}},className:"shadow-none",children:ye||js?"Stoppe…":"Stoppen"}):null,g.jsx(Ua,{job:s,variant:"table",collapseToMenu:!1,busy:ye||js,isHot:a||J,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:_?q=>_(q):void 0,onToggleFavorite:v?q=>v(q):void 0,onToggleLike:b?q=>b(q):void 0,onToggleHot:y?async q=>{Me(),await new Promise(ke=>setTimeout(ke,150)),await y(q),await new Promise(ke=>setTimeout(ke,0));const ce=ht.current;if(ce&&!ce.isDisposed?.()){const ke=ce.play?.();ke&&typeof ke.catch=="function"&&ke.catch(()=>{})}}:void 0,onKeep:f?async q=>{Me(),t(),await new Promise(ce=>setTimeout(ce,150)),await f(q)}:void 0,onDelete:p?async q=>{Me(),t(),await new Promise(ce=>setTimeout(ce,150)),await p(q)}:void 0,order:M?["watch","favorite","like","details"]:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-start gap-1"})]})}),g.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-2 text-sm",children:[g.jsx("div",{className:"text-white/60",children:"Status"}),g.jsx("div",{className:"font-medium",children:s.status}),g.jsx("div",{className:"text-white/60",children:"Auflösung"}),g.jsx("div",{className:"font-medium",children:Ve}),g.jsx("div",{className:"text-white/60",children:"FPS"}),g.jsx("div",{className:"font-medium",children:lt}),g.jsx("div",{className:"text-white/60",children:"Laufzeit"}),g.jsx("div",{className:"font-medium",children:K}),g.jsx("div",{className:"text-white/60",children:"Größe"}),g.jsx("div",{className:"font-medium",children:B}),g.jsx("div",{className:"text-white/60",children:"Datum"}),g.jsx("div",{className:"font-medium",children:X}),g.jsx("div",{className:"col-span-2",children:le.length?g.jsx("div",{className:"flex flex-wrap gap-1.5",children:le.map(q=>g.jsx("span",{className:"rounded bg-white/10 px-2 py-0.5 text-xs text-white/90",children:q},q))}):g.jsx("span",{className:"text-white/50",children:"—"})})]})]})}),Pr=g.jsx(ja,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:fo("relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10","w-full",Qe?"h-full":"h-[220px] max-h-[40vh]",e?"rounded-2xl":Ht?"rounded-lg":"rounded-none"),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:g.jsxs("div",{className:"flex flex-1 min-h-0",children:[Gi?li:null,Ns]})}),{w:Kn,h:rn,ox:Bn,oy:be,bottomInset:Ce}=ut(),Ae={left:Bn+16,top:be+16,width:Math.max(0,Kn-32),height:Math.max(0,rn-32)},Ye=e?Ae:Ht?{left:Mi.x,top:Mi.y,width:Mi.w,height:Mi.h}:void 0;return kc.createPortal(g.jsxs(g.Fragment,{children:[g.jsx("style",{children:` + /* Live-Download: Progress/Seek-Bar ausblenden */ + .is-live-download .vjs-progress-control { + display: none !important; + } + `}),e||Ht?g.jsxs("div",{className:fo("fixed z-[2147483647]",!Yi&&!si&&"transition-[left,top,width,height] duration-300 ease-[cubic-bezier(.2,.9,.2,1)]"),style:{...Ye,willChange:Yi?"left, top, width, height":void 0},children:[Pr,Ht?g.jsxs("div",{className:"pointer-events-none absolute inset-0",children:[g.jsx("div",{className:"pointer-events-auto absolute -left-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:Ts("w")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:Ts("e")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -top-1 h-3 cursor-ns-resize",onPointerDown:Ts("n")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -bottom-1 h-3 cursor-ns-resize",onPointerDown:Ts("s")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -top-1 h-4 w-4 cursor-nwse-resize",onPointerDown:Ts("nw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -top-1 h-4 w-4 cursor-nesw-resize",onPointerDown:Ts("ne")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -bottom-1 h-4 w-4 cursor-nesw-resize",onPointerDown:Ts("sw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -bottom-1 h-4 w-4 cursor-nwse-resize",onPointerDown:Ts("se")})]}):null]}):g.jsx("div",{className:` + fixed z-[2147483647] inset-x-0 w-full + shadow-2xl + md:bottom-4 md:left-1/2 md:right-auto md:inset-x-auto md:w-[min(760px,calc(100vw-32px))] md:-translate-x-1/2 + `,style:{bottom:`calc(${Ce}px + env(safe-area-inset-bottom))`},children:Pr})]}),Dt)}function sR({jobId:s,thumbTick:e,autoTickMs:t=1e4,blur:i=!1,alignStartAt:n,alignEndAt:r=null,alignEveryMs:a,fastRetryMs:u,fastRetryMax:c,fastRetryWindowMs:d,className:f}){const[p,y]=E.useState(()=>typeof document>"u"?!0:!document.hidden),v=i?"blur-md":"",[b,_]=E.useState(0),[S,L]=E.useState(!1),I=E.useRef(null),[R,$]=E.useState(!1),B=E.useRef(null),F=E.useRef(0),M=E.useRef(!1),G=E.useRef(!1),D=J=>{if(typeof J=="number"&&Number.isFinite(J))return J;if(J instanceof Date)return J.getTime();const ae=Date.parse(String(J??""));return Number.isFinite(ae)?ae:NaN};E.useEffect(()=>{const J=()=>y(!document.hidden);return document.addEventListener("visibilitychange",J),()=>document.removeEventListener("visibilitychange",J)},[]),E.useEffect(()=>()=>{B.current&&window.clearTimeout(B.current)},[]),E.useEffect(()=>{typeof e!="number"&&(!R||!p||G.current||(G.current=!0,_(J=>J+1)))},[R,e,p]),E.useEffect(()=>{if(typeof e=="number"||!R||!p)return;const J=Number(a??t??1e4);if(!Number.isFinite(J)||J<=0)return;const ae=n?D(n):NaN,se=r?D(r):NaN;if(Number.isFinite(ae)){let X;const ee=()=>{const le=Date.now();if(Number.isFinite(se)&&le>=se)return;const P=Math.max(0,le-ae)%J,Q=P===0?J:J-P;X=window.setTimeout(()=>{_(ue=>ue+1),ee()},Q)};return ee(),()=>{X&&window.clearTimeout(X)}}const K=window.setInterval(()=>{_(X=>X+1)},J);return()=>window.clearInterval(K)},[e,t,R,p,n,r,a]),E.useEffect(()=>{const J=I.current;if(!J)return;const ae=new IntersectionObserver(se=>{const K=se[0];$(!!(K&&(K.isIntersecting||K.intersectionRatio>0)))},{root:null,threshold:0,rootMargin:"300px 0px"});return ae.observe(J),()=>ae.disconnect()},[]);const O=typeof e=="number"?e:b;E.useEffect(()=>{L(!1)},[O]),E.useEffect(()=>{M.current=!1,F.current=0,G.current=!1,L(!1),_(J=>J+1)},[s]);const W=E.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${O}`,[s,O]),Y=E.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&hover=1&file=index_hq.m3u8`,[s]);return g.jsx(OA,{content:(J,{close:ae})=>J&&g.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:g.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[g.jsx(iR,{src:Y,muted:!1,className:["w-full h-full relative z-0"].filter(Boolean).join(" ")}),g.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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),g.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:se=>{se.preventDefault(),se.stopPropagation(),ae()},children:g.jsx(sb,{className:"h-4 w-4"})})]})}),children:g.jsx("div",{ref:I,className:["block relative rounded bg-gray-100 dark:bg-white/5 overflow-hidden",f||"w-full h-full"].join(" "),children:S?g.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"}):g.jsx("img",{src:W,loading:R?"eager":"lazy",fetchPriority:R?"high":"auto",alt:"",className:["block w-full h-full object-cover object-center",v].filter(Boolean).join(" "),onLoad:()=>{M.current=!0,F.current=0,B.current&&window.clearTimeout(B.current),L(!1)},onError:()=>{if(L(!0),!u||!R||!p||M.current)return;const J=n?D(n):NaN,ae=Number(d??6e4);if(!(!Number.isFinite(J)||Date.now()-J=K||(B.current&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{F.current+=1,_(X=>X+1)},u))}})})})}const Gc=new Map;let zw=!1;function d$(){zw||(zw=!0,document.addEventListener("visibilitychange",()=>{if(document.hidden)for(const s of Gc.values())s.es&&(s.es.close(),s.es=null,s.dispatchers.clear());else for(const s of Gc.values())s.refs>0&&!s.es&&nR(s)}))}function nR(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 a of t)a(r)};s.dispatchers.set(e,i),s.es.addEventListener(e,i)}s.es.onerror=()=>{}}}function h$(s){s.es&&(s.es.close(),s.es=null,s.dispatchers.clear())}function f$(s){let e=Gc.get(s);return e||(e={url:s,es:null,refs:0,listeners:new Map,dispatchers:new Map},Gc.set(s,e)),e}function rR(s,e,t){d$();const i=f$(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=a=>{let u=null;try{u=JSON.parse(String(a.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 nR(i);return()=>{const r=Gc.get(s);if(!r)return;const a=r.listeners.get(e);a&&(a.delete(t),a.size===0&&r.listeners.delete(e)),r.refs=Math.max(0,r.refs-1),r.refs===0&&(h$(r),Gc.delete(s))}}const Fp=s=>{const e=s;return e.modelName??e.model??e.modelKey??e.username??e.name??"—"},aR=s=>{const e=s;return e.sourceUrl??e.url??e.roomUrl??""},oR=s=>{const e=s;return String(e.imageUrl??e.image_url??"").trim()},nc=s=>{const e=s;return String(e.key??e.id??Fp(s))},mn=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},rc=s=>{if(s.kind==="job"){const t=s.job;return mn(t.addedAt)||mn(t.createdAt)||mn(t.enqueuedAt)||mn(t.queuedAt)||mn(t.requestedAt)||mn(t.startedAt)||0}const e=s.pending;return mn(e.addedAt)||mn(e.createdAt)||mn(e.enqueuedAt)||mn(e.queuedAt)||mn(e.requestedAt)||0},lR=s=>{switch((s??"").toLowerCase()){case"stopping":return"Stop wird angefordert…";case"probe":return"Analysiere Datei (Dauer/Streams)…";case"remuxing":return"Konvertiere Container zu MP4…";case"moving":return"Verschiebe nach Done…";case"assets":return"Erstelle Vorschau/Thumbnails…";case"postwork":return"Nacharbeiten laufen…";default:return""}};async function m$(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 uR(s,e){const t=s.postWork;if(!t)return"Warte auf Nacharbeiten…";if(t.state==="running"){const i=typeof t.running=="number"?t.running:0,n=typeof t.maxParallel=="number"?t.maxParallel:0;return n>0?`Nacharbeiten laufen… (${i}/${n} parallel)`:"Nacharbeiten laufen…"}if(t.state==="queued"){const i=typeof t.position=="number"?t.position:0,n=typeof t.waiting=="number"?t.waiting:0,r=typeof t.running=="number"?t.running:0,a=Math.max(n+r,i),u=typeof e?.pos=="number"&&Number.isFinite(e.pos)&&e.pos>0?e.pos:i,c=typeof e?.total=="number"&&Number.isFinite(e.total)&&e.total>0?e.total:a;return u>0&&c>0?`Warte auf Nacharbeiten… ${u} / ${c}`:"Warte auf Nacharbeiten…"}return"Warte auf Nacharbeiten…"}function p$({job:s,postworkInfo:e}){const t=String(s?.phase??"").trim(),i=Number(s?.progress??0),n=t.toLowerCase(),r=n==="recording";let a=t?lR(t)||t:"";n==="postwork"&&(a=uR(s,e)),r&&(a="Recording läuft…");const u=a||String(s?.status??"").trim().toLowerCase(),c=!r&&Number.isFinite(i)&&i>0&&i<100,d=!r&&!c&&!!t&&(!Number.isFinite(i)||i<=0||i>=100);return g.jsx("div",{className:"min-w-0",children:c?g.jsx(Dc,{label:u,value:Math.max(0,Math.min(100,i)),showPercent:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):d?g.jsx(Dc,{label:u,indeterminate:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:u})})})}function Iv({r:s,nowMs:e,blurPreviews:t,modelsByKey:i,stopRequestedIds:n,postworkInfoOf:r,markStopRequested:a,onOpenPlayer:u,onStopJob:c,onToggleFavorite:d,onToggleLike:f,onToggleWatch:p}){if(s.kind==="pending"){const X=s.pending,ee=Fp(X),le=aR(X),pe=(X.currentShow||"unknown").toLowerCase();return g.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:[g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",title:ee,children:ee}),g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[g.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"}),g.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:pe})]})]}),g.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:"⏳"})]}),g.jsx("div",{className:"mt-3",children:(()=>{const P=oR(X);return g.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:P?g.jsx("img",{src:P,alt:ee,className:["h-full w-full object-cover",t?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:Q=>{Q.currentTarget.style.display="none"}}):g.jsx("div",{className:"grid h-full w-full place-items-center",children:g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-300",children:"Waiting…"})})})})()}),le?g.jsx("a",{href:le,target:"_blank",rel:"noreferrer",className:"mt-3 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:P=>P.stopPropagation(),title:le,children:le}):null]})]})}const y=s.job,v=Wx(y.output),b=mT(y.output||""),_=String(y.phase??"").trim(),S=_.toLowerCase(),L=S==="recording",I=!!n[y.id],R=String(y.status??"").toLowerCase(),B=S!==""&&S!=="recording"||R!=="running"||I;let F=_?lR(_)||_:"";S==="recording"?F="Recording läuft…":S==="postwork"&&(F=uR(y,r(y)));const M=R||"unknown",G=F||M,D=Number(y.progress??0),O=!L&&Number.isFinite(D)&&D>0&&D<100,W=!L&&!O&&!!_&&(!Number.isFinite(D)||D<=0||D>=100),Y=v&&v!=="—"?v.toLowerCase():"",J=Y?i[Y]:void 0,ae=!!J?.favorite,se=J?.liked===!0,K=!!J?.watching;return g.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:()=>u(y),role:"button",tabIndex:0,onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&u(y)},children:[g.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"}),g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start gap-3",children:[g.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:g.jsx(sR,{jobId:y.id,blur:t,alignStartAt:y.startedAt,alignEndAt:y.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-base font-semibold text-gray-900 dark:text-white",title:v,children:v}),g.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",B?"ring-1 ring-amber-500/30":"ring-1 ring-emerald-500/25"].join(" "),title:M,children:M})]}),g.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-600 dark:text-gray-300",title:y.output,children:b||"—"})]}),g.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-1",children:[g.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:cR(y,e)}),g.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:hR(dR(y))})]})]}),y.sourceUrl?g.jsx("a",{href:y.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:X=>X.stopPropagation(),title:y.sourceUrl,children:y.sourceUrl}):null]})]}),O||W?g.jsx("div",{className:"mt-3",children:O?g.jsx(Dc,{label:G,value:Math.max(0,Math.min(100,D)),showPercent:!0,size:"sm",className:"w-full"}):g.jsx(Dc,{label:G,indeterminate:!0,size:"sm",className:"w-full"})}):null,g.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2 border-t border-white/30 pt-3 dark:border-white/10",children:[g.jsx("div",{className:"flex items-center gap-1",onClick:X=>X.stopPropagation(),onMouseDown:X=>X.stopPropagation(),children:g.jsx(Ua,{job:y,variant:"table",busy:B,isFavorite:ae,isLiked:se,isWatching:K,onToggleFavorite:d,onToggleLike:f,onToggleWatch:p,order:["watch","favorite","like","details"],className:"flex items-center gap-1"})}),g.jsx(ti,{size:"sm",variant:"primary",disabled:B,className:"shrink-0",onClick:X=>{X.stopPropagation(),!B&&(a(y.id),c(y.id))},children:B?"Stoppe…":"Stop"})]})]})]})}const mT=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",Wx=s=>{const e=mT(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},g$=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`},cR=(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)?g$(i-t):"—"},dR=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},hR=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]}`},Nv=s=>{const e=s,t=String(e.phase??"").trim(),i=e.postWork;return!!(String(e.postWorkKey??"").trim()||i&&(i.state==="queued"||i.state==="running")||s.endedAt&&t||t==="postwork")};function y$({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,modelsByKey:c={},blurPreviews:d}){const[f,p]=E.useState(!1),[y,v]=E.useState(!1),b=E.useRef(null),[_,S]=E.useState(!1),L=E.useCallback(async()=>{try{const Q=!!(await m$("/api/autostart/state",{cache:"no-store"}))?.paused;b.current=Q,v(Q)}catch{}},[]);E.useEffect(()=>{L();const P=rR("/api/autostart/state/stream","autostart",Q=>{const ue=!!Q?.paused;b.current!==ue&&(b.current=ue,v(ue))});return()=>{P()}},[L]);const I=E.useCallback(async()=>{if(!(_||y)){S(!0);try{await fetch("/api/autostart/pause",{method:"POST"}),v(!0)}catch{}finally{S(!1)}}},[_,y]),R=E.useCallback(async()=>{if(!(_||!y)){S(!0);try{await fetch("/api/autostart/resume",{method:"POST"}),v(!1)}catch{}finally{S(!1)}}},[_,y]),[$,B]=E.useState({}),[F,M]=E.useState({}),G=E.useCallback(P=>{const Q=Array.isArray(P)?P:[P];B(ue=>{const he={...ue};for(const re of Q)re&&(he[re]=!0);return he}),M(ue=>{const he={...ue};for(const re of Q)re&&(he[re]=!0);return he})},[]);E.useEffect(()=>{B(P=>{const Q=Object.keys(P);if(Q.length===0)return P;const ue={};for(const he of Q){const re=s.find(Ve=>Ve.id===he);if(!re)continue;const Pe=String(re.phase??"").trim().toLowerCase();Pe!==""&&Pe!=="recording"||re.status!=="running"||(ue[he]=!0)}return ue})},[s]);const[D,O]=E.useState(()=>Date.now()),W=E.useMemo(()=>s.some(P=>!P.endedAt&&P.status==="running"),[s]),Y=E.useMemo(()=>{const P=new Map,Q=Ee=>{const Ge=Ee,Ve=Ge.postWork;return mn(Ve?.enqueuedAt)||mn(Ge.enqueuedAt)||mn(Ge.queuedAt)||mn(Ge.createdAt)||mn(Ge.addedAt)||mn(Ee.endedAt)||mn(Ee.startedAt)||0},ue=[],he=[];for(const Ee of s){const Ge=Ee?.postWork;if(!Ge)continue;const Ve=String(Ge.state??"").toLowerCase();Ve==="running"?ue.push(Ee):Ve==="queued"&&he.push(Ee)}ue.sort((Ee,Ge)=>Q(Ee)-Q(Ge)),he.sort((Ee,Ge)=>Q(Ee)-Q(Ge));const re=ue.length,Pe=re+he.length;for(let Ee=0;Ee{const Q=String(P?.id??"");return Q?Y.get(Q):void 0},[Y]);E.useEffect(()=>{if(!W)return;const P=window.setInterval(()=>O(Date.now()),15e3);return()=>window.clearInterval(P)},[W]);const ae=E.useMemo(()=>s.filter(P=>{if(Nv(P)||P.endedAt)return!1;const Q=String(P.phase??"").trim(),ue=!!$[P.id],he=Q.trim().toLowerCase();return!(he!==""&&he!=="recording"||P.status!=="running"||ue)}).map(P=>P.id),[s,$]),se=E.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[96px]",cell:P=>{if(P.kind==="job"){const re=P.job;return g.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md",children:g.jsx(sR,{jobId:re.id,blur:d,alignStartAt:re.startedAt,alignEndAt:re.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})})}const Q=P.pending,ue=Fp(Q),he=oR(Q);return he?g.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:g.jsx("img",{src:he,alt:ue,className:["h-full w-full object-cover",d?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:re=>{re.currentTarget.style.display="none"}})}):g.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:P=>{if(P.kind==="job"){const re=P.job,Pe=mT(re.output||""),Ee=Wx(re.output),Ge=String(re.status??"").toLowerCase(),Ve=!!$[re.id],lt=!!F[re.id],_t=Ge==="stopped"||lt&&!!re.endedAt,mt=_t?"stopped":Ge||"unknown",Ze=!_t&&Ve,bt=Ze?"stopping":mt;return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"min-w-0 block max-w-[170px] truncate font-medium",title:Ee,children:Ee}),g.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1",Ge==="running"?"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":_t?"bg-slate-500/15 text-slate-900 ring-slate-500/30 dark:bg-slate-400/10 dark:text-slate-200 dark:ring-slate-400/25":Ge==="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":Ge==="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":Ze?"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:bt,children:bt})]}),g.jsx("span",{className:"block max-w-[220px] truncate",title:re.output,children:Pe}),re.sourceUrl?g.jsx("a",{href:re.sourceUrl,target:"_blank",rel:"noreferrer",title:re.sourceUrl,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:gt=>gt.stopPropagation(),children:re.sourceUrl}):g.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}const Q=P.pending,ue=Fp(Q),he=aR(Q);return g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"block max-w-[170px] truncate font-medium",title:ue,children:ue}),he?g.jsx("a",{href:he,target:"_blank",rel:"noreferrer",title:he,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:re=>re.stopPropagation(),children:he}):g.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:P=>{if(P.kind==="job"){const he=P.job;return g.jsx(p$,{job:he,postworkInfo:J(he)})}const ue=(P.pending.currentShow||"unknown").toLowerCase();return g.jsx("div",{className:"min-w-0",children:g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:ue})})})}},{key:"runtime",header:"Dauer",widthClassName:"w-[90px]",cell:P=>P.kind==="job"?cR(P.job,D):"—"},{key:"size",header:"Größe",align:"right",widthClassName:"w-[110px]",cell:P=>P.kind==="job"?g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white",children:hR(dR(P.job))}):g.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:P=>{if(P.kind!=="job")return g.jsx("div",{className:"pr-2 text-right text-sm text-gray-500 dark:text-gray-400",children:"—"});const Q=P.job,ue=String(Q.phase??"").trim(),he=!!$[Q.id],re=ue.trim().toLowerCase(),Ee=re!==""&&re!=="recording"||Q.status!=="running"||he,Ge=Wx(Q.output||""),Ve=Ge&&Ge!=="—"?c[Ge.toLowerCase()]:void 0,lt=!!Ve?.favorite,_t=Ve?.liked===!0,mt=!!Ve?.watching;return g.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pr-2",children:[g.jsx(Ua,{job:Q,variant:"table",busy:Ee,isFavorite:lt,isLiked:_t,isWatching:mt,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,order:["watch","favorite","like","details"],className:"flex items-center gap-1"}),(()=>{const Ze=String(Q.phase??"").trim(),bt=!!$[Q.id],gt=Ze.trim().toLowerCase(),wt=gt!==""&>!=="recording"||Q.status!=="running"||bt;return g.jsx(ti,{size:"sm",variant:"primary",disabled:wt,className:"shrink-0",onClick:Et=>{Et.stopPropagation(),!wt&&(G(Q.id),i(Q.id))},children:wt?"Stoppe…":"Stop"})})()]})}}],[d,G,c,D,i,n,r,a,$,F,J]),K=E.useMemo(()=>{const P=s.filter(Q=>!Nv(Q)).map(Q=>({kind:"job",job:Q}));return P.sort((Q,ue)=>rc(ue)-rc(Q)),P},[s]),X=E.useMemo(()=>{const P=s.filter(Q=>Nv(Q)).map(Q=>({kind:"job",job:Q}));return P.sort((Q,ue)=>rc(ue)-rc(Q)),P},[s]),ee=E.useMemo(()=>{const P=e.map(Q=>({kind:"pending",pending:Q}));return P.sort((Q,ue)=>rc(ue)-rc(Q)),P},[e]),le=K.length+X.length+ee.length,pe=E.useCallback(async()=>{if(!f&&ae.length!==0){p(!0);try{G(ae),await Promise.allSettled(ae.map(P=>Promise.resolve(i(P))))}finally{p(!1)}}},[f,ae,G,i]);return g.jsxs("div",{className:"grid gap-3",children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:g.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[g.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Downloads"}),g.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:le})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[g.jsx(ti,{size:"sm",variant:y?"secondary":"primary",disabled:_,onClick:P=>{P.preventDefault(),P.stopPropagation(),y?R():I()},className:"hidden sm:inline-flex",title:y?"Autostart fortsetzen":"Autostart pausieren",leadingIcon:y?g.jsx(yM,{className:"size-4 shrink-0"}):g.jsx(xM,{className:"size-4 shrink-0"}),children:"Autostart"}),g.jsx(ti,{size:"sm",variant:"primary",disabled:f||ae.length===0,onClick:P=>{P.preventDefault(),P.stopPropagation(),pe()},className:"hidden sm:inline-flex",title:ae.length===0?"Nichts zu stoppen":"Alle laufenden stoppen",children:f?"Stoppe alle…":`Alle stoppen (${ae.length})`})]})]})})}),K.length>0||X.length>0||ee.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-3 grid gap-4 sm:hidden",children:[K.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Downloads (",K.length,")"]}),K.map(P=>g.jsx(Iv,{r:P,nowMs:D,blurPreviews:d,modelsByKey:c,postworkInfoOf:J,stopRequestedIds:$,markStopRequested:G,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`dl:${P.kind==="job"?P.job.id:nc(P.pending)}`))]}):null,X.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Nacharbeiten (",X.length,")"]}),X.map(P=>g.jsx(Iv,{r:P,nowMs:D,blurPreviews:d,modelsByKey:c,postworkInfoOf:J,stopRequestedIds:$,markStopRequested:G,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`pw:${P.kind==="job"?P.job.id:nc(P.pending)}`))]}):null,ee.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Wartend (",ee.length,")"]}),ee.map(P=>g.jsx(Iv,{r:P,nowMs:D,blurPreviews:d,modelsByKey:c,postworkInfoOf:J,stopRequestedIds:$,markStopRequested:G,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`wa:${P.kind==="job"?P.job.id:nc(P.pending)}`))]}):null]}),g.jsxs("div",{className:"mt-3 hidden sm:block space-y-4",children:[K.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Downloads (",K.length,")"]}),g.jsx(ph,{rows:K,columns:se,getRowKey:P=>P.kind==="job"?`dl:job:${P.job.id}`:`dl:pending:${nc(P.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:P=>{P.kind==="job"&&t(P.job)}})]}):null,X.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Nacharbeiten (",X.length,")"]}),g.jsx(ph,{rows:X,columns:se,getRowKey:P=>P.kind==="job"?`pw:job:${P.job.id}`:`pw:pending:${nc(P.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:P=>{P.kind==="job"&&t(P.job)}})]}):null,ee.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Wartend (",ee.length,")"]}),g.jsx(ph,{rows:ee,columns:se,getRowKey:P=>P.kind==="job"?`wa:job:${P.job.id}`:`wa:pending:${nc(P.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0})]}):null]})]}):g.jsx(ja,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"⏸️"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine laufenden Downloads"}),g.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."})]})]})})]})}function Yx({open:s,onClose:e,title:t,children:i,footer:n,icon:r,width:a="max-w-lg"}){return g.jsx(mh,{show:s,as:E.Fragment,children:g.jsxs(mc,{as:"div",className:"relative z-50",onClose:e,children:[g.jsx(mh.Child,{as:E.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:g.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),g.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto px-4 py-6 sm:px-6",children:g.jsx("div",{className:"min-h-full flex items-start justify-center sm:items-center",children:g.jsx(mh.Child,{as:E.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:g.jsxs(mc.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",a].join(" "),children:[r&&g.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}),g.jsxs("div",{className:"px-6 pt-6 flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0",children:t?g.jsx(mc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white truncate",children:t}):null}),g.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:g.jsx(sb,{className:"size-5"})})]}),g.jsx("div",{className:"px-6 pb-6 pt-4 text-sm text-gray-700 dark:text-gray-300 overflow-y-auto",children:i}),n?g.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 Ov(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 qw=(s,e)=>g.jsx("span",{className:xi("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 v$(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 Mv(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 x$(s){return String(s??"").trim().toLowerCase().replace(/^www\./,"")}function b$(s){const t=String(s||"").replaceAll("\\","/").split("/");return t[t.length-1]||""}function T$(s){const e=String(s||"");return e.toUpperCase().startsWith("HOT ")?e.slice(4).trim():e}function _$(s){const e=b$(s||""),t=T$(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}function Pv(s){if(s.isUrl&&/^https?:\/\//i.test(String(s.input??"")))return String(s.input);const e=x$(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 Kw({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return g.jsx("span",{className:xi(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:g.jsx(ti,{variant:e?"soft":"secondary",size:"xs",className:xi("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:g.jsx("span",{className:"text-base leading-none",children:n})})})}function Ww(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 S$(){const[s,e]=E.useState([]),t=E.useRef({}),[i,n]=E.useState(!1),[r,a]=E.useState(null),[u,c]=E.useState(""),[d,f]=E.useState(1),p=10,[y,v]=E.useState([]),[b,_]=E.useState({}),[S,L]=E.useState(!1),[I,R]=E.useState(),$=E.useCallback(async()=>{L(!0);try{const ve=await fetch("/api/record/done?all=1&includeKeep=1",{cache:"no-store"});if(!ve.ok)return;const dt=await ve.json().catch(()=>null),qe=Array.isArray(dt?.items)?dt.items:Array.isArray(dt)?dt:[],st={};for(const ft of qe){const yt=_$(ft.output);if(!yt||yt==="—")continue;const nt=yt.trim().toLowerCase();nt&&(st[nt]=(st[nt]??0)+1)}_(st)}finally{L(!1)}},[]),B=E.useMemo(()=>new Set(y.map(ve=>ve.toLowerCase())),[y]),F=E.useCallback(ve=>{const dt=ve.toLowerCase();v(qe=>qe.some(ft=>ft.toLowerCase()===dt)?qe.filter(ft=>ft.toLowerCase()!==dt):[...qe,ve])},[]),M=E.useCallback(()=>v([]),[]);E.useEffect(()=>{const ve=dt=>{const qe=dt,st=Array.isArray(qe.detail?.tags)?qe.detail.tags:[];v(st)};return window.addEventListener("models:set-tag-filter",ve),()=>window.removeEventListener("models:set-tag-filter",ve)},[]),E.useEffect(()=>{try{const ve=localStorage.getItem("models_pendingTags");if(!ve)return;const dt=JSON.parse(ve);Array.isArray(dt)&&v(dt),localStorage.removeItem("models_pendingTags")}catch{}},[]);const[G,D]=E.useState(""),[O,W]=E.useState(null),[Y,J]=E.useState(null),[ae,se]=E.useState(!1),[K,X]=E.useState(!1),[ee,le]=E.useState(null),[pe,P]=E.useState(null),[Q,ue]=E.useState("favorite"),[he,re]=E.useState(!1),[Pe,Ee]=E.useState(null);async function Ge(){if(ee){re(!0),P(null),a(null);try{const ve=new FormData;ve.append("file",ee),ve.append("kind",Q);const dt=await fetch("/api/models/import",{method:"POST",body:ve});if(!dt.ok)throw new Error(await dt.text());const qe=await dt.json();P(`✅ Import: ${qe.inserted} neu, ${qe.updated} aktualisiert, ${qe.skipped} übersprungen`),X(!1),le(null),await _t(),window.dispatchEvent(new Event("models-changed"))}catch(ve){Ee(ve?.message??String(ve))}finally{re(!1)}}}function Ve(ve){const dt=Pv(ve)??void 0;return{output:`${ve.modelKey}_01_01_2000__00-00-00.mp4`,sourceUrl:dt}}const lt=()=>{Ee(null),P(null),le(null),ue("favorite"),X(!0)},_t=E.useCallback(async()=>{n(!0),a(null);try{const ve=await Ov("/api/models/list",{cache:"no-store"});e(Array.isArray(ve)?ve:[]),$()}catch(ve){a(ve?.message??String(ve))}finally{n(!1)}},[$]);E.useEffect(()=>{$()},[$]),E.useEffect(()=>{_t()},[_t]),E.useEffect(()=>{const ve=dt=>{const st=dt?.detail??{};if(st?.model){const ft=st.model;e(yt=>{const nt=yt.findIndex(qt=>qt.id===ft.id);if(nt===-1)return yt;const jt=yt.slice();return jt[nt]=ft,jt});return}if(st?.removed&&st?.id){const ft=String(st.id);e(yt=>yt.filter(nt=>nt.id!==ft));return}_t()};return window.addEventListener("models-changed",ve),()=>window.removeEventListener("models-changed",ve)},[_t]),E.useEffect(()=>{const ve=G.trim();if(!ve){W(null),J(null);return}const dt=v$(ve);if(!dt){W(null),J("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const qe=window.setTimeout(async()=>{try{const st=await Ov("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:dt})});if(!st?.isUrl){W(null),J("Bitte nur URLs einfügen (keine Modelnamen).");return}W(st),J(null)}catch(st){W(null),J(st?.message??String(st))}},300);return()=>window.clearTimeout(qe)},[G]);const mt=E.useMemo(()=>s.map(ve=>({m:ve,hay:`${ve.modelKey} ${ve.host??""} ${ve.input??""} ${ve.tags??""}`.toLowerCase()})),[s]),Ze=E.useDeferredValue(u),bt=E.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:ve=>{const dt=ve.liked===!0,qe=ve.favorite===!0,st=ve.watching===!0,ft=!st&&!qe&&!dt;return g.jsxs("div",{className:"group flex items-center justify-center gap-1 w-[110px]",children:[g.jsx("span",{className:xi(ft&&!st?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:g.jsx(ti,{variant:st?"soft":"secondary",size:"xs",className:xi("px-2 py-1 leading-none",!st&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:st?"Nicht mehr beobachten":"Beobachten",onClick:yt=>{yt.stopPropagation(),ht(ve.id,{watched:!st})},children:g.jsx("span",{className:xi("text-base leading-none",st?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),g.jsx(Kw,{title:qe?"Favorit entfernen":"Als Favorit markieren",active:qe,hiddenUntilHover:ft,onClick:yt=>{yt.stopPropagation(),qe?ht(ve.id,{favorite:!1}):ht(ve.id,{favorite:!0,liked:!1})},icon:g.jsx("span",{className:qe?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),g.jsx(Kw,{title:dt?"Gefällt mir entfernen":"Gefällt mir",active:dt,hiddenUntilHover:ft,onClick:yt=>{yt.stopPropagation(),dt?ht(ve.id,{liked:!1}):ht(ve.id,{liked:!0,favorite:!1})},icon:g.jsx("span",{className:dt?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",sortable:!0,sortValue:ve=>(ve.modelKey||"").toLowerCase(),cell:ve=>{const dt=Pv(ve);return g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"font-medium truncate",children:ve.modelKey}),dt?g.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",title:dt,onClick:qe=>{qe.stopPropagation(),window.open(dt,"_blank","noreferrer")},children:"↗"}):null]}),g.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:ve.host??"—"}),dt?g.jsx("div",{className:"text-xs text-indigo-600 dark:text-indigo-400 truncate max-w-[520px]",children:dt}):null]})}},{key:"videos",header:"Videos",sortable:!0,sortValue:ve=>{const dt=String(ve.modelKey||"").trim().toLowerCase(),qe=b[dt];return typeof qe=="number"?qe:0},align:"right",cell:ve=>{const dt=String(ve.modelKey||"").trim().toLowerCase(),qe=b[dt];return g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white w-[64px] inline-block text-right",children:typeof qe=="number"?qe:S?"…":0})}},{key:"tags",header:"Tags",sortable:!0,sortValue:ve=>Mv(ve.tags).length,cell:ve=>{const dt=Mv(ve.tags),qe=dt.slice(0,6),st=dt.length-qe.length,ft=dt.join(", ");return g.jsxs("div",{className:"flex flex-wrap gap-2 max-w-[520px]",title:ft||void 0,children:[ve.hot?qw(!0,"🔥 HOT"):null,ve.keep?qw(!0,"📌 Behalten"):null,qe.map(yt=>g.jsx(aa,{tag:yt,title:yt,active:B.has(yt.toLowerCase()),onClick:F},yt)),st>0?g.jsxs(aa,{title:ft,children:["+",st]}):null,!ve.hot&&!ve.keep&&dt.length===0?g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}},{key:"actions",header:"",align:"right",cell:ve=>g.jsx("div",{className:"flex justify-end w-[92px]",children:g.jsx(Ua,{job:Ve(ve),variant:"table",order:["add","details"],className:"flex items-center gap-2"})})}],[B,F,b,S]),gt=E.useMemo(()=>{const ve=Ze.trim().toLowerCase(),dt=ve?mt.filter(qe=>qe.hay.includes(ve)).map(qe=>qe.m):s;return B.size===0?dt:dt.filter(qe=>{const st=Mv(qe.tags);if(st.length===0)return!1;const ft=new Set(st.map(yt=>yt.toLowerCase()));for(const yt of B)if(!ft.has(yt))return!1;return!0})},[s,mt,Ze,B]),at=E.useMemo(()=>{if(!I)return gt;const ve=bt.find(st=>st.key===I.key);if(!ve)return gt;const dt=I.direction==="asc"?1:-1,qe=gt.map((st,ft)=>({r:st,i:ft}));return qe.sort((st,ft)=>{let yt=0;if(ve.sortFn)yt=ve.sortFn(st.r,ft.r);else{const nt=ve.sortValue?ve.sortValue(st.r):st.r?.[ve.key],jt=ve.sortValue?ve.sortValue(ft.r):ft.r?.[ve.key],qt=Ww(nt),Yt=Ww(jt);qt.isNull&&!Yt.isNull?yt=1:!qt.isNull&&Yt.isNull?yt=-1:qt.kind==="number"&&Yt.kind==="number"?yt=qt.valueYt.value?1:0:yt=String(qt.value).localeCompare(String(Yt.value),void 0,{numeric:!0})}return yt===0?st.i-ft.i:yt*dt}),qe.map(st=>st.r)},[gt,I,bt]);E.useEffect(()=>{f(1)},[u,y]);const wt=at.length,Et=E.useMemo(()=>Math.max(1,Math.ceil(wt/p)),[wt,p]);E.useEffect(()=>{d>Et&&f(Et)},[d,Et]);const Ot=E.useMemo(()=>{const ve=(d-1)*p;return at.slice(ve,ve+p)},[at,d,p]),ot=async()=>{if(O){if(!O.isUrl){J("Bitte nur URLs einfügen (keine Modelnamen).");return}se(!0),a(null);try{const ve=await Ov("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});e(dt=>{const qe=dt.filter(st=>st.id!==ve.id);return[ve,...qe]}),D(""),W(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:ve}}))}catch(ve){a(ve?.message??String(ve))}finally{se(!1)}}};async function ht(ve,dt){if(a(null),t.current[ve])return;t.current[ve]=!0;const qe=s.find(st=>st.id===ve)??null;if(qe){const st={...qe,...dt};typeof dt?.watched=="boolean"&&(st.watching=dt.watched),dt?.favorite===!0&&(st.liked=!1),dt?.liked===!0&&(st.favorite=!1),e(ft=>ft.map(yt=>yt.id===ve?st:yt)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:st}}))}try{const st=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:ve,...dt})});if(st.status===204){e(yt=>yt.filter(nt=>nt.id!==ve)),qe?window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:qe.id,modelKey:qe.modelKey}})):window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ve}}));return}if(!st.ok){const yt=await st.text().catch(()=>"");throw new Error(yt||`HTTP ${st.status}`)}const ft=await st.json();e(yt=>{const nt=yt.findIndex(qt=>qt.id===ft.id);if(nt===-1)return yt;const jt=yt.slice();return jt[nt]=ft,jt}),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:ft}}))}catch(st){qe&&(e(ft=>ft.map(yt=>yt.id===ve?qe:yt)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:qe}}))),a(st?.message??String(st))}finally{delete t.current[ve]}}return g.jsxs("div",{className:"space-y-4",children:[g.jsx(ja,{header:g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:g.jsxs("div",{className:"grid gap-2",children:[g.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[g.jsx("input",{value:G,onChange:ve=>D(ve.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"}),g.jsx(ti,{className:"px-3 py-2 text-sm",onClick:ot,disabled:!O||ae,title:O?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),g.jsx(ti,{className:"px-3 py-2 text-sm",onClick:_t,disabled:i,children:"Aktualisieren"})]}),Y?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:Y}):O?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",g.jsx("span",{className:"font-medium",children:O.modelKey}),O.host?g.jsxs("span",{className:"opacity-70",children:[" • ",O.host]}):null]}):null,r?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:r}):null]})}),g.jsxs(ja,{header:g.jsxs("div",{className:"space-y-2",children:[g.jsxs("div",{className:"grid gap-2 sm:flex sm:items-center sm:justify-between",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",gt.length,")"]})]}),g.jsx("div",{className:"sm:hidden",children:g.jsx(ti,{variant:"secondary",size:"md",onClick:lt,children:"Import"})})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("div",{className:"hidden sm:block",children:g.jsx(ti,{variant:"secondary",size:"md",onClick:lt,children:"Importieren"})}),g.jsx("input",{value:u,onChange:ve=>c(ve.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 + `})]})]}),y.length>0?g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Tag-Filter:"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.map(ve=>g.jsx(aa,{tag:ve,active:!0,onClick:F,title:ve},ve)),g.jsx(ti,{size:"sm",variant:"soft",className:"text-xs font-medium text-gray-600 hover:underline dark:text-gray-300",onClick:M,children:"Zurücksetzen"})]})]}):null]}),noBodyPadding:!0,children:[g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:"min-w-[980px]",children:g.jsx(ph,{rows:Ot,columns:bt,getRowKey:ve=>ve.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,sort:I,onSortChange:ve=>R(ve),onRowClick:ve=>{const dt=Pv(ve);dt&&window.open(dt,"_blank","noreferrer")}})})}),g.jsx(BA,{page:d,pageSize:p,totalItems:wt,onPageChange:f})]}),g.jsx(Yx,{open:K,onClose:()=>!he&&X(!1),title:"Models importieren",footer:g.jsxs(g.Fragment,{children:[g.jsx(ti,{variant:"secondary",onClick:()=>X(!1),disabled:he,children:"Abbrechen"}),g.jsx(ti,{variant:"primary",onClick:Ge,isLoading:he,disabled:!ee||he,children:"Import starten"})]}),children:g.jsxs("div",{className:"space-y-3",children:[g.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),g.jsxs("div",{className:"space-y-2",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),g.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:Q==="favorite",onChange:()=>ue("favorite"),disabled:he}),"Favoriten (★)"]}),g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:Q==="liked",onChange:()=>ue("liked"),disabled:he}),"Gefällt mir (♥)"]})]})]}),g.jsx("input",{type:"file",accept:".csv,text/csv",onChange:ve=>{const dt=ve.target.files?.[0]??null;Ee(null),le(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"}),ee?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",g.jsx("span",{className:"font-medium",children:ee.name})]}):null,Pe?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:Pe}):null,pe?g.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:pe}):null]})})]})}function Gn(...s){return s.filter(Boolean).join(" ")}const E$=new Intl.NumberFormat("de-DE");function Bv(s){return s==null||!Number.isFinite(s)?"—":E$.format(s)}function w$(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 th(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 A$(s){return s?s.split(",").map(e=>e.trim()).filter(Boolean):[]}function nu(s){return(s||"").split(/[\\/]/).pop()||""}function C$(s){return String(s||"").replaceAll("\\","/")}function k$(s){return(C$(s||"").toLowerCase().match(/\/keep\/([^/]+)\//)?.[1]||"").trim().toLowerCase()}function pT(s){return s.startsWith("HOT ")?s.slice(4):s}function D$(s){return String(s||"").startsWith("HOT ")}function L$(s,e){const t=String(s||"");return t&&t.replace(/([\\/])[^\\/]*$/,`$1${e}`)}function R$(s){return D$(s)?pT(s):`HOT ${s}`}function Xw(s){const e=nu(s||""),t=pT(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}function Fv(s){return s?String(s).replace(/[\s\S]*?<\/script>/gi,"").replace(/[\s\S]*?<\/style>/gi,"").replace(/<\/?[^>]+>/g," ").replace(/\s+/g," ").trim():""}function I$(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 mo(s){return Gn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset",s)}const Uv=s=>s?"blur-md scale-[1.03] brightness-90":"";function N$(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 O$(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 M$({open:s,modelKey:e,onClose:t,onOpenPlayer:i,cookies:n,runningJobs:r,blurPreviews:a,onToggleWatch:u,onToggleFavorite:c,onToggleLike:d,onToggleHot:f,onDelete:p}){const[y,v]=E.useState([]),[b,_]=E.useState(!1),[S,L]=E.useState(null),[I,R]=E.useState(null),[$,B]=E.useState(!1),[F,M]=E.useState(null),[G,D]=E.useState(null),[O,W]=E.useState(!1),[Y,J]=E.useState([]),[ae,se]=E.useState(!1),[K,X]=E.useState([]),[ee,le]=E.useState(!1),[pe,P]=E.useState(0),[Q,ue]=E.useState(null),[he,re]=E.useState(0),Pe=E.useCallback(async()=>{try{const te=await(await fetch("/api/models/list",{cache:"no-store"})).json().catch(()=>null);v(Array.isArray(te)?te:[])}catch{}},[]),Ee=E.useCallback(async()=>{try{const xe=await(await fetch("/api/record/done?all=1&sort=completed_desc&includeKeep=1",{cache:"no-store"})).json().catch(()=>null),Me=Array.isArray(xe)?xe:Array.isArray(xe?.items)?xe.items:[];J(Me)}catch{}},[]);function Ge(V){return{id:`model:${V}`,output:`${V}_01_01_2000__00-00-00.mp4`,status:"finished"}}const Ve=E.useCallback((V,te)=>{const xe=String(V??"").trim();xe&&ue({src:xe,alt:te})},[]);E.useEffect(()=>{s||P(0)},[s]);const[lt,_t]=E.useState(1),mt=25,Ze=N$(e),bt=E.useMemo(()=>Array.isArray(r)?r:K,[r,K]);E.useEffect(()=>{s&&_t(1)},[s,e]),E.useEffect(()=>{if(!s)return;let V=!0;return _(!0),fetch("/api/models/list",{cache:"no-store"}).then(te=>te.json()).then(te=>{V&&v(Array.isArray(te)?te:[])}).catch(()=>{V&&v([])}).finally(()=>{V&&_(!1)}),()=>{V=!1}},[s]),E.useEffect(()=>{if(!s||!Ze)return;let V=!0;return B(!0),L(null),R(null),fetch("/api/chaturbate/online",{cache:"no-store"}).then(te=>te.json()).then(te=>{if(!V)return;R({enabled:te?.enabled,fetchedAt:te?.fetchedAt,lastError:te?.lastError});const Me=(Array.isArray(te?.rooms)?te.rooms:[]).find(ut=>String(ut?.username??"").trim().toLowerCase()===Ze)??null;L(Me)}).catch(()=>{V&&(R({enabled:void 0,fetchedAt:void 0,lastError:"Fetch fehlgeschlagen"}),L(null))}).finally(()=>{V&&B(!1)}),()=>{V=!1}},[s,Ze]),E.useEffect(()=>{if(!s||!Ze)return;let V=!0;W(!0),M(null),D(null);const te=O$(n),xe=`/api/chaturbate/biocontext?model=${encodeURIComponent(Ze)}${pe>0?"&refresh=1":""}`;return fetch(xe,{cache:"no-store",headers:te?{"X-Chaturbate-Cookie":te}:void 0}).then(async Me=>{if(!Me.ok){const ut=await Me.text().catch(()=>"");throw new Error(ut||`HTTP ${Me.status}`)}return Me.json()}).then(Me=>{V&&(D({enabled:Me?.enabled,fetchedAt:Me?.fetchedAt,lastError:Me?.lastError}),M(Me?.bio??null))}).catch(Me=>{V&&(D({enabled:void 0,fetchedAt:void 0,lastError:Me?.message||"Fetch fehlgeschlagen"}),M(null))}).finally(()=>{V&&W(!1)}),()=>{V=!1}},[s,Ze,pe,n]),E.useEffect(()=>{if(!s||!Ze)return;let V=!0;se(!0);const te=`/api/record/done?model=${encodeURIComponent(Ze)}&page=${lt}&pageSize=${mt}&sort=completed_desc&includeKeep=1&withCount=1`;return fetch(te,{cache:"no-store"}).then(xe=>xe.json()).then(xe=>{if(!V)return;const Me=Array.isArray(xe?.items)?xe.items:[],ut=Number(xe?.count??Me.length);J(Me),re(Number.isFinite(ut)?ut:Me.length)}).catch(()=>{V&&(J([]),re(0))}).finally(()=>{V&&se(!1)}),()=>{V=!1}},[s,Ze,lt]),E.useEffect(()=>{if(!s||Array.isArray(r))return;let V=!0;return le(!0),fetch("/api/record/jobs",{cache:"no-store"}).then(te=>te.json()).then(te=>{V&&X(Array.isArray(te)?te:[])}).catch(()=>{V&&X([])}).finally(()=>{V&&le(!1)}),()=>{V=!1}},[s,r]);const gt=E.useMemo(()=>Ze?y.find(V=>(V.modelKey||"").toLowerCase()===Ze)??null:null,[y,Ze]),at=E.useMemo(()=>Ze?Y.filter(V=>{const te=V.output||"",xe=k$(te);if(xe)return xe===Ze;const Me=Xw(te);return Me!=="—"&&Me.trim().toLowerCase()===Ze}):[],[Y,Ze]),wt=E.useMemo(()=>Math.max(1,Math.ceil(he/mt)),[he]),Et=E.useMemo(()=>{const V=(lt-1)*mt;return at.slice(V,V+mt)},[at,lt]),Ot=E.useMemo(()=>Ze?bt.filter(V=>{const te=Xw(V.output);return te!=="—"&&te.trim().toLowerCase()===Ze}):[],[bt,Ze]),ot=E.useMemo(()=>{const V=A$(gt?.tags),te=Array.isArray(S?.tags)?S.tags:[],xe=new Map;for(const Me of[...V,...te]){const ut=String(Me).trim().toLowerCase();ut&&(xe.has(ut)||xe.set(ut,String(Me).trim()))}return Array.from(xe.values()).sort((Me,ut)=>Me.localeCompare(ut,"de"))},[gt?.tags,S?.tags]),ht=S?.display_name||gt?.modelKey||Ze||"Model",ve=S?.image_url_360x270||S?.image_url||"",dt=S?.image_url||ve,qe=S?.chat_room_url_revshare||S?.chat_room_url||"",st=(S?.current_show||"").trim().toLowerCase(),ft=st?st==="public"?"Public":st==="private"?"Private":st:"",yt=(F?.location||"").trim(),nt=F?.follower_count,jt=F?.display_age,qt=(F?.room_status||"").trim(),Yt=F?.last_broadcast?th(F.last_broadcast):"—",Ut=Fv(F?.about_me),Ni=Fv(F?.wish_list),rt=Array.isArray(F?.social_medias)?F.social_medias:[],Dt=Array.isArray(F?.photo_sets)?F.photo_sets:[],ii=Array.isArray(F?.interested_in)?F.interested_in:[],ci=b||ae||ee||$||O,mi=({icon:V,label:te,value:xe})=>g.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:[g.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[V,te]}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold text-gray-900 dark:text-white",children:xe})]}),Ht=E.useCallback(async V=>{const te=V.output||"",xe=nu(te);if(!xe){await f?.(V);return}const Me=R$(xe);J(ut=>ut.map(Pt=>nu(Pt.output||"")!==xe?Pt:{...Pt,output:L$(Pt.output||"",Me)})),await f?.(V),Ee()},[f,Ee]),Oi=E.useCallback(async V=>{const te=V.output||"",xe=nu(te);xe&&J(Me=>Me.filter(ut=>nu(ut.output||"")!==xe)),await p?.(V),Ee()},[p,Ee]),Ki=E.useCallback(async()=>{Ze&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===Ze?{...te,favorite:!te.favorite}:te)),await c?.(Ge(Ze)),Pe())},[Ze,c,Pe]),Lt=E.useCallback(async()=>{Ze&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===Ze?{...te,liked:te.liked!==!0}:te)),await d?.(Ge(Ze)),Pe())},[Ze,d,Pe]),z=E.useCallback(async()=>{Ze&&(v(V=>V.map(te=>(te.modelKey||"").toLowerCase()===Ze?{...te,watching:!te.watching}:te)),await u?.(Ge(Ze)),Pe())},[Ze,u,Pe]);return g.jsxs(Yx,{open:s,onClose:t,title:ht,width:"max-w-6xl",footer:g.jsx(ti,{variant:"secondary",onClick:t,children:"Schließen"}),children:[g.jsxs("div",{className:"space-y-6",children:[g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:Ze?g.jsxs("span",{children:["Key: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Ze}),I?.fetchedAt?g.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Online-Stand: ",th(I.fetchedAt)]}):null,G?.fetchedAt?g.jsxs("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:["· Bio-Stand: ",th(G.fetchedAt)]}):null]}):"—"}),g.jsx("div",{className:"flex items-center gap-2",children:qe?g.jsxs("a",{href:qe,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:[g.jsx(Ey,{className:"size-4"}),"Room öffnen"]}):null})]}),g.jsxs("div",{className:"grid gap-5 lg:grid-cols-[320px_1fr]",children:[g.jsx("div",{className:"space-y-4",children:g.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:[g.jsxs("div",{className:"relative",children:[ve?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ve(dt,ht),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:ve,alt:ht,className:Gn("h-52 w-full object-cover transition",Uv(a))})}):g.jsx("div",{className:"h-52 w-full bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),g.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"}),g.jsxs("div",{className:"absolute left-3 top-3 flex flex-wrap items-center gap-2",children:[ft?g.jsx("span",{className:mo("bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20"),children:ft}):null,qt?g.jsx("span",{className:mo(qt.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:qt}):null,S?.is_hd?g.jsx("span",{className:mo("bg-indigo-500/10 text-indigo-900 ring-indigo-200 backdrop-blur dark:text-indigo-200 dark:ring-indigo-400/20"),children:"HD"}):null,S?.is_new?g.jsx("span",{className:mo("bg-amber-500/10 text-amber-900 ring-amber-200 backdrop-blur dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),g.jsxs("div",{className:"absolute bottom-3 left-3 right-3",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white drop-shadow",children:S?.display_name||S?.username||gt?.modelKey||Ze||"—"}),g.jsx("div",{className:"truncate text-xs text-white/85 drop-shadow",children:S?.username?`@${S.username}`:gt?.modelKey?`@${gt.modelKey}`:""})]}),g.jsxs("div",{className:"absolute bottom-3 right-3 flex items-center gap-2",children:[g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),z()},className:Gn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.watching?"bg-sky-500/25 ring-sky-200/30":"bg-black/20 ring-white/15"),title:gt?.watching?"Watch entfernen":"Auf Watch setzen","aria-pressed":!!gt?.watching,"aria-label":gt?.watching?"Watch entfernen":"Auf Watch setzen",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(Jv,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Lc,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-200")})]})}),g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),Ki()},className:Gn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.favorite?"bg-amber-500/25 ring-amber-200/30":"bg-black/20 ring-white/15"),title:gt?.favorite?"Favorit entfernen":"Als Favorit markieren","aria-pressed":!!gt?.favorite,"aria-label":gt?.favorite?"Favorit entfernen":"Als Favorit markieren",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(ex,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Ah,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-200")})]})}),g.jsx("button",{type:"button",onClick:V=>{V.preventDefault(),V.stopPropagation(),Lt()},className:Gn("inline-flex items-center justify-center rounded-full p-2 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",gt?.liked?"bg-rose-500/25 ring-rose-200/30":"bg-black/20 ring-white/15"),title:gt?.liked?"Like entfernen":"Liken","aria-pressed":gt?.liked===!0,"aria-label":gt?.liked?"Like entfernen":"Liken",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(ap,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Rc,{className:Gn("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",gt?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-200")})]})})]})]}),g.jsxs("div",{className:"p-4",children:[g.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[g.jsx(mi,{icon:g.jsx(nM,{className:"size-4"}),label:"Viewer",value:Bv(S?.num_users)}),g.jsx(mi,{icon:g.jsx(VS,{className:"size-4"}),label:"Follower",value:Bv(S?.num_followers??nt)})]}),g.jsxs("dl",{className:"mt-4 grid gap-2 text-xs",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(zO,{className:"size-4"}),"Location"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:S?.location||yt||"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(jO,{className:"size-4"}),"Sprache"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:S?.spoken_languages||"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx($S,{className:"size-4"}),"Online"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:Yw(S?.seconds_online)})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(ap,{className:"size-4"}),"Alter"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:jt!=null?String(jt):S?.age!=null?String(S.age):"—"})]}),g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx($S,{className:"size-4"}),"Last broadcast"]}),g.jsx("dd",{className:"truncate font-medium text-gray-900 dark:text-white",children:Yt})]})]}),I?.enabled===!1?g.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."}):I?.lastError?g.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: ",I.lastError]}):null,G?.enabled===!1?g.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."}):G?.lastError?g.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: ",G.lastError]}):null]})]})}),g.jsxs("div",{className:"space-y-4",children:[g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Room Subject"}),ci?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:S?.room_subject?g.jsx("p",{className:"line-clamp-4 whitespace-pre-wrap break-words",children:S.room_subject}):g.jsx("p",{className:"text-gray-600 dark:text-gray-300",children:"Keine Subject-Info vorhanden."})})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Bio"}),g.jsxs("div",{className:"flex items-center gap-2",children:[O?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null,g.jsx(ti,{variant:"secondary",className:"h-7 px-2 text-xs",disabled:O||!e,onClick:()=>P(V=>V+1),title:"BioContext neu abrufen",children:"Aktualisieren"})]})]}),g.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[g.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(PO,{className:"size-4"}),"Über mich"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Ut?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Ut}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]}),g.jsxs("div",{className:"rounded-xl border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(VS,{className:"size-4"}),"Wishlist"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Ni?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Ni}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]})]}),g.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Real name:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:F?.real_name?Fv(F.real_name):"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Body type:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:F?.body_type||"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Smoke/Drink:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:F?.smoke_drink||"—"})]}),g.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:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Sex:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:F?.sex||"—"})]})]}),ii.length?g.jsxs("div",{className:"mt-3",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Interested in"}),g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ii.map(V=>g.jsx("span",{className:mo("bg-sky-500/10 text-sky-900 ring-sky-200 dark:text-sky-200 dark:ring-sky-400/20"),children:V},V))})]}):null]}),g.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:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tags"}),ot.length?g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ot.map(V=>g.jsx(aa,{tag:V},V))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Tags vorhanden."})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Socials"}),rt.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[rt.length," Links"]}):null]}),rt.length?g.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:rt.map(V=>{const te=I$(V.link);return g.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",className:Gn("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:V.title_name,children:[g.jsx("div",{className:"flex size-9 items-center justify-center rounded-lg bg-black/5 dark:bg-white/5",children:V.image_url?g.jsx("img",{src:V.image_url,alt:"",className:"size-5"}):g.jsx(HO,{className:"size-5"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:V.title_name}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:V.label_text?V.label_text:V.tokens!=null?`${V.tokens} token(s)`:"Link"})]}),g.jsx(Ey,{className:"ml-auto size-4 text-gray-400 transition group-hover:text-indigo-500 dark:text-gray-500 dark:group-hover:text-indigo-400"})]},V.id)})}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Social-Medias vorhanden."})]}),g.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:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Photo sets"}),Dt.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[Dt.length," Sets"]}):null]}),Dt.length?g.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:Dt.slice(0,6).map(V=>g.jsxs("div",{className:"overflow-hidden rounded-xl border border-gray-200/70 bg-white/60 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"relative",children:[V.cover_url?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Ve(V.cover_url,V.name),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:V.cover_url,alt:V.name,className:Gn("h-28 w-full object-cover transition",Uv(a))})}):g.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-black/5 dark:bg-white/5",children:g.jsx(KO,{className:"size-6 text-gray-500"})}),g.jsxs("div",{className:"absolute left-2 top-2 flex flex-wrap gap-2",children:[V.is_video?g.jsx("span",{className:mo("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"Video"}):g.jsx("span",{className:mo("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:"Photos"}),V.fan_club_only?g.jsx("span",{className:mo("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"FanClub"}):null]})]}),g.jsxs("div",{className:"p-3",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:V.name}),g.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:["Tokens: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Bv(V.tokens)}),V.user_can_access===!0?g.jsx("span",{className:"ml-2",children:"· Zugriff: ✅"}):null]})]})]},V.id))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Photo-Sets vorhanden."})]})]})]}),g.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:[g.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Inkl. Dateien aus ",g.jsx("span",{className:"font-medium",children:"/done/keep/"})]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx(ti,{size:"sm",variant:"secondary",disabled:ae||lt<=1,onClick:()=>_t(V=>Math.max(1,V-1)),children:"Zurück"}),g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Seite ",lt," / ",wt]}),g.jsx(ti,{size:"sm",variant:"secondary",disabled:ae||lt>=wt,onClick:()=>_t(V=>Math.min(wt,V+1)),children:"Weiter"})]})]}),g.jsx("div",{className:"mt-3",children:ae?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade Downloads…"}):at.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads für dieses Model gefunden."}):g.jsx("div",{className:"grid gap-2",children:Et.map(V=>{const te=nu(V.output||""),xe=te.startsWith("HOT "),Me=V.endedAt?th(V.endedAt):"—";return g.jsxs("div",{role:i?"button":void 0,tabIndex:i?0:void 0,className:Gn("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?.(V),onKeyDown:ut=>{i&&(ut.key==="Enter"||ut.key===" ")&&i(V)},children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[g.jsx("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white",children:pT(te)||"—"}),xe?g.jsx("span",{className:mo("shrink-0 bg-orange-500/10 text-orange-900 ring-orange-200 dark:text-orange-200 dark:ring-orange-400/20"),children:"HOT"}):null]}),g.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:[g.jsxs("span",{children:["Datum: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Me})]}),g.jsxs("span",{children:["Dauer:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:Yw(V.durationSeconds)})]}),g.jsxs("span",{children:["Größe:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:w$(V.sizeBytes)})]})]})]}),g.jsx("div",{className:"shrink-0 flex items-center gap-2",children:g.jsx("span",{onClick:ut=>ut.stopPropagation(),onMouseDown:ut=>ut.stopPropagation(),onKeyDown:ut=>ut.stopPropagation(),children:g.jsx(Ua,{job:V,variant:"table",isHot:xe,isFavorite:!!gt?.favorite,isLiked:gt?.liked===!0,isWatching:!!gt?.watching,onToggleHot:Ht,onDelete:Oi,order:["hot","delete"],className:"flex items-center"})})})]},`${V.id}-${te}`)})})})]}),g.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:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Laufende Jobs"}),g.jsx("div",{className:"mt-2",children:ee?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade…"}):Ot.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Jobs."}):g.jsx("div",{className:"grid gap-2",children:Ot.map(V=>g.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:g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"break-words line-clamp-2 font-medium text-gray-900 dark:text-white",children:nu(V.output||"")}),g.jsxs("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:["Start:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:th(V.startedAt)})]})]}),i?g.jsx(ti,{size:"sm",variant:"secondary",className:"shrink-0",onClick:()=>i(V),children:"Öffnen"}):null]})},V.id))})})]})]}),g.jsx(Yx,{open:!!Q,onClose:()=>ue(null),title:Q?.alt||"Bild",width:"max-w-4xl",footer:g.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Q?.src?g.jsxs("a",{href:Q.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:[g.jsx(Ey,{className:"size-4"}),"In neuem Tab"]}):null,g.jsx(ti,{variant:"secondary",onClick:()=>ue(null),children:"Schließen"})]}),children:g.jsx("div",{className:"grid place-items-center",children:Q?.src?g.jsx("img",{src:Q.src,alt:Q.alt||"",className:Gn("max-h-[80vh] w-auto max-w-full rounded-xl object-contain",Uv(a))}):null})})]})}const jm=s=>Math.max(0,Math.min(1,s));function $m(s){return s==="good"?"bg-emerald-500":s==="warn"?"bg-amber-500":"bg-red-500"}function P$(s){return s==null?"–":`${Math.round(s)}ms`}function Qw(s){return s==null?"–":`${Math.round(s)}%`}function jv(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 B$(s=1e3){const[e,t]=zt.useState(null);return zt.useEffect(()=>{let i=0,n=performance.now(),r=0,a=!0,u=!1;const c=y=>{if(!a||!u)return;r+=1;const v=y-n;if(v>=s){const b=Math.round(r*1e3/v);t(b),r=0,n=y}i=requestAnimationFrame(c)},d=()=>{a&&(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),()=>{a=!1,document.removeEventListener("visibilitychange",p),f()}},[s]),e}function Zw({mode:s="inline",className:e,pollMs:t=3e3}){const i=B$(1e3),[n,r]=zt.useState(null),[a,u]=zt.useState(null),[c,d]=zt.useState(null),[f,p]=zt.useState(null),[y,v]=zt.useState(null),b=5*1024*1024*1024,_=8*1024*1024*1024,S=zt.useRef(!1);zt.useEffect(()=>{const J=`/api/perf/stream?ms=${encodeURIComponent(String(t))}`,ae=rR(J,"perf",se=>{const K=typeof se?.cpuPercent=="number"?se.cpuPercent:null,X=typeof se?.diskFreeBytes=="number"?se.diskFreeBytes:null,ee=typeof se?.diskTotalBytes=="number"?se.diskTotalBytes:null,le=typeof se?.diskUsedPercent=="number"?se.diskUsedPercent:null;u(K),d(X),p(ee),v(le);const pe=typeof se?.serverMs=="number"?se.serverMs:null;r(pe!=null?Math.max(0,Date.now()-pe):null)});return()=>ae()},[t]);const L=n==null?"bad":n<=120?"good":n<=300?"warn":"bad",I=i==null?"bad":i>=55?"good":i>=30?"warn":"bad",R=a==null?"bad":a<=60?"good":a<=85?"warn":"bad",$=jm((n??999)/500),B=jm((i??0)/60),F=jm((a??0)/100),M=c!=null&&f!=null&&f>0?c/f:null,G=y??(M!=null?(1-M)*100:null),D=jm((G??0)/100);c==null?S.current=!1:S.current?c>=_&&(S.current=!1):c<=b&&(S.current=!0);const O=c==null||S.current||M==null?"bad":M>=.15?"good":M>=.07?"warn":"bad",W=c==null?"Disk: –":`Free: ${jv(c)} / Total: ${jv(f)} · Used: ${Qw(G)}`,Y=s==="floating"?"fixed bottom-4 right-4 z-[80]":"flex items-center";return g.jsx("div",{className:`${Y} ${e??""}`,children:g.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:[g.jsxs("div",{className:"flex items-center gap-2",title:W,children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Disk"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${$m(O)}`,style:{width:`${Math.round(D*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-11 tabular-nums text-gray-900 dark:text-gray-100",children:jv(c)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Ping"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${$m(L)}`,style:{width:`${Math.round($*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:P$(n)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"FPS"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${$m(I)}`,style:{width:`${Math.round(B*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-8 tabular-nums text-gray-900 dark:text-gray-100",children:i??"–"})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"CPU"}),g.jsx("div",{className:"h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${$m(R)}`,style:{width:`${Math.round(F*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:Qw(a)})]})]})})}function F$(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=>{a||(u(),t=window.setTimeout(()=>{f()},p))},f=async()=>{if(!a)try{const p=(s.getModels?.()??[]).map(W=>String(W||"").trim()).filter(Boolean),v=(s.getShow?.()??[]).map(W=>String(W||"").trim()).filter(Boolean).slice().sort(),b=p.slice().sort(),_=b.length===0&&!!s.fetchAllWhenNoModels;if(b.length===0&&!_){c();const W={enabled:r?.enabled??!1,rooms:[]};r=W,s.onData(W);const Y=document.hidden?Math.max(15e3,e):e;d(Y);return}const S=_?[]:b,L=`${v.join(",")}|${_?"__ALL__":S.join(",")}`,I=L;n=L,c();const R=new AbortController;i=R;const B=_?[[]]:F$(S,350);let F=[],M=!1,G=0,D=!1;for(const W of B){if(R.signal.aborted||I!==n||a)return;const Y=await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:W,show:v,refresh:!1}),signal:R.signal,cache:"no-store"});if(!Y.ok)continue;D=!0;const J=await Y.json();M=M||!!J?.enabled,F.push(...Array.isArray(J?.rooms)?J.rooms:[]);const ae=Number(J?.total??0);Number.isFinite(ae)&&ae>G&&(G=ae)}if(!D){const W=document.hidden?Math.max(15e3,e):e;d(W);return}const O={enabled:M,rooms:U$(F),total:G};if(R.signal.aborted||I!==n||a)return;r=O,s.onData(O)}catch(p){if(p?.name==="AbortError")return;s.onError?.(p)}finally{const p=document.hidden?Math.max(15e3,e):e;d(p)}};return f(),()=>{a=!0,u(),c()}}async function $v(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 eA(s,e,t,i){const n=`/api/generated/cover?category=${encodeURIComponent(s)}`,r=e?`&v=${e}`:"",a=t?"&refresh=1":"",u=i&&i.trim()?`&model=${encodeURIComponent(i.trim())}`:"";return`${n}${r}${a}${u}`}function tA(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(t=>t.trim()).filter(Boolean);return Array.from(new Set(e))}function fR(s){return String(s||"").replaceAll("\\","/").split("/").pop()||""}function mR(s){return s.toUpperCase().startsWith("HOT ")?s.slice(4).trim():s}function j$(s){const e=mR(fR(s||""));return e?e.replace(/\.[^.]+$/,""):""}const $$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function Hv(s){const t=mR(fR(s)).replace(/\.[^.]+$/,""),i=t.match($$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n).trim():t?t.trim():null}function H$(s){const e=j$(s);return e?`/generated/meta/${encodeURIComponent(e)}/thumbs.jpg`:null}async function G$(s,e,t,i){const n=(t||"").trim(),r=`/api/generated/cover?category=${encodeURIComponent(s)}&src=${encodeURIComponent(e)}`+(n?`&model=${encodeURIComponent(n)}`:"")+"&refresh=1";await fetch(r,{method:"GET",cache:"no-store"})}function V$(){const[s,e]=E.useState([]),[t,i]=E.useState(!1),[n,r]=E.useState(null),[a,u]=E.useState(()=>Date.now()),[c,d]=E.useState({}),[f,p]=E.useState(!1),[y,v]=E.useState(null),[b,_]=E.useState({}),S=E.useRef(null),L=E.useRef({}),I=E.useCallback((M,G)=>{const D={};for(const W of Array.isArray(M)?M:[]){const Y=String(W?.modelKey??"").trim().toLowerCase();if(!Y)continue;const J=tA(W?.tags).map(ae=>ae.toLowerCase());J.length&&(D[Y]=J)}const O={};for(const W of Array.isArray(G)?G:[]){const Y=String(W?.output??"");if(!Y)continue;const J=(Hv(Y)||"").trim().toLowerCase();if(!J)continue;const ae=D[J];if(!(!ae||ae.length===0))for(const se of ae)se&&(O[se]||(O[se]=[]),O[se].push(Y))}for(const[W,Y]of Object.entries(O))O[W]=Array.from(new Set(Y));L.current=O},[]),R=E.useCallback(M=>{const G=String(M||"").trim();if(G){try{localStorage.setItem("finishedDownloads_pendingTags",JSON.stringify([G]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"finished"}})),window.dispatchEvent(new CustomEvent("finished-downloads:tag-filter",{detail:{tags:[G],mode:"replace"}}))}},[]),$=E.useCallback(M=>{const G=String(M||"").trim();if(G){try{localStorage.setItem("models_pendingTags",JSON.stringify([G]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"models"}})),window.dispatchEvent(new CustomEvent("models:set-tag-filter",{detail:{tags:[G]}}))}},[]),B=E.useCallback(async()=>{S.current?.abort();const M=new AbortController;S.current=M,i(!0),r(null);try{const[G,D]=await Promise.all([$v("/api/models/list",{cache:"no-store",signal:M.signal}),$v("/api/record/done?page=1&pageSize=2000&sort=completed_desc",{cache:"no-store",signal:M.signal})]),O=Array.isArray(D?.items)?D.items:Array.isArray(D)?D:[];I(Array.isArray(G)?G:[],O);const W=new Map;for(const K of Array.isArray(G)?G:[])for(const X of tA(K?.tags)){const ee=X.toLowerCase();W.set(ee,(W.get(ee)??0)+1)}const Y=L.current||{},J=Array.from(W.entries()).map(([K,X])=>({tag:K,modelsCount:X,downloadsCount:(Y[K]||[]).length})).sort((K,X)=>K.tag.localeCompare(X.tag,void 0,{sensitivity:"base"}));let ae=new Map;try{const K=await $v("/api/generated/coverinfo/list",{cache:"no-store",signal:M.signal});for(const X of Array.isArray(K)?K:[]){const ee=String(X?.category??"").trim().toLowerCase();ee&&ae.set(ee,X)}}catch{}const se={};for(const K of J){const ee=(Y[K.tag]||[])[0]||"";let le=ee?Hv(ee):null;if(!le){const pe=ae.get(K.tag);pe?.hasCover&&pe.model?.trim()&&(le=pe.model.trim())}le&&(se[K.tag]=le)}_(se),e(J),u(Date.now())}catch(G){if(G?.name==="AbortError")return;r(G?.message??String(G)),e([]),L.current={},_({})}finally{S.current===M&&(S.current=null,i(!1))}},[I]);E.useEffect(()=>(B(),()=>{S.current?.abort()}),[B]);const F=E.useCallback(async()=>{if(!f){p(!0),r(null),v({done:0,total:s.length});try{const M=L.current||{},G=await Promise.all(s.map(async O=>{try{const W=M[O.tag]||[],Y=W.length?W[Math.floor(Math.random()*W.length)]:"",J=Y?H$(Y):null;if(J){const ee=Y?Hv(Y):null;return await G$(O.tag,J,ee,!0),_(le=>{const pe={...le};return ee?.trim()?pe[O.tag]=ee.trim():delete pe[O.tag],pe}),{tag:O.tag,ok:!0,status:200,text:""}}const ae=b[O.tag]??"",se=await fetch(eA(O.tag,Date.now(),!0,ae),{method:"GET",cache:"no-store"}),K=se.ok?"":await se.text().catch(()=>""),X=se.ok||se.status===404;return{tag:O.tag,ok:X,status:se.status,text:K}}catch(W){return{tag:O.tag,ok:!1,status:0,text:W?.message??String(W)}}finally{v(W=>W&&{...W,done:Math.min(W.total,W.done+1)})}})),D=G.filter(O=>!O.ok&&O.status!==404);if(D.length){console.warn("Cover renew failed:",D.slice(0,20));const O=D.slice(0,8).map(W=>`${W.tag} (${W.status||"ERR"})`).join(", ");r(`Covers fehlgeschlagen: ${D.length}/${G.length} — z.B.: ${O}`)}else r(null)}finally{u(Date.now()),p(!1),setTimeout(()=>v(null),400)}}},[s,f]);return g.jsxs(ja,{header:g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Kategorien ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",s.length,")"]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[y?g.jsxs("div",{className:"hidden sm:flex items-center gap-2 mr-2",children:[g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300 tabular-nums",children:["Covers: ",y.done,"/",y.total]}),g.jsx("div",{className:"h-2 w-28 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:"h-full bg-indigo-500",style:{width:y.total>0?`${Math.round(y.done/y.total*100)}%`:"0%"}})})]}):null,g.jsx(ti,{variant:"secondary",size:"md",onClick:F,disabled:t||f,children:"Cover erneuern"}),g.jsx(ti,{variant:"secondary",size:"md",onClick:B,disabled:t||f,children:"Aktualisieren"})]})]}),grayBody:!0,children:[n?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null,s.length===0&&!t?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Kategorien/Tags gefunden."}):null,g.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:s.map(M=>{const G=b[M.tag]??null,D=eA(M.tag,a,!1),O=c[M.tag]==="ok",W=c[M.tag]==="error";return g.jsxs("button",{type:"button",onClick:()=>R(M.tag),className:xi("group text-left rounded-2xl overflow-hidden transition","bg-white/70 dark:bg-white/[0.06]","border border-gray-200/70 dark:border-white/10","shadow-sm hover:shadow-md","hover:-translate-y-[1px]","hover:bg-white dark:hover:bg-white/[0.09]","focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-gray-950"),title:"In FinishedDownloads öffnen (Tag-Filter setzen)",children:[g.jsx("div",{className:"relative w-full overflow-hidden aspect-[16/9] bg-gray-100/70 dark:bg-white/5",children:W?g.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2",children:[g.jsx("div",{className:"absolute inset-0 opacity-70",style:{background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,0.25), transparent 55%),radial-gradient(circle at 70% 80%, rgba(14,165,233,0.18), transparent 55%)"}}),g.jsxs("div",{className:"relative z-10 rounded-xl bg-white/80 dark:bg-black/30 px-3 py-2.5 shadow-sm ring-1 ring-black/5 dark:ring-white/10 backdrop-blur-md",children:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Cover nicht verfügbar"}),G?g.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-700 dark:text-gray-300",children:["Model: ",g.jsx("span",{className:"font-semibold",children:G})]}):null,g.jsx("div",{className:"mt-1 flex justify-center",children:g.jsx("span",{className:`text-[11px] inline-flex items-center rounded-full bg-indigo-50 px-2 py-1 font-semibold text-indigo-700 ring-1 ring-indigo-100 hover:bg-indigo-100\r + dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20 dark:hover:bg-indigo-500/20`,onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),d(J=>{const ae={...J};return delete ae[M.tag],ae}),u(Date.now())},children:"Retry"})})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 z-[1] pointer-events-none",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.10), rgba(255,255,255,0) 35%),linear-gradient(to top, rgba(0,0,0,0.35), rgba(0,0,0,0) 45%)"}}),g.jsx("img",{src:D,alt:"","aria-hidden":"true",className:"absolute inset-0 z-0 h-full w-full object-cover blur-xl scale-110 opacity-60",loading:"lazy"}),g.jsx("img",{src:D,alt:M.tag,className:"absolute inset-0 z-0 h-full w-full object-contain",loading:"lazy",onLoad:()=>d(Y=>({...Y,[M.tag]:"ok"})),onError:()=>d(Y=>({...Y,[M.tag]:"error"}))}),O&&G?g.jsx("div",{className:"absolute left-3 bottom-3 z-10 max-w-[calc(100%-24px)]",children:g.jsx("div",{className:xi("truncate rounded-full px-2.5 py-1 text-[11px] font-semibold","bg-black/40 text-white backdrop-blur-md","ring-1 ring-white/15"),children:G})}):null]})}),g.jsx("div",{className:"px-4 py-3.5",children:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"font-semibold text-gray-900 dark:text-white truncate tracking-tight",children:M.tag}),g.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[g.jsxs("span",{role:"button",tabIndex:0,className:xi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap","overflow-hidden","bg-indigo-50 text-indigo-700 ring-1 ring-indigo-100","dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20","cursor-pointer"),title:"FinishedDownloads nach diesem Tag filtern",onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),R(M.tag)},onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),Y.stopPropagation(),R(M.tag))},children:[g.jsx("span",{className:"shrink-0",children:M.downloadsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Downloads"})]}),g.jsxs("span",{role:"button",tabIndex:0,className:xi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap overflow-hidden","bg-gray-50 text-gray-700 ring-1 ring-gray-200","dark:bg-white/5 dark:text-gray-200 dark:ring-white/10","cursor-pointer"),title:"Models nach diesem Tag filtern",onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),$(M.tag)},onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),Y.stopPropagation(),$(M.tag))},children:[g.jsx("span",{className:"shrink-0",children:M.modelsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Models"})]})]})]}),g.jsx("span",{"aria-hidden":"true",className:xi("shrink-0 mt-0.5 text-gray-400 dark:text-gray-500","transition-transform group-hover:translate-x-[1px]"),children:"→"})]})})]},M.tag)})})]})}async function ih(s,e){const t=await fetch(s,{credentials:"include",...e});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function z$(){try{const e=new URL(window.location.href).searchParams.get("next")||"/";return!e.startsWith("/")||e.startsWith("/login")?"/":e}catch{return"/"}}function q$({onLoggedIn:s}){const e=E.useMemo(()=>z$(),[]),[t,i]=E.useState(""),[n,r]=E.useState(""),[a,u]=E.useState(""),[c,d]=E.useState(!1),[f,p]=E.useState(null),[y,v]=E.useState("login"),[b,_]=E.useState(null),[S,L]=E.useState(null),[I,R]=E.useState(null);E.useEffect(()=>{let G=!1;return(async()=>{try{const O=await ih("/api/auth/me",{cache:"no-store"});if(G)return;if(O?.authenticated){O?.totpConfigured?window.location.assign(e||"/"):(v("setup"),F());return}if(O?.pending2fa){v("verify");return}v("login")}catch{}})(),()=>{G=!0}},[e]);const $=async()=>{d(!0),p(null);try{if((await ih("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})}))?.totpRequired){v("verify");return}const D=await ih("/api/auth/me",{cache:"no-store"});if(D?.authenticated&&!D?.totpConfigured){v("setup"),await F();return}s&&await s(),window.location.assign(e||"/")}catch(G){p(G?.message??String(G))}finally{d(!1)}},B=async()=>{d(!0),p(null);try{await ih("/api/auth/2fa/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:a})}),s&&await s(),window.location.assign(e||"/")}catch(G){p(G?.message??String(G))}finally{d(!1)}},F=async()=>{p(null),R(null);try{const G=await ih("/api/auth/2fa/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),D=(G?.otpauth??"").trim();if(!D)throw new Error("2FA Setup fehlgeschlagen (keine otpauth URL).");_(D),L((G?.secret??"").trim()||null),R("Scan den QR-Code in deiner Authenticator-App und bestätige danach mit dem 6-stelligen Code.")}catch(G){p(G?.message??String(G))}},M=G=>{G.key==="Enter"&&(G.preventDefault(),!c&&(y==="verify"||y==="setup"?B():$()))};return g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsx("div",{className:"relative grid min-h-[100dvh] place-items-center px-4",children:g.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-gray-200/70 bg-white/80 p-6 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Recorder Login"}),g.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Bitte melde dich an, um fortzufahren."})]}),g.jsxs("div",{className:"mt-5 space-y-3",children:[y==="login"?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Username"}),g.jsx("input",{value:t,onChange:G=>i(G.target.value),onKeyDown:M,autoComplete:"username",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",placeholder:"admin",disabled:c})]}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Passwort"}),g.jsx("input",{type:"password",value:n,onChange:G=>r(G.target.value),onKeyDown:M,autoComplete:"current-password",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",placeholder:"••••••••••",disabled:c})]}),g.jsx(ti,{variant:"primary",className:"w-full rounded-lg",disabled:c||!t.trim()||!n,onClick:()=>{$()},children:c?"Login…":"Login"})]}):y==="verify"?g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:"2FA ist aktiv – bitte gib den Code aus deiner Authenticator-App ein."}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{htmlFor:"totp",className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"2FA Code"}),g.jsx("input",{id:"id_code",name:"code","aria-label":"totp",type:"text",value:a,onChange:G=>u(G.target.value),onKeyDown:M,autoComplete:"one-time-code",required:!0,inputMode:"numeric",pattern:"[0-9]*",maxLength:6,enterKeyHint:"done",autoCapitalize:"none",autoCorrect:"off",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",placeholder:"123456",disabled:c})]}),g.jsxs("div",{className:"flex gap-2",children:[g.jsx(ti,{variant:"secondary",className:"flex-1 rounded-lg",disabled:c,onClick:()=>{_(null),L(null),R(null)},children:"Zurück"}),g.jsx(ti,{variant:"primary",className:"flex-1 rounded-lg",disabled:c||a.trim().length<6,onClick:()=>{B()},children:c?"Prüfe…":"Bestätigen"})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2 text-sm text-indigo-900 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-200",children:"2FA ist noch nicht eingerichtet – bitte richte es jetzt ein (empfohlen)."}),g.jsxs("div",{className:"space-y-2 text-sm text-gray-700 dark:text-gray-200",children:[g.jsx("div",{children:"1) Öffne deine Authenticator-App und füge einen neuen Account hinzu."}),g.jsx("div",{children:"2) Scanne den QR-Code oder verwende den Secret-Key."})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white/70 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"QR / Setup"}),b?g.jsx("div",{className:"mt-2 flex items-center justify-center",children:g.jsx("img",{alt:"2FA QR Code",className:"h-44 w-44 rounded bg-white p-2",src:`https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(b)}`})}):g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-300",children:"QR wird geladen…"}),S?g.jsxs("div",{className:"mt-3",children:[g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Secret (manuell):"}),g.jsx("div",{className:"mt-1 select-all break-all rounded bg-gray-100 px-2 py-1 text-xs font-mono text-gray-900 dark:bg-white/10 dark:text-gray-100",children:S})]}):null,I?g.jsx("div",{className:"mt-3 text-xs text-gray-600 dark:text-gray-300",children:I}):null,g.jsx("div",{className:"mt-3",children:g.jsx(ti,{variant:"secondary",className:"w-full rounded-lg",disabled:c,onClick:()=>{F()},title:"Setup-Infos neu laden",children:b?"QR/Setup erneut laden":"QR/Setup laden"})})]}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{htmlFor:"totp",className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"2FA Code (zum Aktivieren)"}),g.jsx("input",{id:"totp-setup",name:"code","aria-label":"totp",type:"text",value:a,onChange:G=>u(G.target.value),onKeyDown:M,autoComplete:"one-time-code",required:!0,inputMode:"numeric",pattern:"[0-9]*",maxLength:6,enterKeyHint:"done",autoCapitalize:"none",autoCorrect:"off",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",placeholder:"123456",disabled:c})]}),g.jsxs("div",{className:"flex gap-2",children:[g.jsx(ti,{variant:"secondary",className:"flex-1 rounded-lg",disabled:c,onClick:()=>{s&&s(),window.location.assign(e||"/")},title:"Ohne 2FA fortfahren (nicht empfohlen)",children:"Später"}),g.jsx(ti,{variant:"primary",className:"flex-1 rounded-lg",disabled:c||a.trim().length<6,onClick:()=>{B()},children:c?"Aktiviere…":"2FA aktivieren"})]})]}),f?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:f}),g.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:()=>p(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null]})]})})]})}const Gv="record_cookies";function Hm(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 zs(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 iA={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!1,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:3e3};function go(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 eu(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g)){const i=go(t);if(i)return i}return null}function wh(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}}function pR(s){try{const e=new URL(s),t=e.hostname.replace(/^www\./i,"").toLowerCase();if(t!=="chaturbate.com"&&!t.endsWith(".chaturbate.com"))return"";const i=e.pathname.split("/").filter(Boolean);return i[0]?decodeURIComponent(i[0]).trim():""}catch{return""}}function ml(s){const e=wh(s);if(!e)return s;if(e==="chaturbate"){const i=pR(s);return i?`https://chaturbate.com/${encodeURIComponent(i)}/`:s}const t=gR(s);return t?`https://www.myfreecams.com/#${encodeURIComponent(t)}`:s}function K$(s){const e=wh(s);return e?((e==="chaturbate"?pR(s):gR(s))||"").trim().toLowerCase():""}function gR(s){try{const e=new URL(s),t=e.hostname.replace(/^www\./i,"").toLowerCase();if(t!=="myfreecams.com"&&!t.endsWith(".myfreecams.com"))return"";const i=(e.hash||"").replace(/^#\/?/,"");if(i){const a=i.split("/").filter(Boolean),u=a[a.length-1]||"";if(u)return decodeURIComponent(u).trim()}const n=e.pathname.split("/").filter(Boolean),r=n[n.length-1]||"";return r?decodeURIComponent(r).trim():""}catch{return""}}const ln=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function W$(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function Y$(s){return s.startsWith("HOT ")?s.slice(4):s}const X$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function sh(s){const t=Y$(ln(s)).replace(/\.[^.]+$/,""),i=t.match(X$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function Q$(){const[s,e]=E.useState(!1),[t,i]=E.useState(!1),n=E.useCallback(async()=>{try{const be=await zs("/api/auth/me",{cache:"no-store"});i(!!be?.authenticated)}catch{i(!1)}finally{e(!0)}},[]),r=E.useCallback(async()=>{try{await fetch("/api/auth/logout",{method:"POST",cache:"no-store"})}catch{}finally{i(!1),e(!0),gt(null),wt(!1),st("running"),yt(null),jt(!1),mt(null),F([]),G([]),Y(0),O(1),re({}),ae(0),Xt({}),ys.current={},Me.current={},ut.current=!1,Ki([]),z({}),K(0),$("")}},[]);E.useEffect(()=>{n()},[n]);const a=UA(),u=E.useRef(a),c=E.useRef(0),d=be=>{const Ce=(be||"").toLowerCase();return Ce.includes("altersverifikationsseite erhalten")||Ce.includes("verify your age")||Ce.includes("schutzseite von cloudflare erhalten")||Ce.includes("just a moment")||Ce.includes("kein room-html")},f=be=>{const Ce=!!be?.silent,Ae="Cookies fehlen oder sind abgelaufen",Ye="Der Recorder hat statt des Room-HTML eine Schutz-/Altersverifikationsseite erhalten. Bitte Cookies aktualisieren (bei Chaturbate z.B. cf_clearance + sessionId) und erneut starten.";if(!Ce){gt(`⚠️ ${Ae}. ${Ye}`),Ot(!0);return}const q=Date.now();q-c.current>15e3&&(c.current=q,u.current?.error(Ae,Ye))};E.useEffect(()=>{u.current=a},[a]);const[p,y]=E.useState(!1);E.useEffect(()=>{const be=window,Ce=typeof be.requestIdleCallback=="function"?be.requestIdleCallback(()=>y(!0),{timeout:1500}):window.setTimeout(()=>y(!0),800);return()=>{typeof be.cancelIdleCallback=="function"?be.cancelIdleCallback(Ce):window.clearTimeout(Ce)}},[]);const v=8,b="finishedDownloads_sort",[_,S]=E.useState(()=>{try{return window.localStorage.getItem(b)||"completed_desc"}catch{return"completed_desc"}});E.useEffect(()=>{try{window.localStorage.setItem(b,_)}catch{}},[_]);const[L,I]=E.useState(null),[R,$]=E.useState(""),[B,F]=E.useState([]),[M,G]=E.useState([]),[D,O]=E.useState(1),[W,Y]=E.useState(0),[J,ae]=E.useState(0),[se,K]=E.useState(0),[X,ee]=E.useState(()=>Date.now()),[le,pe]=E.useState(()=>Date.now());E.useEffect(()=>{const be=window.setInterval(()=>pe(Date.now()),1e3);return()=>window.clearInterval(be)},[]);const P=be=>(be||"").toLowerCase().trim(),Q=be=>{const Ce=Math.max(0,Math.floor(be/1e3));if(Ce<2)return"gerade eben";if(Ce<60)return`vor ${Ce} Sekunden`;const Ae=Math.floor(Ce/60);if(Ae===1)return"vor 1 Minute";if(Ae<60)return`vor ${Ae} Minuten`;const Ye=Math.floor(Ae/60);return Ye===1?"vor 1 Stunde":`vor ${Ye} Stunden`},ue=E.useMemo(()=>{const be=le-X;return`(zuletzt aktualisiert: ${Q(be)})`},[le,X]),[he,re]=E.useState({}),Pe=E.useCallback(be=>{const Ce={};for(const Ae of Array.isArray(be)?be:[]){const Ye=(Ae?.modelKey||"").trim().toLowerCase();if(!Ye)continue;const q=ke=>(ke.favorite?4:0)+(ke.liked===!0?2:0)+(ke.watching?1:0),ce=Ce[Ye];(!ce||q(Ae)>=q(ce))&&(Ce[Ye]=Ae)}return Ce},[]),Ee=E.useCallback(async()=>{try{const be=await zs("/api/models/list",{cache:"no-store"});re(Pe(Array.isArray(be)?be:[])),ee(Date.now())}catch{}},[Pe]),[Ge,Ve]=E.useState(null),lt=E.useRef(null),[_t,mt]=E.useState(null);E.useEffect(()=>{const be=Ce=>{const Ye=(Ce.detail?.modelKey??"").trim();if(!Ye)return;if(!Ye.includes(" ")&&!Ye.includes("/")&&!Ye.includes("\\")){const Be=Ye.replace(/^@/,"").trim().toLowerCase();Be&&mt(Be);return}const ce=go(Ye);if(!ce){let Be=Ye.replace(/^https?:\/\//i,"");Be.includes("/")&&(Be=Be.split("/").filter(Boolean).pop()||Be),Be.includes(":")&&(Be=Be.split(":").pop()||Be),Be=Be.trim().toLowerCase(),Be&&mt(Be);return}const ke=ml(ce),De=K$(ke);De&&mt(De)};return window.addEventListener("open-model-details",be),()=>window.removeEventListener("open-model-details",be)},[]);const Ze=E.useCallback(be=>{const Ce=Date.now(),Ae=lt.current;if(!Ae){lt.current={ts:Ce,list:[be]};return}Ae.ts=Ce;const Ye=Ae.list.findIndex(q=>q.id===be.id);Ye>=0?Ae.list[Ye]=be:Ae.list.unshift(be)},[]);E.useEffect(()=>{Ee();const be=Ce=>{const Ye=Ce?.detail??{},q=Ye?.model;if(q&&typeof q=="object"){const ce=String(q.modelKey??"").toLowerCase().trim();ce&&re(ke=>({...ke,[ce]:q}));try{Ze(q)}catch{}Ve(ke=>ke?.id===q.id?q:ke),ee(Date.now());return}if(Ye?.removed){const ce=String(Ye?.id??"").trim(),ke=String(Ye?.modelKey??"").toLowerCase().trim();ke&&re(De=>{const{[ke]:Be,...et}=De;return et}),ce&&Ve(De=>De?.id===ce?null:De),ee(Date.now());return}Ee()};return window.addEventListener("models-changed",be),()=>window.removeEventListener("models-changed",be)},[Ee,Ze]);const[bt,gt]=E.useState(null),[at,wt]=E.useState(!1),[Et,Ot]=E.useState(!1),[ot,ht]=E.useState({}),[ve,dt]=E.useState(!1),[qe,st]=E.useState("running"),[ft,yt]=E.useState(null),[nt,jt]=E.useState(!1),[qt,Yt]=E.useState(0),Ut=E.useCallback(()=>Yt(be=>be+1),[]),Ni=E.useRef(null),rt=E.useCallback(()=>{Ut(),Ni.current&&window.clearTimeout(Ni.current),Ni.current=window.setTimeout(()=>Ut(),3500)},[Ut]),[Dt,ii]=E.useState(iA),ci=E.useRef(Dt);E.useEffect(()=>{ci.current=Dt},[Dt]);const mi=!!Dt.autoAddToDownloadList,Ht=!!Dt.autoStartAddedDownloads,[Oi,Ki]=E.useState([]),[Lt,z]=E.useState({}),V=E.useRef(!1),te=E.useRef({}),xe=E.useRef([]),Me=E.useRef({}),ut=E.useRef(!1);E.useEffect(()=>{V.current=at},[at]),E.useEffect(()=>{te.current=ot},[ot]),E.useEffect(()=>{xe.current=B},[B]);const Pt=E.useRef(null),Ii=E.useRef(""),Mi=4,Fi=E.useRef([]),Ui=E.useRef(0),Wi=E.useRef(new Set),pi=E.useRef(!1),os=E.useCallback(()=>{const be=Ui.current>0;wt(be),V.current=be},[]),Yi=E.useCallback(be=>{const Ce=go(be.url);if(!Ce)return!1;const Ae=ml(Ce);return Wi.current.has(Ae)||(Wi.current.add(Ae),Fi.current.push({...be,url:Ae}),pi.current||(pi.current=!0,queueMicrotask(()=>{pi.current=!1,si()}))),!0},[]);async function zi(be,Ce){if(be=ml(be),xe.current.some(Ye=>{if(String(Ye.status||"").toLowerCase()!=="running"||Ye.endedAt)return!1;const q=go(String(Ye.sourceUrl||""));return(q?ml(q):"")===be}))return!0;try{const Ye=te.current,q=wh(be);if(!q)return Ce||gt("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;if(q==="chaturbate"&&!Se(Ye))return Ce||gt('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;const ce=Object.entries(Ye).map(([De,Be])=>`${De}=${Be}`).join("; "),ke=await zs("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:be,cookie:ce})});return ke?.id&&(Me.current[String(ke.id)]=!0),F(De=>[ke,...De]),xe.current=[ke,...xe.current],!0}catch(Ye){const q=Ye?.message??String(Ye);return d(q)?(f({silent:Ce}),!1):(Ce||gt(q),!1)}}async function si(){for(;Ui.current0;){const be=Fi.current.shift();Ui.current++,os(),(async()=>{try{if(await zi(be.url,be.silent)&&be.pendingKeyLower){const Ae=be.pendingKeyLower;z(Ye=>{const q={...Ye||{}};return delete q[Ae],Us.current=q,q})}}finally{Wi.current.delete(be.url),Ui.current=Math.max(0,Ui.current-1),os(),Fi.current.length>0&&si()}})()}}const[Gt,Xt]=E.useState({}),ys=E.useRef({}),ms=E.useRef({}),vn=E.useRef({}),Mn=E.useRef(!1),vs=E.useRef({});E.useEffect(()=>{ys.current=Gt},[Gt]);const Ti=E.useCallback(be=>{const Ce=String(be?.host??"").toLowerCase(),Ae=String(be?.input??"").toLowerCase();return Ce.includes("chaturbate")||Ae.includes("chaturbate.com")},[]),Is=E.useMemo(()=>{const be=new Set;for(const Ce of Object.values(he)){if(!Ti(Ce))continue;const Ae=P(String(Ce?.modelKey??""));Ae&&be.add(Ae)}return Array.from(be)},[he,Ti]),Ws=E.useRef(he);E.useEffect(()=>{Ws.current=he},[he]);const Us=E.useRef(Lt);E.useEffect(()=>{Us.current=Lt},[Lt]);const bs=E.useRef(Is);E.useEffect(()=>{bs.current=Is},[Is]);const Pi=E.useRef(qe);E.useEffect(()=>{Pi.current=qe},[qe]);const Ts=E.useCallback(async(be,Ce)=>{const Ae=go(be);if(!Ae)return!1;const Ye=ml(Ae),q=!!Ce?.silent;q||gt(null);const ce=wh(Ye);if(!ce)return q||gt("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;const ke=te.current;if(ce==="chaturbate"&&!Se(ke))return q||gt('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(xe.current.some(Be=>{if(String(Be.status||"").toLowerCase()!=="running"||Be.endedAt)return!1;const et=go(String(Be.sourceUrl||""));return(et?ml(et):"")===Ye}))return!0;if(ce==="chaturbate"&&ci.current.useChaturbateApi)try{const Be=await zs("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Ye})}),et=String(Be?.modelKey??"").trim().toLowerCase();if(et){if(V.current)return z(it=>({...it||{},[et]:Ye})),!0;const ct=ys.current[et],$e=String(ct?.current_show??"");if(ct&&$e&&$e!=="public")return z(it=>({...it||{},[et]:Ye})),!0}}catch{}else if(V.current)return Pt.current=Ye,!0;if(V.current)return!1;wt(!0),V.current=!0;try{const Be=Object.entries(ke).map(([ct,$e])=>`${ct}=${$e}`).join("; "),et=await zs("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:Ye,cookie:Be})});return et?.id&&(Me.current[String(et.id)]=!0),F(ct=>[et,...ct]),xe.current=[et,...xe.current],!0}catch(Be){const et=Be?.message??String(Be);return d(et)?(f({silent:q}),!1):(q||gt(et),!1)}finally{wt(!1),V.current=!1}},[]);E.useEffect(()=>{let be=!1;const Ce=async()=>{try{const q=await zs("/api/settings",{cache:"no-store"});!be&&q&&ii({...iA,...q})}catch{}},Ae=()=>{Ce()},Ye=()=>{Ce()};return window.addEventListener("recorder-settings-updated",Ae),window.addEventListener("focus",Ye),document.addEventListener("visibilitychange",Ye),Ce(),()=>{be=!0,window.removeEventListener("recorder-settings-updated",Ae),window.removeEventListener("focus",Ye),document.removeEventListener("visibilitychange",Ye)}},[]),E.useEffect(()=>{let be=!1;const Ce=async()=>{try{const Ye=await zs("/api/models/meta",{cache:"no-store"}),q=Number(Ye?.count??0);!be&&Number.isFinite(q)&&(ae(q),ee(Date.now()))}catch{}};Ce();const Ae=window.setInterval(Ce,document.hidden?6e4:3e4);return()=>{be=!0,window.clearInterval(Ae)}},[]);const xn=E.useMemo(()=>Object.entries(ot).map(([be,Ce])=>({name:be,value:Ce})),[ot]),tn=E.useCallback(be=>{lt.current=null,Ve(null),yt(be),jt(!1)},[]),sn=B.filter(be=>{const Ce=String(be?.status??"").toLowerCase();return Ce==="running"||Ce==="postwork"}),Or=E.useMemo(()=>{let be=0;for(const Ce of Object.values(he)){if(!Ce?.watching||!Ti(Ce))continue;const Ae=P(String(Ce?.modelKey??""));Ae&&Gt[Ae]&&be++}return be},[he,Gt,Ti]),{onlineFavCount:Mr,onlineLikedCount:js}=E.useMemo(()=>{let be=0,Ce=0;for(const Ae of Object.values(he)){const Ye=P(String(Ae?.modelKey??""));Ye&&Gt[Ye]&&(Ae?.favorite&&be++,Ae?.liked===!0&&Ce++)}return{onlineFavCount:be,onlineLikedCount:Ce}},[he,Gt]),bn=[{id:"running",label:"Laufende Downloads",count:sn.length},{id:"finished",label:"Abgeschlossene Downloads",count:W},{id:"models",label:"Models",count:J},{id:"categories",label:"Kategorien"},{id:"settings",label:"Einstellungen"}],Pn=E.useMemo(()=>R.trim().length>0&&!at,[R,at]);E.useEffect(()=>{let be=!1;return(async()=>{try{const Ae=await zs("/api/cookies",{cache:"no-store"}),Ye=Hm(Ae?.cookies);if(be||ht(Ye),Object.keys(Ye).length===0){const q=localStorage.getItem(Gv);if(q)try{const ce=JSON.parse(q),ke=Hm(ce);Object.keys(ke).length>0&&(be||ht(ke),await zs("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:ke})}))}catch{}}}catch{const Ae=localStorage.getItem(Gv);if(Ae)try{const Ye=JSON.parse(Ae);be||ht(Hm(Ye))}catch{}}finally{be||dt(!0)}})(),()=>{be=!0}},[]),E.useEffect(()=>{ve&&localStorage.setItem(Gv,JSON.stringify(ot))},[ot,ve]),E.useEffect(()=>{let be=!1,Ce;const Ae=async()=>{try{const q=await fetch(`/api/record/done?page=1&pageSize=1&withCount=1&sort=${encodeURIComponent(_)}`,{cache:"no-store"});if(!q.ok)return;const ce=await q.json().catch(()=>null),ke=Number(ce?.count??ce?.totalCount??0),De=Number.isFinite(ke)&&ke>=0?ke:0;be||(Y(De),ee(Date.now()))}catch{}finally{if(!be){const q=document.hidden?6e4:3e4;Ce=window.setTimeout(Ae,q)}}},Ye=()=>{document.hidden||Ae()};return document.addEventListener("visibilitychange",Ye),Ae(),()=>{be=!0,Ce&&window.clearTimeout(Ce),document.removeEventListener("visibilitychange",Ye)}},[_]),E.useEffect(()=>{const be=Math.max(1,Math.ceil(W/v));D>be&&O(be)},[W,D]),E.useEffect(()=>{if(!t)return;let be=!1,Ce=null,Ae=null,Ye=!1;const q=()=>{Ae&&(window.clearInterval(Ae),Ae=null)},ce=ct=>{const $e=Array.isArray(ct)?ct:[];if(be)return;const it=xe.current,vt=new Map;for(const Mt of Array.isArray(it)?it:[]){const Ai=String(Mt?.id??"");Ai&&vt.set(Ai,String(Mt?.status??""))}if(!ut.current){const Mt={};for(const Ai of $e){const _i=String(Ai?.id??"");_i&&(Mt[_i]=!0)}Me.current=Mt,ut.current=!0}const Tt=new Set(["finished","stopped","failed"]);let St=0;for(const Mt of $e){const Ai=String(Mt?.id??"");if(!Ai)continue;const _i=String(vt.get(Ai)??"").toLowerCase().trim(),Wn=String(Mt?.status??"").toLowerCase().trim();!_i||_i===Wn||Tt.has(Wn)&&!Tt.has(_i)&&St++}St>0&&(window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:St}})),rt());const Rt=Mt=>String(Mt?.status??"").toLowerCase().trim(),gi=Mt=>{const Ai=Rt(Mt);return Ai==="postwork"||Ai==="queued_postwork"||Ai==="waiting_postwork"},Jt=Mt=>Number(Mt?.endedAtMs??Mt?.endedAt??Mt?.createdAtMs??Mt?.createdAt??Mt?.startedAtMs??Mt?.startedAt??0)||0,Vt=$e.filter(gi).slice().sort((Mt,Ai)=>Jt(Mt)-Jt(Ai)),wi=Vt.length,Ys=new Map;for(let Mt=0;Mt{const Ai=String(Mt?.id??""),_i=Ai?Ys.get(Ai):void 0;return _i?{...Mt,postworkQueuePos:_i,postworkQueueTotal:wi}:Mt});F(ts),xe.current=ts,yt(Mt=>{if(!Mt)return Mt;const Ai=ts.find(_i=>_i.id===Mt.id);return Ai||(Mt.status==="running"?null:Mt)})},ke=async()=>{if(!(be||Ye)){Ye=!0;try{const ct=await zs("/api/record/list");ce(ct)}catch{}finally{Ye=!1}}},De=()=>{Ae||(Ae=window.setInterval(ke,document.hidden?15e3:5e3))};ke(),Ce=new EventSource("/api/record/stream"),Ce.onopen=()=>{q()};const Be=ct=>{q();try{ce(JSON.parse(ct.data))}catch{}};Ce.addEventListener("jobs",Be),Ce.onerror=()=>De();const et=()=>{document.hidden||ke()};return document.addEventListener("visibilitychange",et),()=>{be=!0,q(),document.removeEventListener("visibilitychange",et),Ce?.removeEventListener("jobs",Be),Ce?.close(),Ce=null}},[t]),E.useEffect(()=>{if(qe!=="finished")return;let be=!1;const Ce={current:!1},Ae=new AbortController,Ye=async()=>{if(!(be||Ce.current)){Ce.current=!0;try{const De=await fetch(`/api/record/done?page=${D}&pageSize=${v}&sort=${encodeURIComponent(_)}&withCount=1`,{cache:"no-store",signal:Ae.signal});if(!De.ok)throw new Error(`HTTP ${De.status}`);const Be=await De.json().catch(()=>null),et=Array.isArray(Be?.items)?Be.items:Array.isArray(Be)?Be:[],ct=typeof Be?.count=="number"?Be.count:typeof Be?.totalCount=="number"?Be.totalCount:et.length;be||(G(et),Y(Number.isFinite(ct)?ct:et.length))}catch{be||(G([]),Y(0))}finally{Ce.current=!1}}};Ye();const ce=window.setInterval(()=>{document.hidden||Ye()},2e4),ke=()=>{document.hidden||Ye()};return document.addEventListener("visibilitychange",ke),()=>{be=!0,Ae.abort(),window.clearInterval(ce),document.removeEventListener("visibilitychange",ke)}},[qe,D,_]);const Bi=E.useCallback(async be=>{try{const Ce=typeof be=="number"?be:D,Ae=await zs(`/api/record/done?page=${Ce}&pageSize=${v}&sort=${encodeURIComponent(_)}&withCount=1`,{cache:"no-store"}),Ye=Array.isArray(Ae?.items)?Ae.items:[],q=Number(Ae?.count??Ae?.totalCount??Ye.length),ce=Number.isFinite(q)&&q>=0?q:Ye.length;Y(ce);const ke=Math.max(1,Math.ceil(ce/v)),De=Math.min(Math.max(1,Ce),ke);if(De!==D&&O(De),De===Ce)G(Ye);else{const Be=await zs(`/api/record/done?page=${De}&pageSize=${v}&sort=${encodeURIComponent(_)}&withCount=1`,{cache:"no-store"}),et=Array.isArray(Be?.items)?Be.items:[];G(et)}}catch{}},[D,_]);E.useEffect(()=>{let be=null;try{be=new EventSource("/api/record/done/stream")}catch{return}const Ce=()=>{Pi.current==="finished"&&Bi()};return be.addEventListener("doneChanged",Ce),be.onerror=()=>{},()=>{be?.removeEventListener("doneChanged",Ce),be?.close()}},[Bi]);function me(be){const Ce=go(be);if(!Ce)return!1;try{return new URL(Ce).hostname.includes("chaturbate.com")}catch{return!1}}function ye(be,Ce){const Ae=Object.fromEntries(Object.entries(be).map(([Ye,q])=>[Ye.trim().toLowerCase(),q]));for(const Ye of Ce){const q=Ae[Ye.toLowerCase()];if(q)return q}}function Se(be){const Ce=ye(be,["cf_clearance"]),Ae=ye(be,["sessionid","session_id","sessionId"]);return!!(Ce&&Ae)}async function Ue(be){try{await zs(`/api/record/stop?id=${encodeURIComponent(be)}`,{method:"POST"})}catch(Ce){a.error("Stop fehlgeschlagen",Ce?.message??String(Ce))}}E.useEffect(()=>{const be=Ce=>{const Ye=Number(Ce.detail?.delta??0);if(!Number.isFinite(Ye)||Ye===0){Bi();return}Y(q=>Math.max(0,q+Ye)),Bi()};return window.addEventListener("finished-downloads:count-hint",be),()=>window.removeEventListener("finished-downloads:count-hint",be)},[Bi]),E.useEffect(()=>{const be=Ce=>{const Ae=Ce.detail||{};Ae.tab==="finished"&&st("finished"),Ae.tab==="categories"&&st("categories"),Ae.tab==="models"&&st("models"),Ae.tab==="running"&&st("running"),Ae.tab==="settings"&&st("settings")};return window.addEventListener("app:navigate-tab",be),()=>window.removeEventListener("app:navigate-tab",be)},[]),E.useEffect(()=>{if(!ft){Ve(null),I(null);return}const be=(sh(ft.output||"")||"").trim().toLowerCase();I(be||null);const Ce=be?he[be]:void 0;Ve(Ce??null)},[ft,he]);async function Qe(){return Ts(R)}const Kt=E.useCallback(async be=>{const Ce=String(be?.sourceUrl??""),Ae=eu(Ce);if(!Ae)return!1;const Ye=go(Ae);if(!Ye)return!1;const q=ml(Ye),ce=await Ts(q,{silent:!0});return ce||a.error("Konnte URL nicht hinzufügen","Start fehlgeschlagen oder URL ungültig."),ce},[Ts,a]),Zt=E.useCallback(async be=>{const Ce=ln(be.output||"");if(Ce){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"start"}}));try{const Ae=await zs(`/api/record/delete?file=${encodeURIComponent(Ce)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"success"}})),window.setTimeout(()=>{G(q=>q.filter(ce=>ln(ce.output||"")!==Ce)),F(q=>q.filter(ce=>ln(ce.output||"")!==Ce)),yt(q=>q&&ln(q.output||"")===Ce?null:q)},320),window.setTimeout(()=>{Bi()},350);const Ye=typeof Ae?.undoToken=="string"?Ae.undoToken:"";return Ye?{undoToken:Ye}:{}}catch(Ae){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"error"}})),a.error("Löschen fehlgeschlagen",Ae?.message??String(Ae));return}}},[a,Bi]),hi=E.useCallback(async be=>{await Zt(be)},[Zt]),Hi=E.useCallback(async be=>{const Ce=ln(be.output||"");if(Ce){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"start"}}));try{await zs(`/api/record/keep?file=${encodeURIComponent(Ce)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"success"}})),window.setTimeout(()=>{G(Ae=>Ae.filter(Ye=>ln(Ye.output||"")!==Ce)),F(Ae=>Ae.filter(Ye=>ln(Ye.output||"")!==Ce)),yt(Ae=>Ae&&ln(Ae.output||"")===Ce?null:Ae)},320),Bi()}catch(Ae){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:Ce,phase:"error"}})),a.error("Keep fehlgeschlagen",Ae?.message??String(Ae));return}}},[qe,Bi,a]),nn=E.useCallback(async be=>{const Ce=ln(be.output||"");if(Ce)try{const Ae=await zs(`/api/record/toggle-hot?file=${encodeURIComponent(Ce)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:rename",{detail:{oldFile:Ae.oldFile,newFile:Ae.newFile}}));const Ye=q=>W$(q||"",Ae.newFile);yt(q=>q&&{...q,output:Ye(q.output||"")}),G(q=>q.map(ce=>ce.id===be.id||ln(ce.output||"")===Ce?{...ce,output:Ye(ce.output||"")}:ce)),F(q=>q.map(ce=>ce.id===be.id||ln(ce.output||"")===Ce?{...ce,output:Ye(ce.output||"")}:ce))}catch(Ae){a.error("Umbenennen fehlgeschlagen",Ae?.message??String(Ae))}},[a]);async function Gi(be){const Ce=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(be)});if(Ce.status===204)return null;if(!Ce.ok){const Ae=await Ce.text().catch(()=>"");throw new Error(Ae||`HTTP ${Ce.status}`)}return Ce.json()}const Ns=E.useCallback(be=>{const Ce=lt.current;!Ce||!be||(Ce.ts=Date.now(),Ce.list=Ce.list.filter(Ae=>Ae.id!==be))},[]),li=E.useRef({}),Pr=E.useCallback(async be=>{const Ce=ln(be.output||""),Ae=!!(ft&&ln(ft.output||"")===Ce),Ye=$e=>{try{const it=String($e.sourceUrl??$e.SourceURL??""),vt=eu(it);return vt?new URL(vt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},q=(sh(be.output||"")||"").trim().toLowerCase();if(q){const $e=q;if(li.current[$e])return;li.current[$e]=!0;const it=he[q]??{id:"",input:"",host:Ye(be)||void 0,modelKey:q,watching:!1,favorite:!1,liked:null,isUrl:!1},vt=!it.favorite,Tt={...it,modelKey:it.modelKey||q,favorite:vt,liked:vt?!1:it.liked};re(St=>({...St,[q]:Tt})),Ze(Tt),Ae&&Ve(Tt);try{const St=await Gi({...Tt.id?{id:Tt.id}:{},host:Tt.host||Ye(be)||"",modelKey:q,favorite:vt,...vt?{liked:!1}:{}});if(!St){re(gi=>{const{[q]:Jt,...Vt}=gi;return Vt}),it.id&&Ns(it.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:it.id,modelKey:q}}));return}const Rt=P(St.modelKey||q);Rt&&re(gi=>({...gi,[Rt]:St})),Ze(St),Ae&&Ve(St),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:St}}))}catch(St){re(Rt=>({...Rt,[q]:it})),Ze(it),Ae&&Ve(it),a.error("Favorit umschalten fehlgeschlagen",St?.message??String(St))}finally{delete li.current[$e]}return}let ce=Ae?Ge:null;if(ce||(ce=await Bn(be,{ensure:!0})),!ce)return;const ke=P(ce.modelKey||ce.id||"");if(!ke||li.current[ke])return;li.current[ke]=!0;const De=ce,Be=!De.favorite,et={...De,favorite:Be,liked:Be?!1:De.liked},ct=P(De.modelKey||"");ct&&re($e=>({...$e,[ct]:et})),Ze(et),Ae&&Ve(et);try{const $e=await Gi({id:De.id,favorite:Be,...Be?{liked:!1}:{}});if(!$e){re(vt=>{const Tt=P(De.modelKey||"");if(!Tt)return vt;const{[Tt]:St,...Rt}=vt;return Rt}),Ns(De.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:De.id,modelKey:De.modelKey}}));return}const it=P($e.modelKey||"");it&&re(vt=>({...vt,[it]:$e})),Ze($e),Ae&&Ve($e),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:$e}}))}catch($e){const it=P(De.modelKey||"");it&&re(vt=>({...vt,[it]:De})),Ze(De),Ae&&Ve(De),a.error("Favorit umschalten fehlgeschlagen",$e?.message??String($e))}finally{delete li.current[ke]}},[a,ft,Ge,Bn,Gi,Ze,Ns,he]),Kn=E.useCallback(async be=>{const Ce=ln(be.output||""),Ae=!!(ft&&ln(ft.output||"")===Ce),Ye=$e=>{try{const it=String($e.sourceUrl??$e.SourceURL??""),vt=eu(it);return vt?new URL(vt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},q=(sh(be.output||"")||"").trim().toLowerCase();if(q){const $e=q;if(li.current[$e])return;li.current[$e]=!0;const it=he[q]??{id:"",input:"",host:Ye(be)||void 0,modelKey:q,watching:!1,favorite:!1,liked:null,isUrl:!1},vt=it.liked!==!0,Tt={...it,modelKey:it.modelKey||q,liked:vt,favorite:vt?!1:it.favorite};re(St=>({...St,[q]:Tt})),Ze(Tt),Ae&&Ve(Tt);try{const St=await Gi({...Tt.id?{id:Tt.id}:{},host:Tt.host||Ye(be)||"",modelKey:q,liked:vt,...vt?{favorite:!1}:{}});if(!St){re(gi=>{const{[q]:Jt,...Vt}=gi;return Vt}),it.id&&Ns(it.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:it.id,modelKey:q}}));return}const Rt=P(St.modelKey||q);Rt&&re(gi=>({...gi,[Rt]:St})),Ze(St),Ae&&Ve(St),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:St}}))}catch(St){re(Rt=>({...Rt,[q]:it})),Ze(it),Ae&&Ve(it),a.error("Like umschalten fehlgeschlagen",St?.message??String(St))}finally{delete li.current[$e]}return}let ce=Ae?Ge:null;if(ce||(ce=await Bn(be,{ensure:!0})),!ce)return;const ke=P(ce.modelKey||ce.id||"");if(!ke||li.current[ke])return;li.current[ke]=!0;const De=ce,Be=De.liked!==!0,et={...De,liked:Be,favorite:Be?!1:De.favorite},ct=P(De.modelKey||"");ct&&re($e=>({...$e,[ct]:et})),Ze(et),Ae&&Ve(et);try{const $e=Be?await Gi({id:De.id,liked:!0,favorite:!1}):await Gi({id:De.id,liked:!1});if(!$e){re(vt=>{const Tt=P(De.modelKey||"");if(!Tt)return vt;const{[Tt]:St,...Rt}=vt;return Rt}),Ns(De.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:De.id,modelKey:De.modelKey}}));return}const it=P($e.modelKey||"");it&&re(vt=>({...vt,[it]:$e})),Ze($e),Ae&&Ve($e),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:$e}}))}catch($e){const it=P(De.modelKey||"");it&&re(vt=>({...vt,[it]:De})),Ze(De),Ae&&Ve(De),a.error("Like umschalten fehlgeschlagen",$e?.message??String($e))}finally{delete li.current[ke]}},[a,ft,Ge,Bn,Gi,Ze,Ns,he]),rn=E.useCallback(async be=>{const Ce=ln(be.output||""),Ae=!!(ft&&ln(ft.output||"")===Ce),Ye=$e=>{try{const it=String($e.sourceUrl??$e.SourceURL??""),vt=eu(it);return vt?new URL(vt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},q=(sh(be.output||"")||"").trim().toLowerCase();if(q){const $e=q;if(li.current[$e])return;li.current[$e]=!0;const it=he[q]??{id:"",input:"",host:Ye(be)||void 0,modelKey:q,watching:!1,favorite:!1,liked:null,isUrl:!1},vt=!it.watching,Tt={...it,modelKey:it.modelKey||q,watching:vt};re(St=>({...St,[q]:Tt})),Ze(Tt),Ae&&Ve(Tt);try{const St=await Gi({...Tt.id?{id:Tt.id}:{},host:Tt.host||Ye(be)||"",modelKey:q,watched:vt});if(!St){re(gi=>{const{[q]:Jt,...Vt}=gi;return Vt}),it.id&&Ns(it.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:it.id,modelKey:q}}));return}const Rt=P(St.modelKey||q);Rt&&re(gi=>({...gi,[Rt]:St})),Ze(St),Ae&&Ve(St),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:St}}))}catch(St){re(Rt=>({...Rt,[q]:it})),Ze(it),Ae&&Ve(it),a.error("Watched umschalten fehlgeschlagen",St?.message??String(St))}finally{delete li.current[$e]}return}let ce=Ae?Ge:null;if(ce||(ce=await Bn(be,{ensure:!0})),!ce)return;const ke=P(ce.modelKey||ce.id||"");if(!ke||li.current[ke])return;li.current[ke]=!0;const De=ce,Be=!De.watching,et={...De,watching:Be},ct=P(De.modelKey||"");ct&&re($e=>({...$e,[ct]:et})),Ze(et),Ae&&Ve(et);try{const $e=await Gi({id:De.id,watched:Be});if(!$e){re(vt=>{const Tt=P(De.modelKey||"");if(!Tt)return vt;const{[Tt]:St,...Rt}=vt;return Rt}),Ns(De.id),Ae&&Ve(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:De.id,modelKey:De.modelKey}}));return}const it=P($e.modelKey||"");it&&re(vt=>({...vt,[it]:$e})),Ze($e),Ae&&Ve($e),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:$e}}))}catch($e){const it=P(De.modelKey||"");it&&re(vt=>({...vt,[it]:De})),Ze(De),Ae&&Ve(De),a.error("Watched umschalten fehlgeschlagen",$e?.message??String($e))}finally{delete li.current[ke]}},[a,ft,Ge,Bn,Gi,Ze,Ns,he]);async function Bn(be,Ce){const Ae=!!Ce?.ensure,Ye=et=>{const ct=Date.now(),$e=lt.current;if(!$e){lt.current={ts:ct,list:[et]};return}$e.ts=ct;const it=$e.list.findIndex(vt=>vt.id===et.id);it>=0?$e.list[it]=et:$e.list.unshift(et)},q=async et=>{if(!et)return null;const ct=et.trim().toLowerCase();if(!ct)return null;const $e=he[ct];if($e)return Ye($e),$e;if(Ae){let Rt;try{const Jt=be.sourceUrl??be.SourceURL??"",Vt=eu(Jt);Vt&&(Rt=new URL(Vt).hostname.replace(/^www\./i,"").toLowerCase())}catch{}const gi=await zs("/api/models/ensure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({modelKey:et,...Rt?{host:Rt}:{}})});return Ze(gi),gi}const it=Date.now(),vt=lt.current;if(!vt||it-vt.ts>3e4){const Rt=Object.values(he);if(Rt.length)lt.current={ts:it,list:Rt};else{const gi=await zs("/api/models/list",{cache:"no-store"});lt.current={ts:it,list:Array.isArray(gi)?gi:[]}}}const St=(lt.current?.list??[]).find(Rt=>(Rt.modelKey||"").trim().toLowerCase()===ct);return St||null},ce=sh(be.output||"");if(ce)return q(ce);const ke=be.status==="running",De=be.sourceUrl??be.SourceURL??"",Be=eu(De);if(ke&&Be){const et=await zs("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Be})}),ct=await zs("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(et)});return Ze(ct),ct}return null}return E.useEffect(()=>{if(!mi&&!Ht||!navigator.clipboard?.readText)return;let be=!1,Ce=!1,Ae=null;const Ye=async()=>{if(!(be||Ce)){Ce=!0;try{const ke=await navigator.clipboard.readText(),De=eu(ke);if(!De)return;const Be=go(De);if(!Be||!wh(Be))return;const ct=ml(Be);if(ct===Ii.current)return;Ii.current=ct,mi&&$(ct),Ht&&Yi({url:ct,silent:!1})}catch{}finally{Ce=!1}}},q=ke=>{be||(Ae=window.setTimeout(async()=>{await Ye(),q(document.hidden?5e3:1500)},ke))},ce=()=>{Ye()};return window.addEventListener("hover",ce),document.addEventListener("visibilitychange",ce),q(0),()=>{be=!0,Ae&&window.clearTimeout(Ae),window.removeEventListener("hover",ce),document.removeEventListener("visibilitychange",ce)}},[mi,Ht,Ts]),E.useEffect(()=>{const be=Jw({getModels:()=>{if(!ci.current.useChaturbateApi)return[];const Ce=Ws.current,Ae=Us.current,Ye=Object.values(Ce).filter(ce=>!!ce?.watching&&String(ce?.host??"").toLowerCase().includes("chaturbate")).map(ce=>String(ce?.modelKey??"").trim().toLowerCase()).filter(Boolean),q=Object.keys(Ae||{}).map(ce=>String(ce||"").trim().toLowerCase()).filter(Boolean);return Array.from(new Set([...Ye,...q]))},getShow:()=>["public","private","hidden","away"],intervalMs:12e3,onData:Ce=>{(async()=>{if(!Ce?.enabled){Xt({}),ys.current={},ms.current={},Ki([]),vs.current={},Mn.current=!1,vn.current={},ee(Date.now());return}const Ae={};for(const ke of Array.isArray(Ce.rooms)?Ce.rooms:[]){const De=String(ke?.username??"").trim().toLowerCase();De&&(Ae[De]=ke)}Xt(Ae),ys.current=Ae;try{const ke=!!(ci.current.enableNotifications??!0),De=new Set(["private","away","hidden"]),Be=new Set(Object.values(Ws.current||{}).filter(Rt=>!!Rt?.watching&&String(Rt?.host??"").toLowerCase().includes("chaturbate")).map(Rt=>String(Rt?.modelKey??"").trim().toLowerCase()).filter(Boolean)),et=ms.current||{},ct={...et},$e=vn.current||{},it=!Mn.current,vt=vs.current||{},Tt={...vt};for(const[Rt,gi]of Object.entries(Ae)){const Jt=String(gi?.current_show??"").toLowerCase().trim(),Vt=String(et[Rt]??"").toLowerCase().trim(),ts=!0&&!!!$e[Rt],Mt=!!vt[Rt],Ai=String(gi?.username??Rt).trim()||Rt,_i=String(gi?.image_url??"").trim();if(Tt[Rt]=!0,Jt==="public"&&De.has(Vt)){ke&&a.info(Ai,"ist wieder online.",{imageUrl:_i,imageAlt:`${Ai} Vorschau`,durationMs:5500}),Jt&&(ct[Rt]=Jt);continue}if(Be.has(Rt)&&ts){const ca=Mt;ke&&!it&&a.info(Ai,ca?"ist wieder online.":"ist online.",{imageUrl:_i,imageAlt:`${Ai} Vorschau`,durationMs:5500})}Jt&&(ct[Rt]=Jt)}const St={};for(const Rt of Object.keys(Ae))St[Rt]=!0;vn.current=St,vs.current=Tt,Mn.current=!0,ms.current=ct}catch{}const Ye=bs.current;for(const ke of Ye||[]){const De=String(ke||"").trim().toLowerCase();De&&Ae[De]}if(!ci.current.useChaturbateApi)Ki([]);else if(Pi.current==="running"){const ke=Ws.current,De=Us.current,Be=Array.from(new Set(Object.values(ke).filter(it=>!!it?.watching&&String(it?.host??"").toLowerCase().includes("chaturbate")).map(it=>String(it?.modelKey??"").trim().toLowerCase()).filter(Boolean))),et=Object.keys(De||{}).map(it=>String(it||"").trim().toLowerCase()).filter(Boolean),ct=new Set(et),$e=Array.from(new Set([...Be,...et]));if($e.length===0)Ki([]);else{const it=[];for(const vt of $e){const Tt=Ae[vt];if(!Tt)continue;const St=String(Tt?.username??"").trim(),Rt=String(Tt?.current_show??"unknown");if(Rt==="public"&&!ct.has(vt))continue;const gi=`https://chaturbate.com/${(St||vt).trim()}/`;it.push({id:vt,modelKey:St||vt,url:gi,currentShow:Rt,imageUrl:String(Tt?.image_url??"")})}it.sort((vt,Tt)=>vt.modelKey.localeCompare(Tt.modelKey,void 0,{sensitivity:"base"})),Ki(it)}}if(!ci.current.useChaturbateApi||V.current)return;const q=Us.current,ce=Object.keys(q||{}).map(ke=>String(ke||"").toLowerCase()).filter(Boolean);for(const ke of ce){const De=Ae[ke];if(!De||String(De.current_show??"")!=="public")continue;const Be=q[ke];Be&&Yi({url:Be,silent:!0,pendingKeyLower:ke})}ee(Date.now())})()}});return()=>be()},[]),E.useEffect(()=>{if(!Dt.useChaturbateApi){K(0);return}const be=Jw({getModels:()=>[],getShow:()=>["public","private","hidden","away"],intervalMs:3e4,fetchAllWhenNoModels:!0,onData:Ce=>{if(!Ce?.enabled){K(0);return}const Ae=Number(Ce?.total??0);K(Number.isFinite(Ae)?Ae:0),ee(Date.now())},onError:Ce=>{console.error("[ALL-online poller] error",Ce)}});return()=>be()},[Dt.useChaturbateApi]),s?t?g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsxs("div",{className:"relative",children:[g.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:g.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:[g.jsxs("div",{className:"flex items-center sm:items-start justify-between gap-3 sm:gap-4",children:[g.jsx("div",{className:"min-w-0",children:g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight text-gray-900 dark:text-white",children:"Recorder"}),g.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.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:[g.jsx(TM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:se})]}),g.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:"Watched online",children:[g.jsx(Lc,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:Or})]}),g.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:[g.jsx(Rc,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:Mr})]}),g.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:[g.jsx(mM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:js})]})]}),g.jsx("div",{className:"hidden sm:block text-[11px] text-gray-500 dark:text-gray-400",children:ue})]}),g.jsxs("div",{className:"sm:hidden mt-1 w-full",children:[g.jsx("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:ue}),g.jsxs("div",{className:"mt-2 flex items-stretch gap-2",children:[p?g.jsx(Zw,{mode:"inline",className:"flex-1"}):g.jsx("div",{className:"flex-1"}),g.jsx(ti,{variant:"secondary",onClick:()=>Ot(!0),className:"px-3 shrink-0",children:"Cookies"}),g.jsx(ti,{variant:"secondary",onClick:r,className:"px-3 shrink-0",children:"Abmelden"})]})]})]})}),g.jsxs("div",{className:"hidden sm:flex items-center gap-2 h-full",children:[p?g.jsx(Zw,{mode:"inline"}):null,g.jsx(ti,{variant:"secondary",onClick:()=>Ot(!0),className:"h-9 px-3",children:"Cookies"}),g.jsx(ti,{variant:"secondary",onClick:r,className:"h-9 px-3",children:"Abmelden"})]})]}),g.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-stretch",children:[g.jsxs("div",{className:"relative",children:[g.jsx("label",{className:"sr-only",children:"Source URL"}),g.jsx("input",{value:R,onChange:be=>$(be.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"})]}),g.jsx(ti,{variant:"primary",onClick:Qe,disabled:!Pn,className:"w-full sm:w-auto rounded-lg",children:"Start"})]}),bt?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:bt}),g.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:()=>gt(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null,me(R)&&!Se(ot)?g.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:["⚠️ Für Chaturbate werden die Cookies ",g.jsx("code",{children:"cf_clearance"})," und ",g.jsx("code",{children:"sessionId"})," benötigt."]}):null,at?g.jsx("div",{className:"pt-1",children:g.jsx(Dc,{label:"Starte Download…",indeterminate:!0})}):null,g.jsx("div",{className:"hidden sm:block pt-2",children:g.jsx(MS,{tabs:bn,value:qe,onChange:st,ariaLabel:"Tabs",variant:"barUnderline"})})]})}),g.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:g.jsx("div",{className:"mx-auto max-w-7xl px-4 py-2",children:g.jsx(MS,{tabs:bn,value:qe,onChange:st,ariaLabel:"Tabs",variant:"barUnderline"})})}),g.jsxs("main",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-6 space-y-6",children:[qe==="running"?g.jsx(y$,{jobs:sn,modelsByKey:he,pending:Oi,onOpenPlayer:tn,onStopJob:Ue,onToggleFavorite:Pr,onToggleLike:Kn,onToggleWatch:rn,onAddToDownloads:Kt,blurPreviews:!!Dt.blurPreviews}):null,qe==="finished"?g.jsx(HM,{jobs:B,modelsByKey:he,doneJobs:M,doneTotal:W,page:D,pageSize:v,onPageChange:O,onOpenPlayer:tn,onDeleteJob:Zt,onToggleHot:nn,onToggleFavorite:Pr,onToggleLike:Kn,onToggleWatch:rn,blurPreviews:!!Dt.blurPreviews,teaserPlayback:Dt.teaserPlayback??"hover",teaserAudio:!!Dt.teaserAudio,assetNonce:qt,sortMode:_,onSortModeChange:be=>{S(be),O(1)}}):null,qe==="models"?g.jsx(S$,{}):null,qe==="categories"?g.jsx(V$,{}):null,qe==="settings"?g.jsx(sO,{onAssetsGenerated:Ut}):null]}),g.jsx(J5,{open:Et,onClose:()=>Ot(!1),initialCookies:xn,onApply:be=>{const Ce=Hm(Object.fromEntries(be.map(Ae=>[Ae.name,Ae.value])));ht(Ce),zs("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:Ce})}).catch(()=>{})}}),g.jsx(M$,{open:!!_t,modelKey:_t,onClose:()=>mt(null),onOpenPlayer:tn,runningJobs:sn,cookies:ot,blurPreviews:Dt.blurPreviews,onToggleHot:nn,onDelete:hi,onToggleFavorite:Pr,onToggleLike:Kn,onToggleWatch:rn}),ft?g.jsx(c$,{job:ft,modelKey:L??void 0,modelsByKey:he,expanded:nt,onToggleExpand:()=>jt(be=>!be),onClose:()=>yt(null),isHot:ln(ft.output||"").startsWith("HOT "),isFavorite:!!Ge?.favorite,isLiked:Ge?.liked===!0,isWatching:!!Ge?.watching,onKeep:Hi,onDelete:hi,onToggleHot:nn,onToggleFavorite:Pr,onToggleLike:Kn,onStopJob:Ue,onToggleWatch:rn}):null]})]}):g.jsx(q$,{onLoggedIn:n}):g.jsx("div",{className:"min-h-[100dvh] grid place-items-center",children:"Lade…"})}jI.createRoot(document.getElementById("root")).render(g.jsx(E.StrictMode,{children:g.jsx(FM,{position:"top-right",maxToasts:3,defaultDurationMs:3500,children:g.jsx(Q$,{})})})); diff --git a/backend/web/dist/assets/index-SqYhLYXQ.css b/backend/web/dist/assets/index-SqYhLYXQ.css new file mode 100644 index 0000000..8f13771 --- /dev/null +++ b/backend/web/dist/assets/index-SqYhLYXQ.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-green-800:oklch(44.8% .119 151.328);--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-slate-200:oklch(92.9% .013 255.508);--color-slate-400:oklch(70.4% .04 256.788);--color-slate-500:oklch(55.4% .046 257.417);--color-slate-900:oklch(20.8% .042 265.755);--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-md:28rem;--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-4{top:calc(var(--spacing)*4)}.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-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-40{z-index:40}.z-50{z-index:50}.z-\[1\]{z-index:1}.z-\[60\]{z-index:60}.z-\[80\]{z-index:80}.z-\[9999\]{z-index:9999}.z-\[2147483647\]{z-index:2147483647}.col-span-1{grid-column:span 1/span 1}.col-span-2{grid-column:span 2/span 2}.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-5{margin-top:calc(var(--spacing)*5)}.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-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.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{height:calc(var(--spacing)*1)}.h-1\.5{height:calc(var(--spacing)*1.5)}.h-2{height:calc(var(--spacing)*2)}.h-2\.5{height:calc(var(--spacing)*2.5)}.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-44{height:calc(var(--spacing)*44)}.h-52{height:calc(var(--spacing)*52)}.h-80{height:calc(var(--spacing)*80)}.h-\[60px\]{height:60px}.h-\[64px\]{height:64px}.h-\[220px\]{height:220px}.h-full{height:100%}.max-h-0{max-height:calc(var(--spacing)*0)}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-\[40vh\]{max-height:40vh}.max-h-\[80vh\]{max-height:80vh}.max-h-\[720px\]{max-height:720px}.max-h-\[calc\(100vh-3rem\)\]{max-height:calc(100vh - 3rem)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\[100dvh\]{min-height:100dvh}.min-h-full{min-height:100%}.w-1{width:calc(var(--spacing)*1)}.w-2\.5{width:calc(var(--spacing)*2.5)}.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-20{width:calc(var(--spacing)*20)}.w-28{width:calc(var(--spacing)*28)}.w-44{width:calc(var(--spacing)*44)}.w-52{width:calc(var(--spacing)*52)}.w-72{width:calc(var(--spacing)*72)}.w-\[46rem\]{width:46rem}.w-\[52rem\]{width:52rem}.w-\[64px\]{width:64px}.w-\[90px\]{width:90px}.w-\[92px\]{width:92px}.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-\[360px\]{width:360px}.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-\[420px\]{max-width:420px}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100\%-24px\)\]{max-width:calc(100% - 24px)}.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-md{max-width:var(--container-md)}.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-\[980px\]{min-width:980px}.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-1{--tw-translate-y:calc(var(--spacing)*-1);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-grab{cursor:grab}.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))}.grid-cols-\[minmax\(0\,1fr\)_auto_auto\]{grid-template-columns:minmax(0,1fr) auto auto}.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}.items-stretch{align-items:stretch}.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-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}: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-r{border-right-style:var(--tw-border-style);border-right-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-200{border-color:var(--color-indigo-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\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.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\/30{background-color:#0000004d}@supports (color:color-mix(in lab,red,red)){.bg-black\/30{background-color:color-mix(in oklab,var(--color-black)30%,transparent)}}.bg-black\/35{background-color:#00000059}@supports (color:color-mix(in lab,red,red)){.bg-black\/35{background-color:color-mix(in oklab,var(--color-black)35%,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\/70{background-color:#f3f4f6b3}@supports (color:color-mix(in lab,red,red)){.bg-gray-100\/70{background-color:color-mix(in oklab,var(--color-gray-100)70%,transparent)}}.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-100{background-color:var(--color-red-100)}.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-slate-500\/15{background-color:#62748e26}@supports (color:color-mix(in lab,red,red)){.bg-slate-500\/15{background-color:color-mix(in oklab,var(--color-slate-500)15%,transparent)}}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.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)}.pl-2{padding-left:calc(var(--spacing)*2)}.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}.break-all{word-break:break-all}.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-green-800{color:var(--color-green-800)}.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-slate-900{color:var(--color-slate-900)}.text-white{color:var(--color-white)}.text-white\/50{color:#ffffff80}@supports (color:color-mix(in lab,red,red)){.text-white\/50{color:color-mix(in oklab,var(--color-white)50%,transparent)}}.text-white\/60{color:#fff9}@supports (color:color-mix(in lab,red,red)){.text-white\/60{color:color-mix(in oklab,var(--color-white)60%,transparent)}}.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)}}.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)}}.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,.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)}.ring-2{--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)}.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-100{--tw-ring-color:var(--color-indigo-100)}.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-slate-500\/30{--tw-ring-color:#62748e4d}@supports (color:color-mix(in lab,red,red)){.ring-slate-500\/30{--tw-ring-color:color-mix(in oklab,var(--color-slate-500)30%,transparent)}}.ring-white{--tw-ring-color:var(--color-white)}.ring-white\/10{--tw-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.ring-white\/10{--tw-ring-color:color-mix(in oklab,var(--color-white)10%,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,)}.blur-xl{--tw-blur:blur(var(--blur-xl));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,)}.filter{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-md{--tw-backdrop-blur:blur(var(--blur-md));-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-\[max-height\,opacity\]{transition-property:max-height,opacity;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-all{-webkit-user-select:all;user-select:all}.select-none{-webkit-user-select:none;user-select:none}.\[contain-intrinsic-size\:180px_120px\]{contain-intrinsic-size:180px 120px}.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\:translate-x-\[1px\]:is(:where(.group):hover *){--tw-translate-x:1px;translate:var(--tw-translate-x)var(--tw-translate-y)}.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\:-translate-y-\[1px\]:hover{--tw-translate-y: -1px ;translate:var(--tw-translate-x)var(--tw-translate-y)}.hover\:scale-\[1\.03\]:hover{scale:1.03}.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\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.focus-visible\:ring-offset-white:focus-visible{--tw-ring-offset-color:var(--color-white)}.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\:scale-\[0\.98\]:active{scale:.98}.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-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\:inset-x-auto{inset-inline:auto}.md\:right-auto{right:auto}.md\:bottom-4{bottom:calc(var(--spacing)*4)}.md\:left-1\/2{left:50%}.md\:inline-block{display:inline-block}.md\:w-\[min\(760px\,calc\(100vw-32px\)\)\]{width:min(760px,100vw - 32px)}.md\:-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}}@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(min-width:80rem){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@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-indigo-500\/30{border-color:#625fff4d}@supports (color:color-mix(in lab,red,red)){.dark\:border-indigo-500\/30{border-color:color-mix(in oklab,var(--color-indigo-500)30%,transparent)}}.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\/30{background-color:#0000004d}@supports (color:color-mix(in lab,red,red)){.dark\:bg-black\/30{background-color:color-mix(in oklab,var(--color-black)30%,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-black\/45{background-color:#00000073}@supports (color:color-mix(in lab,red,red)){.dark\:bg-black\/45{background-color:color-mix(in oklab,var(--color-black)45%,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\/60{background-color:#10182899}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/60{background-color:color-mix(in oklab,var(--color-gray-900)60%,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\/80{background-color:#030712cc}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-950\/80{background-color:color-mix(in oklab,var(--color-gray-950)80%,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-green-500\/20{background-color:#00c75833}@supports (color:color-mix(in lab,red,red)){.dark\:bg-green-500\/20{background-color:color-mix(in oklab,var(--color-green-500)20%,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-slate-400\/10{background-color:#90a1b91a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-slate-400\/10{background-color:color-mix(in oklab,var(--color-slate-400)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\/35{background-color:#ffffff59}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/35{background-color:color-mix(in oklab,var(--color-white)35%,transparent)}}.dark\:bg-white\/\[0\.06\]{background-color:#ffffff0f}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/\[0\.06\]{background-color:color-mix(in oklab,var(--color-white)6%,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-slate-200{color:var(--color-slate-200)}.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-gray-950{--tw-ring-color:var(--color-gray-950)}.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-indigo-500\/20{--tw-ring-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:ring-indigo-500\/20{--tw-ring-color:color-mix(in oklab,var(--color-indigo-500)20%,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-slate-400\/25{--tw-ring-color:#90a1b940}@supports (color:color-mix(in lab,red,red)){.dark\:ring-slate-400\/25{--tw-ring-color:color-mix(in oklab,var(--color-slate-400)25%,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\/20:hover{background-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/20:hover{background-color:color-mix(in oklab,var(--color-indigo-500)20%,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\:bg-white\/\[0\.09\]:hover{background-color:#ffffff17}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/\[0\.09\]:hover{background-color:color-mix(in oklab,var(--color-white)9%,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\:ring-offset-gray-950:focus-visible{--tw-ring-offset-color:var(--color-gray-950)}.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}.video-js{position:relative}.video-js .vjs-control-bar{z-index:60;position:relative}.video-js .vjs-menu-button-popup .vjs-menu,.video-js .vjs-volume-panel .vjs-volume-control{z-index:9999!important}.vjs-mini .video-js .vjs-current-time,.vjs-mini .video-js .vjs-time-divider,.vjs-mini .video-js .vjs-duration{opacity:1!important;visibility:visible!important;display:flex!important}.vjs-mini .video-js .vjs-current-time-display,.vjs-mini .video-js .vjs-duration-display{display:inline!important}.video-js .vjs-time-control{width:auto!important;min-width:0!important;padding-left:.35em!important;padding-right:.35em!important}.video-js .vjs-time-divider{padding-left:.15em!important;padding-right:.15em!important}.video-js .vjs-time-divider>div{padding:0!important}.video-js .vjs-current-time-display,.video-js .vjs-duration-display{font-variant-numeric:tabular-nums;font-size:.95em}@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/index.html b/backend/web/dist/index.html index 875522d..5deef62 100644 --- a/backend/web/dist/index.html +++ b/backend/web/dist/index.html @@ -5,8 +5,8 @@ App - - + +
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2ad5133..626105f 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -156,6 +156,75 @@ function getProviderFromNormalizedUrl(normUrl: string): Provider | null { } } +function chaturbateUserFromUrl(normUrl: string): string { + try { + const u = new URL(normUrl) + const host = u.hostname.replace(/^www\./i, '').toLowerCase() + if (host !== 'chaturbate.com' && !host.endsWith('.chaturbate.com')) return '' + + // https://chaturbate.com//... + const parts = u.pathname.split('/').filter(Boolean) + return parts[0] ? decodeURIComponent(parts[0]).trim() : '' + } catch { + return '' + } +} + +/** + * Macht aus "beliebigen" Provider-URLs eine EINDEUTIGE Standardform. + * -> wichtig für dedupe (Queue, alreadyRunning), Clipboard, Pending-Maps. + */ +function canonicalizeProviderUrl(normUrl: string): string { + const provider = getProviderFromNormalizedUrl(normUrl) + if (!provider) return normUrl + + if (provider === 'chaturbate') { + const name = chaturbateUserFromUrl(normUrl) + return name ? `https://chaturbate.com/${encodeURIComponent(name)}/` : normUrl + } + + // provider === 'mfc' + const name = mfcUserFromUrl(normUrl) + // Standardisiere auf EIN Format (hier: #) + return name ? `https://www.myfreecams.com/#${encodeURIComponent(name)}` : normUrl +} + +/** Gibt den "ModelKey" aus einer URL zurück (lowercased) – für beide Provider */ +function providerKeyLowerFromUrl(normUrl: string): string { + const provider = getProviderFromNormalizedUrl(normUrl) + if (!provider) return '' + const raw = provider === 'chaturbate' ? chaturbateUserFromUrl(normUrl) : mfcUserFromUrl(normUrl) + return (raw || '').trim().toLowerCase() +} + + +function mfcUserFromUrl(normUrl: string): string { + try { + const u = new URL(normUrl) + const host = u.hostname.replace(/^www\./i, '').toLowerCase() + + // nur MFC + if (host !== 'myfreecams.com' && !host.endsWith('.myfreecams.com')) return '' + + // typische MFC Profile-URLs: + // https://www.myfreecams.com/# + // https://www.myfreecams.com/#/models/ + // https://www.myfreecams.com/ (seltener) + const hash = (u.hash || '').replace(/^#\/?/, '') // "#/models/foo" -> "models/foo" + if (hash) { + const parts = hash.split('/').filter(Boolean) + const last = parts[parts.length - 1] || '' + if (last) return decodeURIComponent(last).trim() + } + + const parts = u.pathname.split('/').filter(Boolean) + const last = parts[parts.length - 1] || '' + return last ? decodeURIComponent(last).trim() : '' + } catch { + return '' + } +} + const baseName = (p: string) => (p || '').replaceAll('\\', '/').split('/').pop() || '' function replaceBasename(fullPath: string, newBase: string) { @@ -232,6 +301,8 @@ export default function App() { setCbOnlineByKeyLower({}) cbOnlineByKeyLowerRef.current = {} + startedToastByJobIdRef.current = {} + jobsInitDoneRef.current = false setPendingWatchedRooms([]) setPendingAutoStartByKey({}) @@ -248,6 +319,50 @@ export default function App() { const notify = useNotify() + const notifyRef = useRef(notify) + + // ✅ Dedupe für "Cookies fehlen" Meldung (damit silent/autostarts nicht spammen) + const cookieProblemLastAtRef = useRef(0) + + const isCookieGateError = (msg: string) => { + const m = (msg || '').toLowerCase() + return ( + m.includes('altersverifikationsseite erhalten') || + m.includes('verify your age') || + m.includes('schutzseite von cloudflare erhalten') || + m.includes('just a moment') || + m.includes('kein room-html') + ) + } + + const showMissingCookiesMessage = (opts?: { silent?: boolean }) => { + const silent = Boolean(opts?.silent) + + const title = 'Cookies fehlen oder sind abgelaufen' + const body = + 'Der Recorder hat statt des Room-HTML eine Schutz-/Altersverifikationsseite erhalten. ' + + 'Bitte Cookies aktualisieren (bei Chaturbate z.B. cf_clearance + sessionId) und erneut starten.' + + // Wenn Nutzer aktiv klickt: oben als Error-Box zeigen + Cookie-Modal anbieten + if (!silent) { + setError(`⚠️ ${title}. ${body}`) + // optional aber hilfreich: Modal direkt öffnen + setCookieModalOpen(true) + return + } + + // Bei silent (Auto-Start / Queue): nur selten Toast + const now = Date.now() + if (now - cookieProblemLastAtRef.current > 15_000) { + cookieProblemLastAtRef.current = now + notifyRef.current?.error(title, body) + } + } + + useEffect(() => { + notifyRef.current = notify + }, [notify]) + // ✅ Perf: PerformanceMonitor erst nach initialer Render/Hydration anzeigen const [showPerfMon, setShowPerfMon] = useState(false) @@ -366,14 +481,38 @@ export default function App() { useEffect(() => { const onOpen = (ev: Event) => { const e = ev as CustomEvent<{ modelKey?: string }> - const raw = (e.detail?.modelKey ?? '').trim() + const raw0 = (e.detail?.modelKey ?? '').trim() + if (!raw0) return - 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() + // 1) Wenn es "nur ein Key" ist (z.B. maypeach), direkt übernehmen + // Heuristik: keine Spaces, keine Slashes -> sehr wahrscheinlich Key + const looksLikeKey = + !raw0.includes(' ') && + !raw0.includes('/') && + !raw0.includes('\\') - if (k) setDetailsModelKey(k) + if (looksLikeKey) { + const k = raw0.replace(/^@/, '').trim().toLowerCase() + if (k) setDetailsModelKey(k) + return + } + + // 2) Sonst: URL/Path normalisieren + Provider-Key extrahieren + const norm0 = normalizeHttpUrl(raw0) + if (!norm0) { + // Fallback auf alte Key-Logik (falls raw sowas wie "chaturbate.com/im_jasmine" ist) + let k = raw0.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) + return + } + + const norm = canonicalizeProviderUrl(norm0) + const keyLower = providerKeyLowerFromUrl(norm) + + if (keyLower) setDetailsModelKey(keyLower) } window.addEventListener('open-model-details', onOpen as any) @@ -479,6 +618,11 @@ export default function App() { const busyRef = useRef(false) const cookiesRef = useRef>({}) const jobsRef = useRef([]) + + // ✅ "Job gestartet" Toast: dedupe (auch gegen SSE/polling) + initial-load suppression + const startedToastByJobIdRef = useRef>({}) + const jobsInitDoneRef = useRef(false) + useEffect(() => { busyRef.current = busy }, [busy]) @@ -493,9 +637,163 @@ export default function App() { const pendingStartUrlRef = useRef(null) const lastClipboardUrlRef = useRef('') + // --- START QUEUE (parallel) --- + const START_CONCURRENCY = 4 // ⬅️ kannst du höher setzen, aber 4 ist ein guter Start + + type StartQueueItem = { + url: string + silent: boolean + pendingKeyLower?: string // wenn aus pendingAutoStartByKey kommt + } + + const startQueueRef = useRef([]) + const startInFlightRef = useRef(0) + const startQueuedSetRef = useRef>(new Set()) // dedupe: verhindert Duplikate + const pumpStartQueueScheduledRef = useRef(false) + + const setBusyFromStarts = useCallback(() => { + const v = startInFlightRef.current > 0 + setBusy(v) + busyRef.current = v + }, []) + + const enqueueStart = useCallback( + (item: StartQueueItem) => { + const norm0 = normalizeHttpUrl(item.url) + if (!norm0) return false + const norm = canonicalizeProviderUrl(norm0) + + // dedupe: gleiche URL nicht 100x in die Queue + if (startQueuedSetRef.current.has(norm)) return true + startQueuedSetRef.current.add(norm) + + startQueueRef.current.push({ ...item, url: norm }) + + // pump einmal pro Tick schedulen + if (!pumpStartQueueScheduledRef.current) { + pumpStartQueueScheduledRef.current = true + queueMicrotask(() => { + pumpStartQueueScheduledRef.current = false + void pumpStartQueue() + }) + } + return true + }, + // pumpStartQueue kommt gleich darunter (useCallback), daher eslint ggf. meckert -> ok, wir definieren pumpStartQueue als function declaration unten + [] + ) + + async function doStartNow(normUrl: string, silent: boolean): Promise { + + normUrl = canonicalizeProviderUrl(normUrl) + + // ✅ Duplicate-running guard (wie vorher) + const alreadyRunning = jobsRef.current.some((j) => { + if (String(j.status || '').toLowerCase() !== 'running') return false + if ((j as any).endedAt) return false + const jNorm0 = normalizeHttpUrl(String((j as any).sourceUrl || '')) + const jNorm = jNorm0 ? canonicalizeProviderUrl(jNorm0) : '' + return jNorm === normUrl + }) + if (alreadyRunning) return true + + try { + const currentCookies = cookiesRef.current + + const provider = getProviderFromNormalizedUrl(normUrl) + if (!provider) { + if (!silent) setError('Nur chaturbate.com oder myfreecams.com werden unterstützt.') + return false + } + + if (provider === 'chaturbate' && !hasRequiredChaturbateCookies(currentCookies)) { + if (!silent) setError('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.') + return false + } + + 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: normUrl, cookie: cookieString }), + }) + + if (created?.id) startedToastByJobIdRef.current[String(created.id)] = true + + // UI sofort aktualisieren (optional) + setJobs((prev) => [created, ...prev]) + jobsRef.current = [created, ...jobsRef.current] + + return true + } catch (e: any) { + const msg = e?.message ?? String(e) + + // ✅ Spezialfall: Age-Gate / Cloudflare / kein Room-HTML => Cookies Hinweis + if (isCookieGateError(msg)) { + showMissingCookiesMessage({ silent }) + return false + } + + if (!silent) setError(msg) + return false + } + } + + async function pumpStartQueue(): Promise { + // so viele wie möglich parallel starten + while (startInFlightRef.current < START_CONCURRENCY && startQueueRef.current.length > 0) { + const next = startQueueRef.current.shift()! + startInFlightRef.current++ + setBusyFromStarts() + + void (async () => { + try { + const ok = await doStartNow(next.url, next.silent) + + // wenn das aus pendingAutoStartByKey kam: nur bei Erfolg dort löschen + if (ok && next.pendingKeyLower) { + const kLower = next.pendingKeyLower + setPendingAutoStartByKey((prev) => { + const copy = { ...(prev || {}) } + delete copy[kLower] + pendingAutoStartByKeyRef.current = copy + return copy + }) + } + } finally { + // dedupe wieder freigeben + startQueuedSetRef.current.delete(next.url) + + startInFlightRef.current = Math.max(0, startInFlightRef.current - 1) + setBusyFromStarts() + + // falls noch was da ist: weiterpumpen + if (startQueueRef.current.length > 0) { + void pumpStartQueue() + } + } + })() + } + } + // ✅ Zentraler Snapshot: username(lower) -> room const [cbOnlineByKeyLower, setCbOnlineByKeyLower] = useState>({}) const cbOnlineByKeyLowerRef = useRef>({}) + + const lastCbShowByKeyLowerRef = useRef>({}) + + // ✅ merkt sich, ob ein Model im letzten Snapshot überhaupt online war + const lastCbOnlineByKeyLowerRef = useRef>({}) + + // ✅ verhindert Toast-Spam direkt beim ersten Poll (Startup) + const cbOnlineInitDoneRef = useRef(false) + + // ✅ merkt sich, ob ein Model seit App-Start schon einmal online war + const everCbOnlineByKeyLowerRef = useRef>({}) + useEffect(() => { cbOnlineByKeyLowerRef.current = cbOnlineByKeyLower }, [cbOnlineByKeyLower]) @@ -539,8 +837,9 @@ export default function App() { // ✅ 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 norm0 = normalizeHttpUrl(rawUrl) + if (!norm0) return false + const norm = canonicalizeProviderUrl(norm0) const silent = Boolean(opts?.silent) if (!silent) setError(null) @@ -565,7 +864,8 @@ export default function App() { // ✅ Wenn endedAt existiert: Aufnahme ist fertig -> Postwork/Queue -> NICHT blocken if ((j as any).endedAt) return false - const jNorm = normalizeHttpUrl(String((j as any).sourceUrl || '')) + const jNorm0 = normalizeHttpUrl(String((j as any).sourceUrl || '')) + const jNorm = jNorm0 ? canonicalizeProviderUrl(jNorm0) : '' return jNorm === norm }) if (alreadyRunning) return true @@ -621,11 +921,23 @@ export default function App() { body: JSON.stringify({ url: norm, cookie: cookieString }), }) + // ✅ verhindert Doppel-Toast: StartUrl toastet ggf. schon selbst, + // und kurz danach kommt der Job nochmal über SSE/polling rein. + if (created?.id) startedToastByJobIdRef.current[String(created.id)] = true + setJobs((prev) => [created, ...prev]) jobsRef.current = [created, ...jobsRef.current] return true } catch (e: any) { - if (!silent) setError(e?.message ?? String(e)) + const msg = e?.message ?? String(e) + + // ✅ Spezialfall: Age-Gate / Cloudflare / kein Room-HTML => Cookies Hinweis + if (isCookieGateError(msg)) { + showMissingCookiesMessage({ silent }) + return false + } + + if (!silent) setError(msg) return false } finally { setBusy(false) @@ -849,50 +1161,122 @@ export default function App() { if (donePage > maxPage) setDonePage(maxPage) }, [doneCount, donePage]) - // jobs SSE / polling (unverändert) + // jobs SSE / polling (mit "Job gestartet" Toast für Backend-Autostarts) useEffect(() => { + if (!authed) return // ✅ WICHTIG: bei Logout alles stoppen + let cancelled = false let es: EventSource | null = null let fallbackTimer: number | null = null let inFlight = false + const stopFallbackPolling = () => { + if (fallbackTimer) { + window.clearInterval(fallbackTimer) + fallbackTimer = null + } + } + const applyList = (list: any) => { const arr = Array.isArray(list) ? (list as RecordJob[]) : [] if (cancelled) return + // --- vorheriger Snapshot für Status-Transitions --- const prev = jobsRef.current - const prevById = new Map(prev.map((j) => [j.id, j.status])) + const prevStatusById = new Map() + for (const j of Array.isArray(prev) ? prev : []) { + const id = String((j as any)?.id ?? '') + if (!id) continue + prevStatusById.set(id, String((j as any)?.status ?? '')) + } + // ✅ 0) Initial load: KEINE Toasts, aber als "gesehen" markieren (falls du später wieder Start-Toast einführen willst) + if (!jobsInitDoneRef.current) { + const seen: Record = {} + for (const j of arr) { + const id = String((j as any)?.id ?? '') + if (id) seen[id] = true + } + startedToastByJobIdRef.current = seen + jobsInitDoneRef.current = true + } + + // ✅ Finished/Stopped/Failed Transition zählen -> Count-Hint + Asset-Bump const terminal = new Set(['finished', 'stopped', 'failed']) let endedDelta = 0 for (const j of arr) { - const ps = prevById.get(j.id) - if (!ps || ps === j.status) continue + const id = String((j as any)?.id ?? '') + if (!id) continue + + const before = String(prevStatusById.get(id) ?? '').toLowerCase().trim() + const now = String((j as any)?.status ?? '').toLowerCase().trim() + + if (!before || before === now) continue // nur zählen, wenn wir "neu" in einen terminal state gehen - if (terminal.has(j.status) && !terminal.has(ps)) { - endedDelta++ - } + if (terminal.has(now) && !terminal.has(before)) endedDelta++ } if (endedDelta > 0) { - // ✅ Tabs/Count sofort aktualisieren – auch wenn Finished-Tab nicht offen ist window.dispatchEvent( new CustomEvent('finished-downloads:count-hint', { detail: { delta: endedDelta } }) ) - - // deine bestehenden Asset-Bumps (thumbnails etc.) bumpAssetsTwice() } - setJobs(arr) - jobsRef.current = arr + // ---- Queue-Info berechnen (Postwork-Warteschlange) ---- + const statusLower = (j: any) => String(j?.status ?? '').toLowerCase().trim() + + const isPostworkQueued = (j: any) => { + const s = statusLower(j) + return s === 'postwork' || s === 'queued_postwork' || s === 'waiting_postwork' + } + + const ts = (j: any) => + Number( + j?.endedAtMs ?? + j?.endedAt ?? + j?.createdAtMs ?? + j?.createdAt ?? + j?.startedAtMs ?? + j?.startedAt ?? + 0 + ) || 0 + + const postworkQueue = arr + .filter(isPostworkQueued) + .slice() + .sort((a, b) => ts(a) - ts(b)) + + const postworkTotal = postworkQueue.length + const postworkPosById = new Map() + for (let i = 0; i < postworkQueue.length; i++) { + const id = String((postworkQueue[i] as any)?.id ?? '') + if (id) postworkPosById.set(id, i + 1) + } + + const arrWithQueue = arr.map((j: any) => { + const id = String(j?.id ?? '') + const pos = id ? postworkPosById.get(id) : undefined + if (!pos) return j + return { + ...j, + postworkQueuePos: pos, + postworkQueueTotal: postworkTotal, + } + }) + + setJobs(arrWithQueue) + jobsRef.current = arrWithQueue setPlayerJob((prevJob) => { if (!prevJob) return prevJob - const updated = arr.find((j) => j.id === prevJob.id) + + const updated = arrWithQueue.find((j) => j.id === prevJob.id) if (updated) return updated + + // wenn running und nicht mehr in list: player schließen, sonst stehen lassen return prevJob.status === 'running' ? null : prevJob }) } @@ -919,7 +1303,13 @@ export default function App() { es = new EventSource('/api/record/stream') + // ✅ wenn SSE wieder verbunden ist: Fallback-Polling stoppen + es.onopen = () => { + stopFallbackPolling() + } + const onJobs = (ev: MessageEvent) => { + stopFallbackPolling() // ✅ sobald Daten kommen, Polling aus try { applyList(JSON.parse(ev.data)) } catch {} @@ -932,18 +1322,20 @@ export default function App() { if (!document.hidden) void loadOnce() } document.addEventListener('visibilitychange', onVis) - window.addEventListener('hover', onVis) + + // ❌ das hier empfehle ich rauszuwerfen, siehe Schritt C + // window.addEventListener('hover', onVis) return () => { cancelled = true - if (fallbackTimer) window.clearInterval(fallbackTimer) + stopFallbackPolling() document.removeEventListener('visibilitychange', onVis) - window.removeEventListener('hover', onVis) + // window.removeEventListener('hover', onVis) es?.removeEventListener('jobs', onJobs as any) es?.close() es = null } - }, [bumpAssetsTwice]) + }, [authed]) useEffect(() => { if (selectedTab !== 'finished') return @@ -1177,10 +1569,13 @@ export default function App() { const handleAddToDownloads = useCallback( async (job: RecordJob): Promise => { const raw = String((job as any)?.sourceUrl ?? '') - const url = extractFirstUrl(raw) - if (!url) return false + const url0 = extractFirstUrl(raw) + if (!url0) return false - // silent=true -> keine rote Error-Box, wir geben Feedback über Checkmark/Toast + const norm0 = normalizeHttpUrl(url0) + if (!norm0) return false + + const url = canonicalizeProviderUrl(norm0) const ok = await startUrl(url, { silent: true }) if (!ok) { @@ -1921,21 +2316,25 @@ export default function App() { inFlight = true try { const text = await navigator.clipboard.readText() - const url = extractFirstUrl(text) - if (!url) return - if (!getProviderFromNormalizedUrl(url)) return + const url0 = extractFirstUrl(text) + if (!url0) return + + const norm0 = normalizeHttpUrl(url0) + if (!norm0) return + + const provider = getProviderFromNormalizedUrl(norm0) + if (!provider) return + + const url = canonicalizeProviderUrl(norm0) + if (url === lastClipboardUrlRef.current) return lastClipboardUrlRef.current = url if (autoAddEnabled) setSourceUrl(url) if (autoStartEnabled) { - if (busyRef.current) { - pendingStartUrlRef.current = url - } else { - pendingStartUrlRef.current = null - await startUrl(url) - } + // ✅ immer enqueue (dedupe verhindert doppelt) + enqueueStart({ url, silent: false }) } } catch { // ignore @@ -1966,15 +2365,6 @@ export default function App() { } }, [autoAddEnabled, autoStartEnabled, startUrl]) - useEffect(() => { - if (busy) return - if (!autoStartEnabled) return - const pending = pendingStartUrlRef.current - if (!pending) return - pendingStartUrlRef.current = null - void startUrl(pending) - }, [busy, autoStartEnabled, startUrl]) - useEffect(() => { const stop = startChaturbateOnlinePolling({ getModels: () => { @@ -2006,7 +2396,11 @@ export default function App() { if (!data?.enabled) { setCbOnlineByKeyLower({}) cbOnlineByKeyLowerRef.current = {} + lastCbShowByKeyLowerRef.current = {} setPendingWatchedRooms([]) + everCbOnlineByKeyLowerRef.current = {} + cbOnlineInitDoneRef.current = false + lastCbOnlineByKeyLowerRef.current = {} setLastHeaderUpdateAtMs(Date.now()) return } @@ -2020,6 +2414,97 @@ export default function App() { setCbOnlineByKeyLower(nextSnap) cbOnlineByKeyLowerRef.current = nextSnap + // ✅ Toasts: (A) watched offline->online, (B) waiting->public, (C) online->offline->online => "wieder online" + try { + const notificationsOn = Boolean((recSettingsRef.current as any).enableNotifications ?? true) + const waiting = new Set(['private', 'away', 'hidden']) + + // watched-Keys (nur Chaturbate) + const watchedSetLower = new Set( + Object.values(modelsByKeyRef.current || {}) + .filter((m) => Boolean(m?.watching) && String(m?.host ?? '').toLowerCase().includes('chaturbate')) + .map((m) => String(m?.modelKey ?? '').trim().toLowerCase()) + .filter(Boolean) + ) + + const prevShow = lastCbShowByKeyLowerRef.current || {} + const nextShowMap: Record = { ...prevShow } + + const prevOnline = lastCbOnlineByKeyLowerRef.current || {} + const isInitial = !cbOnlineInitDoneRef.current + + // ✅ "war schon mal online" Snapshot (vor diesem Poll) + const everOnline = everCbOnlineByKeyLowerRef.current || {} + const nextEverOnline: Record = { ...everOnline } + + for (const [keyLower, room] of Object.entries(nextSnap)) { + const nowShow = String((room as any)?.current_show ?? '').toLowerCase().trim() + const beforeShow = String(prevShow[keyLower] ?? '').toLowerCase().trim() + + const wasOnline = Boolean(prevOnline[keyLower]) + const isOnline = true // weil es in nextSnap ist + const becameOnline = isOnline && !wasOnline + + // ✅ war irgendwann schon mal online (vor diesem Poll)? + const hadEverBeenOnline = Boolean(everOnline[keyLower]) + + const name = String((room as any)?.username ?? keyLower).trim() || keyLower + const imageUrl = String((room as any)?.image_url ?? '').trim() + + // immer merken: jetzt ist es online + nextEverOnline[keyLower] = true + + // (B) waiting -> public => "wieder online" (höchste Priorität, damit kein Doppel-Toast) + const becamePublicFromWaiting = nowShow === 'public' && waiting.has(beforeShow) + if (becamePublicFromWaiting) { + if (notificationsOn) { + notify.info(name, 'ist wieder online.', { + imageUrl, + imageAlt: `${name} Vorschau`, + durationMs: 5500, + }) + } + + if (nowShow) nextShowMap[keyLower] = nowShow + continue + } + + // (A/C) watched: offline -> online + if (watchedSetLower.has(keyLower) && becameOnline) { + // C: online->offline->online => "wieder online" + const cameBackFromOffline = hadEverBeenOnline + + // Startup-Spam vermeiden + if (notificationsOn && !isInitial) { + notify.info( + name, + cameBackFromOffline ? 'ist wieder online.' : 'ist online.', + { + imageUrl, + imageAlt: `${name} Vorschau`, + durationMs: 5500, + } + ) + } + } + + if (nowShow) nextShowMap[keyLower] = nowShow + } + + // Presence-Snapshot merken + const nextOnline: Record = {} + for (const k of Object.keys(nextSnap)) nextOnline[k] = true + lastCbOnlineByKeyLowerRef.current = nextOnline + + // ✅ "ever online" merken + everCbOnlineByKeyLowerRef.current = nextEverOnline + + cbOnlineInitDoneRef.current = true + lastCbShowByKeyLowerRef.current = nextShowMap + } catch { + // ignore + } + // Online-Keys für Store const storeKeys = chaturbateStoreKeysLowerRef.current const nextOnlineStore: Record = {} @@ -2100,16 +2585,8 @@ export default function App() { 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 - }) - } + // ✅ nicht mehr seriell awaiten, sondern in die Start-Queue + enqueueStart({ url, silent: true, pendingKeyLower: kLower }) } setLastHeaderUpdateAtMs(Date.now()) diff --git a/frontend/src/components/ui/Downloads.tsx b/frontend/src/components/ui/Downloads.tsx index 30cb9a6..f69edd3 100644 --- a/frontend/src/components/ui/Downloads.tsx +++ b/frontend/src/components/ui/Downloads.tsx @@ -144,8 +144,11 @@ async function apiJSON(url: string, init?: RequestInit): Promise { return res.json() as Promise } -function postWorkLabel(job: RecordJob): string { - const pw = job.postWork +function postWorkLabel( + job: RecordJob, + override?: { pos?: number; total?: number } +): string { + const pw = (job as any).postWork if (!pw) return 'Warte auf Nacharbeiten…' @@ -158,24 +161,37 @@ function postWorkLabel(job: RecordJob): string { } if (pw.state === 'queued') { - const pos = typeof pw.position === 'number' ? pw.position : 0 - const waiting = typeof pw.waiting === 'number' ? pw.waiting : 0 - const running = typeof (pw as any).running === 'number' ? (pw as any).running : 0 + // Backend-Werte (können was anderes zählen -> deshalb nur Fallback) + const posServer = typeof pw.position === 'number' ? pw.position : 0 + const waitingServer = typeof pw.waiting === 'number' ? pw.waiting : 0 + const runningServer = typeof (pw as any).running === 'number' ? (pw as any).running : 0 + const totalServer = Math.max(waitingServer + runningServer, posServer) - // X = grobe Gesamtmenge (wartend + gerade laufend) - const total = Math.max(waiting + running, pos) + const pos = + typeof override?.pos === 'number' && Number.isFinite(override.pos) && override.pos > 0 + ? override.pos + : posServer + + const total = + typeof override?.total === 'number' && Number.isFinite(override.total) && override.total > 0 + ? override.total + : totalServer - // Wunschformat: "64 / X" return pos > 0 && total > 0 ? `Warte auf Nacharbeiten… ${pos} / ${total}` : 'Warte auf Nacharbeiten…' } - return 'Warte auf Nacharbeiten…' } -function StatusCell({ job }: { job: RecordJob }) { +function StatusCell({ + job, + postworkInfo, +}: { + job: RecordJob + postworkInfo?: { pos?: number; total?: number } +}) { const phaseRaw = String((job as any)?.phase ?? '').trim() const progress = Number((job as any)?.progress ?? 0) @@ -186,7 +202,7 @@ function StatusCell({ job }: { job: RecordJob }) { // ✅ postwork genauer machen (wartend/running + Position) if (phase === 'postwork') { - phaseText = postWorkLabel(job) + phaseText = postWorkLabel(job, postworkInfo) } if (isRecording) { @@ -240,6 +256,7 @@ function DownloadsCardRow({ blurPreviews, modelsByKey, stopRequestedIds, + postworkInfoOf, markStopRequested, onOpenPlayer, onStopJob, @@ -252,6 +269,7 @@ function DownloadsCardRow({ blurPreviews?: boolean modelsByKey: Record stopRequestedIds: Record + postworkInfoOf: (job: RecordJob) => { pos?: number; total?: number } | undefined markStopRequested: (ids: string | string[]) => void onOpenPlayer: (job: RecordJob) => void onStopJob: (id: string) => void @@ -368,7 +386,7 @@ function DownloadsCardRow({ if (phaseLower === 'recording') { phaseText = 'Recording läuft…' } else if (phaseLower === 'postwork') { - phaseText = postWorkLabel(j) + phaseText = postWorkLabel(j, postworkInfoOf(j)) } const statusText = rawStatus || 'unknown' @@ -763,6 +781,69 @@ export default function Downloads({ return jobs.some((j) => !j.endedAt && j.status === 'running') }, [jobs]) + const postworkQueueInfoById = useMemo(() => { + const infoById = new Map() + + const enqueueMsOf = (job: RecordJob): number => { + const anyJ = job as any + const pw = anyJ.postWork + return ( + toMs(pw?.enqueuedAt) || + toMs(anyJ.enqueuedAt) || + toMs(anyJ.queuedAt) || + toMs(anyJ.createdAt) || + toMs(anyJ.addedAt) || + toMs(job.endedAt) || // Postwork entsteht oft nach endedAt + toMs(job.startedAt) || + 0 + ) + } + + // 1) alle relevanten Postwork-Jobs sammeln (queued + running) + const running: RecordJob[] = [] + const queued: RecordJob[] = [] + + for (const j of jobs) { + const pw = (j as any)?.postWork + if (!pw) continue + + const state = String(pw.state ?? '').toLowerCase() + if (state === 'running') running.push(j) + else if (state === 'queued') queued.push(j) + } + + // 2) Reihenfolge stabil machen (FIFO) + running.sort((a, b) => enqueueMsOf(a) - enqueueMsOf(b)) + queued.sort((a, b) => enqueueMsOf(a) - enqueueMsOf(b)) + + const runningCount = running.length + const total = runningCount + queued.length + + // 3) Positionen setzen: running belegt "vorne", queued danach + for (let i = 0; i < queued.length; i++) { + const id = String((queued[i] as any)?.id ?? '') + if (!id) continue + infoById.set(id, { pos: runningCount + i + 1, total }) + } + + // optional (wenn du auch bei running "x / total" sehen willst): + // for (let i = 0; i < running.length; i++) { + // const id = String((running[i] as any)?.id ?? '') + // if (!id) continue + // infoById.set(id, { pos: i + 1, total }) + // } + + return infoById + }, [jobs]) + + const postworkInfoOf = useCallback( + (job: RecordJob) => { + const id = String((job as any)?.id ?? '') + return id ? postworkQueueInfoById.get(id) : undefined + }, + [postworkQueueInfoById] + ) + useEffect(() => { if (!hasActive) return const t = window.setInterval(() => setNowMs(Date.now()), 15000) @@ -954,7 +1035,7 @@ export default function Downloads({ cell: (r) => { if (r.kind === 'job') { const j = r.job - return + return } const p = r.pending @@ -1073,7 +1154,7 @@ export default function Downloads({ }, }, ] - }, [blurPreviews, markStopRequested, modelsByKey, nowMs, onStopJob, onToggleFavorite, onToggleLike, onToggleWatch, stopRequestedIds, stopInitiatedIds]) + }, [blurPreviews, markStopRequested, modelsByKey, nowMs, onStopJob, onToggleFavorite, onToggleLike, onToggleWatch, stopRequestedIds, stopInitiatedIds, postworkInfoOf]) const downloadJobRows = useMemo(() => { const list = jobs @@ -1197,6 +1278,7 @@ export default function Downloads({ nowMs={nowMs} blurPreviews={blurPreviews} modelsByKey={modelsByKey} + postworkInfoOf={postworkInfoOf} stopRequestedIds={stopRequestedIds} markStopRequested={markStopRequested} onOpenPlayer={onOpenPlayer} @@ -1221,6 +1303,7 @@ export default function Downloads({ nowMs={nowMs} blurPreviews={blurPreviews} modelsByKey={modelsByKey} + postworkInfoOf={postworkInfoOf} stopRequestedIds={stopRequestedIds} markStopRequested={markStopRequested} onOpenPlayer={onOpenPlayer} @@ -1245,6 +1328,7 @@ export default function Downloads({ nowMs={nowMs} blurPreviews={blurPreviews} modelsByKey={modelsByKey} + postworkInfoOf={postworkInfoOf} stopRequestedIds={stopRequestedIds} markStopRequested={markStopRequested} onOpenPlayer={onOpenPlayer} diff --git a/frontend/src/components/ui/FinishedDownloads.tsx b/frontend/src/components/ui/FinishedDownloads.tsx index 2489588..e9bc793 100644 --- a/frontend/src/components/ui/FinishedDownloads.tsx +++ b/frontend/src/components/ui/FinishedDownloads.tsx @@ -699,6 +699,9 @@ export default function FinishedDownloads({ // neben deletedKeys / deletingKeys const [removingKeys, setRemovingKeys] = React.useState>(() => new Set()) + // ⏱️ Timer pro Key, damit wir Optimistik bei Fehler sauber zurückrollen können + const removeTimersRef = React.useRef>(new Map()) + const markRemoving = useCallback((key: string, value: boolean) => { setRemovingKeys((prev) => { const next = new Set(prev) @@ -708,21 +711,65 @@ export default function FinishedDownloads({ }) }, []) + const cancelRemoveTimer = useCallback((key: string) => { + const t = removeTimersRef.current.get(key) + if (t != null) { + window.clearTimeout(t) + removeTimersRef.current.delete(key) + } + }, []) + + const restoreRow = useCallback( + (key: string) => { + // Timer stoppen (falls die "commit delete"-Phase noch aussteht) + cancelRemoveTimer(key) + + // wieder sichtbar machen + setDeletedKeys((prev) => { + const next = new Set(prev) + next.delete(key) + return next + }) + setRemovingKeys((prev) => { + const next = new Set(prev) + next.delete(key) + return next + }) + setDeletingKeys((prev) => { + const next = new Set(prev) + next.delete(key) + return next + }) + setKeepingKeys((prev) => { + const next = new Set(prev) + next.delete(key) + return next + }) + }, + [cancelRemoveTimer] + ) + const animateRemove = useCallback( (key: string) => { // 1) rot + fade-out starten markRemoving(key, true) + // ggf. alten Timer entfernen (wenn mehrfach getriggert) + cancelRemoveTimer(key) + // 2) nach der Animation wirklich ausblenden + Seite auffüllen - window.setTimeout(() => { + const t = window.setTimeout(() => { + removeTimersRef.current.delete(key) + markDeleted(key) markRemoving(key, false) - // ✅ wichtig: Seite sofort neu laden -> Item rückt nach queueRefill() }, 320) + + removeTimersRef.current.set(key, t) }, - [markDeleted, markRemoving, queueRefill] + [markDeleted, markRemoving, queueRefill, cancelRemoveTimer] ) const releasePlayingFile = useCallback( @@ -795,6 +842,9 @@ export default function FinishedDownloads({ return true } catch (e: any) { + // ✅ falls irgendwo (z.B. via External-Event) schon optimistisch entfernt wurde: zurückrollen + restoreRow(key) + notify.error('Löschen fehlgeschlagen', String(e?.message || e)) return false } finally { @@ -1060,30 +1110,32 @@ export default function FinishedDownloads({ if (detail.phase === 'start') { markDeleting(key, true) - // ✅ wenn Cards-View: Swipe schon beim Start raus (ohne Aktion, weil App die API schon macht) - if (view === 'cards') { - window.setTimeout(() => { - markDeleted(key) - }, 320) - } else { - animateRemove(key) - } - } else if (detail.phase === 'error') { - markDeleting(key, false) + // ✅ Optimistik: überall gleich -> animiert raus + animateRemove(key) - // ✅ Swipe zurück, falls Delete fehlgeschlagen - if (view === 'cards') { - swipeRefs.current.get(key)?.reset() - } - } else if (detail.phase === 'success') { + return + } + + if (detail.phase === 'error') { + // ✅ alles zurückrollen -> wieder sichtbar + restoreRow(key) + + // ✅ Swipe zurück (nur Cards relevant, schadet sonst aber nicht) + swipeRefs.current.get(key)?.reset() + return + } + + if (detail.phase === 'success') { + // delete final bestätigt markDeleting(key, false) queueRefill() + return } } window.addEventListener('finished-downloads:delete', onExternalDelete as EventListener) return () => window.removeEventListener('finished-downloads:delete', onExternalDelete as EventListener) - }, [animateRemove, markDeleting, markDeleted, view, queueRefill]) + }, [animateRemove, markDeleting, queueRefill, restoreRow]) useEffect(() => { const onExternalRename = (ev: Event) => { diff --git a/frontend/src/components/ui/LoginPage.tsx b/frontend/src/components/ui/LoginPage.tsx index 679d694..0b5d5f2 100644 --- a/frontend/src/components/ui/LoginPage.tsx +++ b/frontend/src/components/ui/LoginPage.tsx @@ -250,14 +250,15 @@ export default function LoginPage({ onLoggedIn }: Props) {
setCode(e.target.value)} onKeyDown={onEnter} autoComplete="one-time-code" + required inputMode="numeric" pattern="[0-9]*" maxLength={6} @@ -349,13 +350,14 @@ export default function LoginPage({ onLoggedIn }: Props) { setCode(e.target.value)} onKeyDown={onEnter} autoComplete="one-time-code" + required inputMode="numeric" pattern="[0-9]*" maxLength={6} diff --git a/frontend/src/components/ui/Player.tsx b/frontend/src/components/ui/Player.tsx index c23a4a8..6c39e8e 100644 --- a/frontend/src/components/ui/Player.tsx +++ b/frontend/src/components/ui/Player.tsx @@ -67,10 +67,13 @@ function ensureGearControlRegistered() { } update() { - try { super.update?.() } catch {} + try { + super.update?.() + } catch {} const p: any = this.player() const curQ = String(p.options_?.__gearQuality ?? 'auto') + const autoApplied = String(p.options_?.__autoAppliedQuality ?? '') const items = (this.items || []) as any[] for (const it of items) { @@ -78,6 +81,23 @@ function ensureGearControlRegistered() { const val = it?.options_?.__value if (kind === 'quality') it.selected?.(String(val) === curQ) } + + // ✅ Auto-Label: "Auto (720p)" wenn Auto aktiv + try { + for (const it of items) { + if (it?.options_?.__kind !== 'quality') continue + if (String(it?.options_?.__value) !== 'auto') continue + const el = it.el?.() as HTMLElement | null + const text = el?.querySelector?.('.vjs-menu-item-text') as HTMLElement | null + if (!text) continue + + if (curQ === 'auto' && autoApplied && autoApplied !== 'auto') { + text.textContent = `Auto (${autoApplied})` + } else { + text.textContent = 'Auto' + } + } + } catch {} } createItems() { @@ -86,13 +106,20 @@ function ensureGearControlRegistered() { // ✅ KEIN "Quality" Header mehr - const qualities = (player.options_?.gearQualities || ['auto', '1080p', '720p', '480p']) as string[] + const qualities = (player.options_?.gearQualities || [ + 'auto', + '1080p', + '720p', + '480p', + ]) as string[] const currentQ = String(player.options_?.__gearQuality ?? 'auto') for (const q of qualities) { + const label = q === 'auto' ? 'Auto' : q === '2160p' ? '4K' : q + items.push( new GearMenuItem(player, { - label: q === 'auto' ? 'Auto' : q, + label, selectable: true, selected: currentQ === q, __kind: 'quality', @@ -112,7 +139,10 @@ function ensureGearControlRegistered() { // ✅ Typing-Fix const VjsComponent = videojs.getComponent('Component') as any - videojs.registerComponent('GearMenuButton', GearMenuButton as unknown as typeof VjsComponent) + videojs.registerComponent( + 'GearMenuButton', + GearMenuButton as unknown as typeof VjsComponent + ) // ✅ CSS nur 1x injizieren if (!vjsAny.__gearControlCssInjected) { @@ -177,7 +207,6 @@ function ensureGearControlRegistered() { } } - const baseName = (p: string) => (p || '').replaceAll('\\', '/').split('/').pop() || '' const stripHotPrefix = (s: string) => (s.startsWith('HOT ') ? s.slice(4) : s) const lower = (s: string) => (s || '').trim().toLowerCase() @@ -266,10 +295,9 @@ function formatFps(n?: number | null): string { return `${n.toFixed(digits)} fps` } -function formatResolution(w?: number | null, h?: number | null): string { - if (!w || !h) return '—' - const p = Math.round(h) - return `${w}×${h} (${p}p)` +function formatResolution(h?: number | null): string { + if (!h || !Number.isFinite(h)) return '—' + return `${Math.round(h)}p` } function parseDateFromOutput(output?: string): Date | null { @@ -338,49 +366,78 @@ function useMediaQuery(query: string) { return matches } -function gearQualitiesForHeight( - h?: number | null, - supported: string[] = ['1080p', '720p', '480p'] // <-- nur was dein Backend wirklich kann -): string[] { - const maxH = typeof h === 'number' && Number.isFinite(h) && h > 0 ? h : 0 +function installAbsoluteTimelineShim(p: any) { + if (!p || p.__absTimelineShimInstalled) return + p.__absTimelineShimInstalled = true - const qToH = (q: string): number => { - const m = String(q).match(/(\d{3,4})p/i) - return m ? Number(m[1]) : 0 + // Originale Methoden sichern + p.__origCurrentTime = p.currentTime.bind(p) + p.__origDuration = p.duration.bind(p) + + // Helper: relative Zeit (innerhalb des aktuell geladenen Segments) setzen, + // OHNE server-seek auszulösen. + p.__setRelativeTime = (rel: number) => { + try { + p.__origCurrentTime(Math.max(0, rel || 0)) + } catch {} } - // nur Qualitäten <= Videohöhe (mit etwas Toleranz) - const filtered = supported - .filter((q) => { - const qh = qToH(q) - if (!qh) return false - if (!maxH) return true // wenn unbekannt: zeig alle supported - return qh <= maxH + 8 // kleine Toleranz - }) - .sort((a, b) => qToH(b) - qToH(a)) // absteigend + // currentTime(): GET => absolute Zeit, SET => absolute Zeit (-> server seek falls vorhanden) + p.currentTime = function (v?: number) { + const off = Number(this.__timeOffsetSec ?? 0) || 0 - // immer Auto vorne - const out = ['auto', ...filtered] + // SET (Seekbar / API) + if (typeof v === 'number' && Number.isFinite(v)) { + const abs = Math.max(0, v) - // dedupe - return Array.from(new Set(out)) + // Wenn wir server-seek können: als absolute Zeit interpretieren + if (typeof this.__serverSeekAbs === 'function') { + this.__serverSeekAbs(abs) + return abs + } + + // Fallback: innerhalb aktueller Datei relativ setzen + return this.__origCurrentTime(Math.max(0, abs - off)) + } + + // GET + const rel = Number(this.__origCurrentTime() ?? 0) || 0 + return Math.max(0, off + rel) + } + + // duration(): immer volle Original-Dauer zurückgeben, wenn bekannt + p.duration = function () { + const full = Number(this.__fullDurationSec ?? 0) || 0 + if (full > 0) return full + + // Fallback: offset + segment-dauer + const off = Number(this.__timeOffsetSec ?? 0) || 0 + const relDur = Number(this.__origDuration() ?? 0) || 0 + return Math.max(0, off + relDur) + } } -function qualityFromHeight(h?: number | null): string { - const hh = typeof h === 'number' && Number.isFinite(h) && h > 0 ? Math.round(h) : 0 - if (!hh) return 'auto' +function gearQualitiesForHeight(h?: number | null): string[] { + const srcH = typeof h === 'number' && Number.isFinite(h) && h > 0 ? Math.round(h) : 0 + const ladder = [2160, 1440, 1080, 720, 480, 360, 240] // gewünschte Stufen - // grob auf gängige Stufen mappen - if (hh >= 1000) return '1080p' - if (hh >= 700) return '720p' - if (hh >= 460) return '480p' + const toQ = (n: number) => `${n}p` + const uniq = (arr: string[]) => Array.from(new Set(arr)) - // falls kleiner: trotzdem was sinnvolles - return `${hh}p` + // Wenn unbekannt: trotzdem Ladder anbieten + Auto + if (!srcH) { + return ['auto', ...ladder.map(toQ)] + } + + // native Höhe (immer anzeigen, auch wenn nicht genau Ladder) + const allowed = ladder.filter((x) => x <= srcH + 8) + + // native immer rein (und dann absteigend sortiert) + const allHeights = Array.from(new Set([...allowed, srcH])).sort((a, b) => b - a) + + return uniq(['auto', ...allHeights.map(toQ)]) } - - export type PlayerProps = { job: RecordJob expanded: boolean @@ -432,12 +489,13 @@ export default function Player({ onStopJob, startMuted = DEFAULT_PLAYER_START_MUTED, }: PlayerProps) { - const title = React.useMemo(() => baseName(job.output?.trim() || '') || job.id, [job.output, job.id]) + const title = React.useMemo( + () => baseName(job.output?.trim() || '') || job.id, + [job.output, job.id] + ) const fileRaw = React.useMemo(() => baseName(job.output?.trim() || ''), [job.output]) - const playName = React.useMemo(() => baseName(job.output?.trim() || ''), [job.output]) - const sizeLabel = React.useMemo(() => formatBytes(sizeBytesOf(job)), [job]) const anyJob = job as any @@ -449,13 +507,10 @@ export default function Player({ // ✅ Backend erwartet "id=" (nicht "name=") // running: echte job.id (jobs-map lookup) // finished: Dateiname ohne Extension als Stem (wenn dein Backend finished so mapped) - const finishedStem = React.useMemo( - () => (playName || '').replace(/\.[^.]+$/, ''), - [playName] - ) + const finishedStem = React.useMemo(() => (playName || '').replace(/\.[^.]+$/, ''), [playName]) const previewId = React.useMemo( - () => (isRunning ? job.id : (finishedStem || job.id)), + () => (isRunning ? job.id : finishedStem || job.id), [isRunning, job.id, finishedStem] ) @@ -467,14 +522,12 @@ export default function Player({ const file = React.useMemo(() => stripHotPrefix(fileRaw), [fileRaw]) const runtimeLabel = React.useMemo(() => { - 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) { - return formatDuration(end - start) - } - const sec = (job as any).durationSeconds - if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) return formatDuration(sec * 1000) - return '—' + const sec = + Number((job as any)?.meta?.durationSeconds) || + Number((job as any)?.durationSeconds) || + 0 + + return sec > 0 ? formatDuration(sec * 1000) : '—' }, [job]) // Datum: bevorzugt aus Dateiname, sonst startedAt/endedAt/createdAt — ✅ inkl. Uhrzeit @@ -525,10 +578,6 @@ export default function Player({ setPreviewSrc(previewA) }, [previewA]) - const videoW = React.useMemo( - () => pickNum(anyJob.videoWidth, anyJob.width, anyJob.meta?.width), - [anyJob.videoWidth, anyJob.width, anyJob.meta?.width] - ) const videoH = React.useMemo( () => pickNum(anyJob.videoHeight, anyJob.height, anyJob.meta?.height), [anyJob.videoHeight, anyJob.height, anyJob.meta?.height] @@ -538,7 +587,9 @@ export default function Player({ [anyJob.fps, anyJob.frameRate, anyJob.meta?.fps, anyJob.meta?.frameRate] ) - const resolutionLabel = React.useMemo(() => formatResolution(videoW, videoH), [videoW, videoH]) + const [intrH, setIntrH] = React.useState(null) + + const resolutionLabel = React.useMemo(() => formatResolution(intrH ?? videoH), [intrH, videoH]) const fpsLabel = React.useMemo(() => formatFps(fps), [fps]) React.useEffect(() => { @@ -552,7 +603,7 @@ export default function Player({ return apiUrl(isRunning ? `${u}&t=${Date.now()}` : u) }, [previewId, isRunning]) - React.useEffect(() => { + React.useEffect(() => { if (!isRunning) { setHlsReady(false) return @@ -578,9 +629,7 @@ export default function Player({ // ✅ muss wirklich wie eine m3u8 aussehen und mindestens 1 Segment enthalten const hasM3u = text.includes('#EXTM3U') const hasSegment = - /#EXTINF:/i.test(text) || - /\.ts(\?|$)/i.test(text) || - /\.m4s(\?|$)/i.test(text) + /#EXTINF:/i.test(text) || /\.ts(\?|$)/i.test(text) || /\.m4s(\?|$)/i.test(text) if (hasM3u && hasSegment) { if (alive) setHlsReady(true) @@ -599,23 +648,62 @@ export default function Player({ } }, [isRunning, hlsIndexUrl]) - const buildVideoSrc = React.useCallback((params: { file?: string; id?: string; quality?: string }) => { - const q = String(params.quality || 'auto') + const buildVideoSrc = React.useCallback( + (params: { file?: string; id?: string; quality?: string; startSec?: number }) => { + const q = String(params.quality || 'auto').trim() - // ✅ query params sauber bauen - const qp = new URLSearchParams() - if (params.file) qp.set('file', params.file) - if (params.id) qp.set('id', params.id) + const startSec = + typeof params.startSec === 'number' && Number.isFinite(params.startSec) && params.startSec > 0 + ? Math.floor(params.startSec) + : 0 - if (q && q !== 'auto') { - qp.set('quality', q) - qp.set('stream', '1') // ✅ HIER stream aktivieren (nur wenn quality gewählt) - } + // ✅ query params sauber bauen + const qp = new URLSearchParams() + if (params.file) qp.set('file', params.file) + if (params.id) qp.set('id', params.id) - return apiUrl(`/api/record/video?${qp.toString()}`) - }, []) - - const [selectedQuality, setSelectedQuality] = React.useState('auto') + const qToH = (qq: string): number => { + const m = String(qq).match(/(\d{3,4})p/i) + return m ? Number(m[1]) : 0 + } + + // Quelle (für Downscale-Erkennung) + const sourceH = + typeof videoH === 'number' && Number.isFinite(videoH) && videoH > 0 ? Math.round(videoH) : 0 + + if (q && q !== 'auto') { + qp.set('quality', q) + + // ✅ stream=1 nur für "Start bei 0" (schneller Start ohne Full-Transcode) + // Bei startSec>0 wollen wir i.d.R. Segment-Cache + Range (besseres Seek/Quality-Switch) + const targetH = qToH(q) + if (startSec === 0 && sourceH && targetH && targetH < sourceH - 8) { + qp.set('stream', '1') + } + } + + if (startSec > 0) { + qp.set('t', String(startSec)) // oder qp.set('start', String(startSec)) + } + + return apiUrl(`/api/record/video?${qp.toString()}`) + }, + [videoH] + ) + + // ✅ requested = UI (Auto oder fix), applied = echte Source-Qualität + const [requestedQuality, setRequestedQuality] = React.useState('auto') + const [appliedQuality, setAppliedQuality] = React.useState('auto') + + const requestedQualityRef = React.useRef(requestedQuality) + React.useEffect(() => { + requestedQualityRef.current = requestedQuality + }, [requestedQuality]) + + const appliedQualityRef = React.useRef(appliedQuality) + React.useEffect(() => { + appliedQualityRef.current = appliedQuality + }, [appliedQuality]) const media = React.useMemo(() => { // ✅ Live wird NICHT mehr über Video.js gespielt @@ -625,44 +713,59 @@ export default function Player({ if (file) { const ext = file.toLowerCase().split('.').pop() const type = - ext === 'mp4' ? 'video/mp4' : - ext === 'ts' ? 'video/mp2t' : - 'application/octet-stream' - return { src: buildVideoSrc({ file, quality: selectedQuality }), type } + ext === 'mp4' ? 'video/mp4' : ext === 'ts' ? 'video/mp2t' : 'application/octet-stream' + return { src: buildVideoSrc({ file, quality: appliedQuality }), type } } - return { src: buildVideoSrc({ id: job.id, quality: selectedQuality }), type: 'video/mp4' } - }, [isRunning, job.output, job.id, selectedQuality, buildVideoSrc]) + return { src: buildVideoSrc({ id: job.id, quality: appliedQuality }), type: 'video/mp4' } + }, [isRunning, job.output, job.id, appliedQuality, buildVideoSrc]) const containerRef = React.useRef(null) const playerRef = React.useRef(null) const videoNodeRef = React.useRef(null) + const skipNextMediaSrcRef = React.useRef(false) const [mounted, setMounted] = React.useState(false) - const [playerReadyTick, setPlayerReadyTick] = React.useState(0) + const updateIntrinsicDims = React.useCallback(() => { + const p: any = playerRef.current + if (!p || p.isDisposed?.()) return + const h = typeof p.videoHeight === 'function' ? p.videoHeight() : 0 + if (typeof h === 'number' && h > 0 && Number.isFinite(h)) { + setIntrH(h) + } + }, []) + // pro Datei einmal default setzen (damit beim nächsten Video wieder sinnvoll startet) const playbackKey = React.useMemo(() => { // finished: Dateiname; running ist eh LiveHlsVideo, also egal return baseName(job.output?.trim() || '') || job.id }, [job.output, job.id]) - const supportedQualities = React.useMemo( - () => gearQualitiesForHeight(videoH, ['1080p', '720p', '480p']), - [videoH] - ) - const defaultQuality = React.useMemo(() => { - const metaQ = qualityFromHeight(videoH) - return supportedQualities.includes(metaQ) ? metaQ : 'auto' - }, [supportedQualities, videoH]) + const h = typeof videoH === 'number' && Number.isFinite(videoH) && videoH > 0 ? Math.round(videoH) : 0 + return h ? `${h}p` : 'auto' + }, [videoH]) const lastPlaybackKeyRef = React.useRef('') + React.useEffect(() => { if (lastPlaybackKeyRef.current !== playbackKey) { lastPlaybackKeyRef.current = playbackKey - setSelectedQuality(defaultQuality) + setRequestedQuality(defaultQuality) + setAppliedQuality(defaultQuality) + setIntrH(null) + + // player-Optionen syncen, falls schon gemountet + const p: any = playerRef.current + if (p && !p.isDisposed?.()) { + try { + p.options_.__gearQuality = defaultQuality + p.options_.__autoAppliedQuality = defaultQuality + p.trigger?.('gear:refresh') + } catch {} + } } }, [playbackKey, defaultQuality]) @@ -676,7 +779,6 @@ export default function Player({ const bump = () => setVvTick((x) => x + 1) - // bump once + listen bump() vv.addEventListener('resize', bump) vv.addEventListener('scroll', bump) @@ -692,9 +794,8 @@ export default function Player({ }, []) const [controlBarH, setControlBarH] = React.useState(56) - const [portalTarget, setPortalTarget] = React.useState(null) - + const mini = !expanded type WinRect = { x: number; y: number; w: number; h: number } @@ -742,49 +843,262 @@ export default function Player({ } }, [mounted, expanded]) - React.useEffect(() => { - const p = playerRef.current - if (!p || (p as any).isDisposed?.()) return - - const onQ = (ev: any) => { - const q = String(ev?.quality ?? 'auto') - - // nur für finished (Video.js läuft da) + // ✅ zentrale Umschalt-Funktion (Quality Switch, inkl. t= Segment) + const applyQualitySwitch = React.useCallback( + (p: any, fileName: string, nextQ: string) => { + if (isRunning) return + + installAbsoluteTimelineShim(p) + + const wasPaused = Boolean(p.paused?.()) + + // absolute Zeit (Shim) + const absNow = Number(p.currentTime?.() ?? 0) || 0 + const startSec = absNow > 0 ? Math.floor(absNow / 2) * 2 : 0 + const rel = absNow - startSec + + p.__timeOffsetSec = startSec + + // media-effect darf nicht direkt danach drüberbügeln + skipNextMediaSrcRef.current = true + + // ✅ applied wechseln + setAppliedQuality(nextQ) + + // fürs Label "Auto (720p)" + p.options_.__autoAppliedQuality = nextQ + + const nextSrc = buildVideoSrc({ + file: fileName, + quality: nextQ, + startSec, + }) + + const knownFull = + Number((job as any)?.meta?.durationSeconds) || + Number((anyJob as any)?.meta?.durationSeconds) || + Number((job as any)?.durationSeconds) || + 0 + if (knownFull > 0) p.__fullDurationSec = knownFull + + try { + const prev = p.__onLoadedMetaQSwitch + if (prev) p.off('loadedmetadata', prev) + } catch {} + + const onLoadedMeta = () => { + updateIntrinsicDims() + + if (!(Number(p.__fullDurationSec) > 0)) { + try { + const segDur = Number(p.__origDuration?.() ?? 0) || 0 + if (segDur > 0) p.__fullDurationSec = startSec + segDur + } catch {} + } + + try { + p.__setRelativeTime?.(rel) + } catch {} + try { + p.trigger?.('timeupdate') + } catch {} + + // Auto-label refresh + try { + p.trigger?.('gear:refresh') + } catch {} + + if (!wasPaused) { + const ret = p.play?.() + if (ret && typeof ret.catch === 'function') ret.catch(() => {}) + } + } + + p.__onLoadedMetaQSwitch = onLoadedMeta + p.one('loadedmetadata', onLoadedMeta) + + try { + p.src({ src: nextSrc, type: 'video/mp4' }) + } catch {} + try { + p.load?.() + } catch {} + }, + [isRunning, buildVideoSrc, updateIntrinsicDims, job, anyJob] + ) + + // ✅ Gear-Auswahl: requestedQuality setzen, bei manual sofort umschalten + React.useEffect(() => { + const p = playerRef.current as any + if (!p || p.isDisposed?.()) return + + installAbsoluteTimelineShim(p) + + const onQ = (ev: any) => { + const q = String(ev?.quality ?? 'auto').trim() if (isRunning) return - // ✅ Beispiel: Backend liefert je nach quality ein anderes File/Transcode - // Du musst backendseitig unterstützen: /api/record/video?file=...&quality=720p const fileName = baseName(job.output?.trim() || '') if (!fileName) return - const ct = p.currentTime?.() || 0 - const wasPaused = p.paused?.() ?? false + // requested immer updaten (UI) + setRequestedQuality(q) - setSelectedQuality(q) + // Auto: applied bleibt erstmal wie aktuell + if (q === 'auto') { + try { + p.options_.__gearQuality = 'auto' + p.options_.__autoAppliedQuality = appliedQualityRef.current || defaultQuality + p.trigger?.('gear:refresh') + } catch {} + return + } - const nextSrc = buildVideoSrc({ file: fileName, quality: q }) + // Manual: direkt umschalten + try { + p.options_.__gearQuality = q + p.options_.__autoAppliedQuality = q + p.trigger?.('gear:refresh') + } catch {} - // src wechseln - try { p.src({ src: nextSrc, type: 'video/mp4' }) } catch {} - - p.one('loadedmetadata', () => { - console.log('[Player] loadedmetadata after switch', { - h: typeof (p as any).videoHeight === 'function' ? (p as any).videoHeight() : null, - w: typeof (p as any).videoWidth === 'function' ? (p as any).videoWidth() : null, - }) - try { if (ct > 0) p.currentTime(ct) } catch {} - if (!wasPaused) { - const ret = p.play?.() - if (ret && typeof (ret as any).catch === 'function') (ret as any).catch(() => {}) - } - }) + applyQualitySwitch(p, fileName, q) } p.on('gear:quality', onQ) return () => { - try { p.off('gear:quality', onQ) } catch {} + try { + p.off('gear:quality', onQ) + } catch {} } - }, [playerReadyTick, job.output, isRunning, buildVideoSrc]) + }, [playerReadyTick, job.output, isRunning, applyQualitySwitch, defaultQuality]) + + // ✅ Auto-Controller: buffer/stall-basiert hoch/runter + React.useEffect(() => { + if (!mounted) return + if (isRunning) return + if (requestedQuality !== 'auto') return + + const p: any = playerRef.current + if (!p || p.isDisposed?.()) return + + installAbsoluteTimelineShim(p) + + const fileName = baseName(job.output?.trim() || '') + if (!fileName) return + + const getLadder = (): string[] => { + const q = (p.options_?.gearQualities || gearQualitiesForHeight(intrH ?? videoH)) as string[] + return q.filter((x) => x && x !== 'auto') + } + + const qToNum = (qq: string) => { + const m = String(qq).match(/(\d{3,4})p/i) + return m ? Number(m[1]) : 0 + } + + const sortDesc = (arr: string[]) => [...arr].sort((a, b) => qToNum(b) - qToNum(a)) + + const pickLower = (cur: string, ladder: string[]) => { + const L = sortDesc(ladder) + const curN = qToNum(cur) + for (let i = 0; i < L.length; i++) { + const n = qToNum(L[i]) + if (n > 0 && n < curN - 8) return L[i] + } + return L[L.length - 1] || cur + } + + const pickHigher = (cur: string, ladder: string[]) => { + const L = sortDesc(ladder) + const curN = qToNum(cur) + for (let i = L.length - 1; i >= 0; i--) { + const n = qToNum(L[i]) + if (n > curN + 8) return L[i] + } + return L[0] || cur + } + + let lastStallAt = 0 + let lastSwitchAt = 0 + let stableSince = 0 + + const onStall = () => { + lastStallAt = Date.now() + } + p.on('waiting', onStall) + p.on('stalled', onStall) + + const getBufferAheadSec = () => { + try { + const relNow = Number(p.__origCurrentTime?.() ?? 0) || 0 + const buf = p.buffered?.() + if (!buf || buf.length <= 0) return 0 + const end = buf.end(buf.length - 1) + return Math.max(0, (Number(end) || 0) - relNow) + } catch { + return 0 + } + } + + const tick = () => { + const now = Date.now() + if (now - lastSwitchAt < 8000) return // hysteresis + + const ladder = getLadder() + if (!ladder.length) return + + const cur = appliedQualityRef.current && appliedQualityRef.current !== 'auto' ? appliedQualityRef.current : ladder[0] + const ahead = getBufferAheadSec() + const recentlyStalled = now - lastStallAt < 2500 + + // downgrade schnell, wenn buffer knapp / stall + if (ahead < 4 || recentlyStalled) { + const next = pickLower(cur, ladder) + if (next && next !== cur) { + lastSwitchAt = now + stableSince = 0 + try { + p.options_.__autoAppliedQuality = next + p.trigger?.('gear:refresh') + } catch {} + applyQualitySwitch(p, fileName, next) + } + return + } + + // stable => upgrade langsam + if (ahead > 20 && now - lastStallAt > 20000) { + if (!stableSince) stableSince = now + if (now - stableSince > 20000) { + const next = pickHigher(cur, ladder) + if (next && next !== cur) { + lastSwitchAt = now + stableSince = now + try { + p.options_.__autoAppliedQuality = next + p.trigger?.('gear:refresh') + } catch {} + applyQualitySwitch(p, fileName, next) + } + } + } else { + stableSince = 0 + } + } + + const id = window.setInterval(tick, 2000) + tick() + + return () => { + window.clearInterval(id) + try { + p.off('waiting', onStall) + } catch {} + try { + p.off('stalled', onStall) + } catch {} + } + }, [mounted, isRunning, requestedQuality, job.output, intrH, videoH, applyQualitySwitch]) React.useEffect(() => setMounted(true), []) @@ -814,107 +1128,150 @@ export default function Player({ }, [isDesktop]) React.useEffect(() => { - const p = playerRef.current + const p: any = playerRef.current + if (!p || p.isDisposed?.()) return + if (isRunning) return // live nutzt Video.js nicht - if (!p || (p as any).isDisposed?.()) return - if (!isLive) return - if (!media.src) return + installAbsoluteTimelineShim(p) - const seekToLive = () => { - try { - const lt = (p as any).liveTracker - if (lt && typeof lt.seekToLiveEdge === 'function') { - lt.seekToLiveEdge() + const fileName = baseName(job.output?.trim() || '') + if (!fileName) return + + // volle Dauer: nimm was du hast (durationSeconds ist bei finished normalerweise da) + const knownFull = Number((job as any).durationSeconds ?? anyJob?.meta?.durationSeconds ?? 0) || 0 + if (knownFull > 0) p.__fullDurationSec = knownFull + + // absolute server-seek + p.__serverSeekAbs = (absSec: number) => { + const abs = Math.max(0, Number(absSec) || 0) + + // ✅ effektive Quality: bei Auto die applied nehmen + const effectiveQ = + requestedQualityRef.current === 'auto' + ? String(appliedQualityRef.current || 'auto').trim() + : String(requestedQualityRef.current || 'auto').trim() + + // helper: "1080p" -> 1080 + const qToH = (qq: string): number => { + const m = String(qq).match(/(\d{3,4})p/i) + return m ? Number(m[1]) : 0 + } + + // Quelle (wie in buildVideoSrc-Logik): wenn target < source => Downscale + const sourceH = + typeof videoH === 'number' && Number.isFinite(videoH) && videoH > 0 ? Math.round(videoH) : 0 + const targetH = qToH(effectiveQ) + + const needsDownscale = + effectiveQ !== 'auto' && sourceH > 0 && targetH > 0 && targetH < sourceH - 8 + + // ✅ 1) NICHT runterskalieren => NUR client seek (kein FFmpeg) + if (!needsDownscale) { + const wasPaused = Boolean(p.paused?.()) + const off = Number(p.__timeOffsetSec ?? 0) || 0 + const curSrc = String(p.currentSrc?.() || '') + const isSegmented = off > 0 || curSrc.includes('t=') || curSrc.includes('start=') + + if (isSegmented) { + p.__timeOffsetSec = 0 + + const nextSrc = buildVideoSrc({ + file: fileName, + quality: effectiveQ, + // startSec absichtlich NICHT setzen + }) + + const onMeta = () => { + updateIntrinsicDims() + try { + p.__origCurrentTime?.(abs) + try { + p.trigger?.('timeupdate') + } catch {} + } catch { + try { + p.currentTime?.(abs) + } catch {} + } + if (!wasPaused) { + const ret = p.play?.() + if (ret && typeof ret.catch === 'function') ret.catch(() => {}) + } + } + + try { + p.one('loadedmetadata', onMeta) + } catch {} + try { + p.src({ src: nextSrc, type: 'video/mp4' }) + } catch {} + try { + p.load?.() + } catch {} return } - // Fallback: direkt auf liveCurrentTime - const liveNow = lt?.liveCurrentTime?.() - if (typeof liveNow === 'number' && Number.isFinite(liveNow) && liveNow > 0) { - // minimaler Offset, um direkt wieder zu “buffer underrun” zu vermeiden - p.currentTime(Math.max(0, liveNow - 0.2)) + + try { + p.__origCurrentTime?.(abs) + try { + p.trigger?.('timeupdate') + } catch {} + } catch { + try { + p.currentTime?.(abs) + } catch {} } + return + } + + // ✅ 2) Downscale aktiv => Server-Seek (Segment) + const wasPaused = Boolean(p.paused?.()) + const startSec = Math.floor(abs / 2) * 2 + const rel = abs - startSec + + p.__timeOffsetSec = startSec + + const nextSrc = buildVideoSrc({ + file: fileName, + quality: effectiveQ, + startSec, + }) + + const onMeta = () => { + updateIntrinsicDims() + p.__setRelativeTime?.(rel) + try { + p.trigger?.('timeupdate') + } catch {} + if (!wasPaused) { + const ret = p.play?.() + if (ret && typeof ret.catch === 'function') ret.catch(() => {}) + } + } + + try { + p.one('loadedmetadata', onMeta) + } catch {} + try { + p.src({ src: nextSrc, type: 'video/mp4' }) + } catch {} + try { + p.load?.() } catch {} } - // 1) Beim Laden sofort an Live-Edge - const onMeta = () => seekToLive() - p.on('loadedmetadata', onMeta) - - // 2) Auch beim Play nochmal (manche Browser sind da zickig) - const onPlay = () => seekToLive() - p.on('playing', onPlay) - - // 3) “Stay live”: wenn wir zu weit hinten sind, nachziehen - const t = window.setInterval(() => { - try { - if (p.paused()) return - if ((p as any).seeking?.()) return - - const lt = (p as any).liveTracker - const liveNow = lt?.liveCurrentTime?.() - if (typeof liveNow !== 'number' || !Number.isFinite(liveNow)) return - - const cur = p.currentTime() || 0 - const behind = liveNow - cur - - // ✅ wenn > 4s hinter Live -> nachziehen - if (behind > 4) { - p.currentTime(Math.max(0, liveNow - 0.2)) - } - } catch {} - }, 1500) - - // einmal sofort - seekToLive() - return () => { - try { p.off('loadedmetadata', onMeta) } catch {} - try { p.off('playing', onPlay) } catch {} - window.clearInterval(t) - } - }, [isLive, media.src, media.type]) - - React.useEffect(() => { - const p = playerRef.current - if (!p || (p as any).isDisposed?.()) return - if (!isRunning || !hlsReady) return - - let lastT = -1 - let lastWall = Date.now() - - const tick = window.setInterval(() => { try { - if (p.paused()) return - const ct = p.currentTime() || 0 - - // wenn Zeit nicht weiterläuft - if (ct <= lastT + 0.01) { - const stuckFor = Date.now() - lastWall - if (stuckFor > 4000) { - const lt = (p as any).liveTracker - if (lt?.seekToLiveEdge) { - lt.seekToLiveEdge() - } else { - // fallback: kleiner hop nach vorne - p.currentTime(Math.max(0, ct + 0.5)) - } - lastWall = Date.now() - } - } else { - lastT = ct - lastWall = Date.now() - } + delete p.__serverSeekAbs } catch {} - }, 1000) - - return () => window.clearInterval(tick) - }, [isRunning, hlsReady]) + } + }, [playerReadyTick, job.output, isRunning, buildVideoSrc, updateIntrinsicDims, anyJob, job, videoH]) React.useLayoutEffect(() => { if (!mounted) return if (!containerRef.current) return if (playerRef.current) return - if (isRunning) return // ✅ neu: für Live keinen Video.js mounten + if (isRunning) return // ✅ neu: für Live keinen Video.js mounten const videoEl = document.createElement('video') videoEl.className = 'video-js vjs-big-play-centered w-full h-full' @@ -925,11 +1282,15 @@ export default function Player({ ensureGearControlRegistered() - const initialGearQualities = gearQualitiesForHeight(videoH, ['1080p', '720p', '480p']) + const initialGearQualities = gearQualitiesForHeight(videoH) - const metaQuality = qualityFromHeight(videoH) - const initialSelectedQuality = initialGearQualities.includes(metaQuality) ? metaQuality : 'auto' - setSelectedQuality(initialSelectedQuality) + const initialSelectedQuality = (() => { + const h = typeof videoH === 'number' && Number.isFinite(videoH) && videoH > 0 ? Math.round(videoH) : 0 + return h ? `${h}p` : 'auto' + })() + + setRequestedQuality(initialSelectedQuality) + setAppliedQuality(initialSelectedQuality) const p = videojs(videoEl, { autoplay: true, @@ -940,21 +1301,17 @@ export default function Player({ responsive: true, fluid: false, fill: true, - - // ✅ Live UI (wir verstecken zwar die Seekbar, aber LiveTracker ist nützlich) liveui: false, - // ✅ optional: VHS Low-Latency (wenn deine Video.js-Version es unterstützt) html5: { - vhs: { - lowLatencyMode: true, - }, + vhs: { lowLatencyMode: true }, }, inactivityTimeout: 0, - + gearQualities: initialGearQualities, __gearQuality: initialSelectedQuality, + __autoAppliedQuality: initialSelectedQuality, controlBar: { skipButtons: { backward: 10, forward: 10 }, @@ -978,21 +1335,35 @@ export default function Player({ }) playerRef.current = p - setPlayerReadyTick((x) => x + 1) p.one('loadedmetadata', () => { + updateIntrinsicDims() try { - const h = - typeof (p as any).videoHeight === 'function' - ? (p as any).videoHeight() - : 0 - - const next = gearQualitiesForHeight(h, ['1080p', '720p', '480p']) + const h = typeof (p as any).videoHeight === 'function' ? (p as any).videoHeight() : 0 + const next = gearQualitiesForHeight(h) ;(p as any).options_.gearQualities = next - const metaQ = qualityFromHeight(h) - ;(p as any).options_.__gearQuality = next.includes(metaQ) ? metaQ : 'auto' + const curReq = String((p as any).options_.__gearQuality ?? 'auto') + const native = + typeof h === 'number' && Number.isFinite(h) && h > 0 ? `${Math.round(h)}p` : 'auto' + + const nextReq = next.includes(curReq) ? curReq : next.includes(native) ? native : 'auto' + + ;(p as any).options_.__gearQuality = nextReq + + // state sync + setRequestedQuality(nextReq) + if (nextReq !== 'auto') { + setAppliedQuality(nextReq) + ;(p as any).options_.__autoAppliedQuality = nextReq + } else { + // Auto gewählt: applied falls noch auto -> native + const curApplied = String(appliedQualityRef.current || 'auto') + const nextApplied = curApplied !== 'auto' ? curApplied : native !== 'auto' ? native : 'auto' + setAppliedQuality(nextApplied) + ;(p as any).options_.__autoAppliedQuality = nextApplied + } p.trigger('gear:refresh') } catch {} @@ -1019,7 +1390,7 @@ export default function Player({ } } } - }, [mounted, startMuted, isRunning, videoH]) + }, [mounted, startMuted, isRunning, videoH, updateIntrinsicDims]) React.useEffect(() => { const p = playerRef.current @@ -1037,6 +1408,12 @@ export default function Player({ const p = playerRef.current if (!p || (p as any).isDisposed?.()) return + // ✅ src wurde gerade manuell (Quality-Wechsel mit t=...) gesetzt -> einmaligen Auto-Apply überspringen + if (skipNextMediaSrcRef.current) { + skipNextMediaSrcRef.current = false + return + } + const t = p.currentTime() || 0 p.muted(startMuted) @@ -1049,6 +1426,12 @@ export default function Player({ return } + ;(p as any).__timeOffsetSec = 0 + + // volle Dauer kennen wir bei finished meistens schon: + const knownFull = Number((job as any).durationSeconds ?? (job as any).meta?.durationSeconds ?? 0) || 0 + ;(p as any).__fullDurationSec = knownFull + p.src({ src: media.src, type: media.type }) const tryPlay = () => { @@ -1060,14 +1443,38 @@ export default function Player({ p.one('loadedmetadata', () => { if ((p as any).isDisposed?.()) return - try { p.playbackRate(1) } catch {} + updateIntrinsicDims() + + // ✅ volle Dauer: aus bekannten Daten (nicht aus p.duration()) + try { + const knownFull = Number((job as any).durationSeconds ?? anyJob?.meta?.durationSeconds ?? 0) || 0 + if (knownFull > 0) (p as any).__fullDurationSec = knownFull + } catch {} + + try { + p.playbackRate(1) + } catch {} + const isHls = /mpegurl/i.test(media.type) - if (t > 0 && !isHls) p.currentTime(t) + + // ✅ initiale Position wiederherstellen, aber RELATIV (ohne server-seek) + if (t > 0 && !isHls) { + try { + const off = Number((p as any).__timeOffsetSec ?? 0) || 0 + const rel = Math.max(0, t - off) + ;(p as any).__setRelativeTime?.(rel) + } catch {} + } + + try { + p.trigger?.('timeupdate') + } catch {} + tryPlay() }) tryPlay() - }, [mounted, media.src, media.type, startMuted]) + }, [mounted, media.src, media.type, startMuted, updateIntrinsicDims, job, anyJob]) React.useEffect(() => { if (!mounted) return @@ -1138,7 +1545,7 @@ export default function Player({ return () => window.removeEventListener('player:close', onCloseIfFile as EventListener) }, [job.output, releaseMedia, onClose]) - const getViewport = () => { + const getViewport = () => { if (typeof window === 'undefined') return { w: 0, h: 0, ox: 0, oy: 0, bottomInset: 0 } const vv = window.visualViewport @@ -1161,7 +1568,7 @@ export default function Player({ return { w, h, ox: 0, oy: 0, bottomInset: 0 } } - const clampRect = React.useCallback((r: WinRect, ratio?: number): WinRect => { + const clampRect = React.useCallback((r: { x: number; y: number; w: number; h: number }, ratio?: number) => { if (typeof window === 'undefined') return r const { w: vw, h: vh } = getViewport() @@ -1199,24 +1606,15 @@ export default function Player({ return { x, y, w, h } }, []) - const loadRect = React.useCallback((): WinRect => { + const loadRect = React.useCallback(() => { if (typeof window === 'undefined') return { x: MARGIN, y: MARGIN, w: DEFAULT_W, h: DEFAULT_H } try { const raw = window.localStorage.getItem(WIN_KEY) if (raw) { - const v = JSON.parse(raw) as Partial - if ( - typeof v.x === 'number' && - typeof v.y === 'number' && - typeof v.w === 'number' && - typeof v.h === 'number' - ) { - const w = v.w - const h = v.h - const x = v.x - const y = v.y - return clampRect({ x, y, w, h }, w / h) + const v = JSON.parse(raw) as Partial<{ x: number; y: number; w: number; h: number }> + if (typeof v.x === 'number' && typeof v.y === 'number' && typeof v.w === 'number' && typeof v.h === 'number') { + return clampRect({ x: v.x, y: v.y, w: v.w, h: v.h }, v.w / v.h) } } } catch {} @@ -1285,7 +1683,6 @@ export default function Player({ // pointermove sehr häufig -> 1x pro Frame committen const dragRafRef = React.useRef(null) const pendingPosRef = React.useRef<{ x: number; y: number } | null>(null) - const draggingRef = React.useRef(null) const applySnap = React.useCallback((r: WinRect): WinRect => { @@ -1293,10 +1690,8 @@ export default function Player({ const leftEdge = MARGIN const rightEdge = vw - r.w - MARGIN const bottomEdge = vh - r.h - MARGIN - const centerX = r.x + r.w / 2 const dockLeft = centerX < vw / 2 - return { ...r, x: dockLeft ? leftEdge : rightEdge, y: bottomEdge } }, []) @@ -1367,10 +1762,7 @@ export default function Player({ // pointermove kommt extrem oft -> wir committen max. 1x pro Frame const resizeRafRef = React.useRef(null) const pendingRectRef = React.useRef(null) - - const resizingRef = React.useRef( - null - ) + const resizingRef = React.useRef(null) const onResizeMove = React.useCallback( (ev: PointerEvent) => { @@ -1397,8 +1789,8 @@ export default function Player({ const startRight = s.start.x + s.start.w const startBottom = s.start.y + s.start.h - const anchoredRight = Math.abs((vw - MARGIN) - startRight) <= EDGE_SNAP - const anchoredBottom = Math.abs((vh - MARGIN) - startBottom) <= EDGE_SNAP + const anchoredRight = Math.abs(vw - MARGIN - startRight) <= EDGE_SNAP + const anchoredBottom = Math.abs(vh - MARGIN - startBottom) <= EDGE_SNAP const fitFromW = (newW: number) => { newW = Math.max(MIN_W, newW) @@ -1554,10 +1946,10 @@ export default function Player({ setStopPending(false) } }} - className={cn('shadow-none shrink-0', isNarrowMini && 'px-2')} + className={cn('shadow-none shrink-0', miniDesktop && isNarrowMini && 'px-2')} > - {isStoppingLike || stopPending ? 'Stoppe…' : isNarrowMini ? 'Stop' : 'Stoppen'} + {isStoppingLike || stopPending ? 'Stoppe…' : miniDesktop && isNarrowMini ? 'Stop' : 'Stoppen'} @@ -1633,7 +2025,6 @@ export default function Player({ ) const fullSize = expanded || miniDesktop - const liveBottom = `env(safe-area-inset-bottom)` const vjsBottom = `calc(${controlBarH}px + env(safe-area-inset-bottom))` @@ -1643,7 +2034,6 @@ export default function Player({ : `calc(${controlBarH + 8}px + env(safe-area-inset-bottom))` const topOverlayTop = miniDesktop ? 'top-4' : 'top-2' - const showSideInfo = expanded && isDesktop const videoChrome = ( @@ -1664,13 +2054,8 @@ export default function Player({
{isRunning ? (
- + - {/* LIVE badge wie im ModelPreview */}
Live @@ -1680,16 +2065,11 @@ export default function Player({
)} - - {/* ✅ Top overlay: Grid -> links Actions, Mitte Drag, rechts Window controls */} + {/* ✅ Top overlay */}
- {/* Left: actions (nur im Mini/Non-SideInfo) */} -
- {showSideInfo ? null : footerRight} -
+
{showSideInfo ? null : footerRight}
- {/* Middle: drag handle (mini desktop only) */} {miniDesktop ? ( ) : null} - {/* Right: window buttons */}
-
@@ -1765,24 +2132,27 @@ export default function Player({ >
{model}
-
{file || title}
+
+ + {file || title} + + {isHot || isHotFile ? ( + HOT + ) : null} + +
- {!isRunning && ( - {job.status} - )} - {(isHot || isHotFile) ? ( - - HOT - + {resolutionLabel !== '—' ? ( + {resolutionLabel} ) : null} - {!isRunning && ( + + {!isRunning ? ( {runtimeLabel} - )} - {sizeLabel !== '—' ? ( - {sizeLabel} ) : null} + + {sizeLabel !== '—' ? {sizeLabel} : null}
@@ -1792,7 +2162,6 @@ export default function Player({ const sidePanel = (
- {/* Vorschaubild ganz oben */}
{/* eslint-disable-next-line @next/next/no-img-element */} @@ -1802,20 +2171,17 @@ export default function Player({ className="absolute inset-0 h-full w-full object-cover" loading="lazy" onError={() => { - // fallback once if (previewSrc !== previewB) setPreviewSrc(previewB) }} />
- {/* Titel */}
{model}
{file || title}
- {/* ✅ Actions links im SidePanel (großer Player) */}
{isRunning ? ( @@ -1893,17 +2259,12 @@ export default function Player({ } : undefined } - order={ - isRunning - ? ['watch', 'favorite', 'like', 'details'] - : ['watch', 'favorite', 'like', 'hot', 'details', 'keep', 'delete'] - } + order={isRunning ? ['watch', 'favorite', 'like', 'details'] : ['watch', 'favorite', 'like', 'hot', 'details', 'keep', 'delete']} className="flex items-center justify-start gap-1" />
- {/* Infos + ✅ Tags direkt darunter (aus ModelStore) */}
Status
{job.status}
@@ -1923,15 +2284,11 @@ export default function Player({
Datum
{dateLabel}
- {/* ✅ volle Breite */}
{tags.length ? (
{tags.map((t) => ( - + {t} ))} @@ -1952,7 +2309,7 @@ export default function Player({ className={cn( 'relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10', 'w-full', - fullSize ? 'h-full' : 'h-[220px] max-h-[40vh]', // ✅ mobile mini bekommt echte Höhe + fullSize ? 'h-full' : 'h-[220px] max-h-[40vh]', expanded ? 'rounded-2xl' : miniDesktop ? 'rounded-lg' : 'rounded-none' )} bodyClassName="flex flex-col flex-1 min-h-0 p-0" @@ -1981,19 +2338,18 @@ export default function Player({ return createPortal( <> - + + {expanded || miniDesktop ? (
- {/* Kanten für Resize */} -
-
-
-
+
+
+
+
- {/* Ecken für Resize */} -
-
-
-
+
+
+
+
) : null}
) : ( - /* FIX FÜR MOBIL: - - h-60 (oder h-[240px]) gibt dem Player eine feste Höhe im Mini-Modus. - - left-0 right-0 sorgt für volle Breite auf Mobilgeräten. - - md: Overrides für Desktop-Zentrierung. - */
diff --git a/frontend/src/components/ui/RecorderSettings.tsx b/frontend/src/components/ui/RecorderSettings.tsx index 2839c7f..85217d4 100644 --- a/frontend/src/components/ui/RecorderSettings.tsx +++ b/frontend/src/components/ui/RecorderSettings.tsx @@ -21,7 +21,7 @@ type RecorderSettings = { teaserPlayback?: 'still' | 'hover' | 'all' teaserAudio?: boolean lowDiskPauseBelowGB?: number - + enableNotifications?: boolean } type DiskStatus = { @@ -47,6 +47,7 @@ const DEFAULTS: RecorderSettings = { teaserPlayback: 'hover', teaserAudio: false, lowDiskPauseBelowGB: 5, + enableNotifications: true, } type Props = { @@ -94,6 +95,7 @@ export default function RecorderSettings({ onAssetsGenerated }: Props) { teaserPlayback: (data as any).teaserPlayback ?? DEFAULTS.teaserPlayback, teaserAudio: (data as any).teaserAudio ?? DEFAULTS.teaserAudio, lowDiskPauseBelowGB: (data as any).lowDiskPauseBelowGB ?? DEFAULTS.lowDiskPauseBelowGB, + enableNotifications: (data as any).enableNotifications ?? DEFAULTS.enableNotifications, }) }) .catch(() => { @@ -186,6 +188,7 @@ export default function RecorderSettings({ onAssetsGenerated }: Props) { : DEFAULTS.teaserPlayback const teaserAudio = !!value.teaserAudio const lowDiskPauseBelowGB = Math.max(1, Math.floor(Number(value.lowDiskPauseBelowGB ?? DEFAULTS.lowDiskPauseBelowGB))) + const enableNotifications = !!value.enableNotifications setSaving(true) try { @@ -206,6 +209,7 @@ export default function RecorderSettings({ onAssetsGenerated }: Props) { teaserPlayback, teaserAudio, lowDiskPauseBelowGB, + enableNotifications, }), }) if (!res.ok) { @@ -540,6 +544,13 @@ export default function RecorderSettings({ onAssetsGenerated }: Props) { description="Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet." /> + setValue((v) => ({ ...v, enableNotifications: checked }))} + label="Benachrichtigungen" + description="Wenn aktiv, zeigt das Frontend Toasts (z.B. wenn watched Models online/live gehen oder wenn ein queued Model wieder public wird)." + /> +
diff --git a/frontend/src/components/ui/ToastProvider.tsx b/frontend/src/components/ui/ToastProvider.tsx index b26c1c7..7003a19 100644 --- a/frontend/src/components/ui/ToastProvider.tsx +++ b/frontend/src/components/ui/ToastProvider.tsx @@ -1,3 +1,5 @@ +// frontend\src\components\ui\ToastProvider.tsx + 'use client' import * as React from 'react' @@ -17,6 +19,8 @@ export type Toast = { type: ToastType title?: string message?: string + imageUrl?: string + imageAlt?: string durationMs?: number // auto close } @@ -82,126 +86,176 @@ export function ToastProvider({ defaultDurationMs?: number position?: 'bottom-right' | 'top-right' | 'bottom-left' | 'top-left' }) { - const [toasts, setToasts] = React.useState([]) + const [toasts, setToasts] = React.useState([]) + const [notificationsEnabled, setNotificationsEnabled] = React.useState(true) - 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) + const loadNotificationSetting = React.useCallback(async () => { + try { + const r = await fetch('/api/settings', { cache: 'no-store' }) + if (!r.ok) return + const data = await r.json() + setNotificationsEnabled(!!(data?.enableNotifications ?? true)) + } catch { + // ignorieren -> default true } + }, []) - return id - }, - [defaultDurationMs, maxToasts, remove] - ) + React.useEffect(() => { + // initial laden + loadNotificationSetting() - const ctx = React.useMemo(() => ({ push, remove, clear }), [push, remove, clear]) + // nach "Speichern" in Settings neu laden + const onUpdated = () => loadNotificationSetting() + window.addEventListener('recorder-settings-updated', onUpdated) + return () => window.removeEventListener('recorder-settings-updated', onUpdated) + }, [loadNotificationSetting]) - const posCls = - position === 'top-right' - ? 'items-start sm:items-start sm:justify-start' - : position === 'top-left' + // optional: wenn deaktiviert, alle aktuellen Toasts ausblenden + React.useEffect(() => { + if (!notificationsEnabled) { + // ✅ Nur nicht-Fehler ausblenden, Fehler dürfen bleiben + setToasts((prev) => prev.filter((t) => t.type === 'error')) + } + }, [notificationsEnabled]) + + 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) => { + // ✅ Errors IMMER zeigen, alles andere abhängig vom Toggle + if (!notificationsEnabled && t.type !== 'error') return '' + + 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, notificationsEnabled] + ) + + const ctx = React.useMemo(() => ({ push, remove, clear }), [push, remove, clear]) + + const posCls = + position === 'top-right' ? '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' + : 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 alignCls = + position.endsWith('left') + ? 'sm:items-start' + : 'sm:items-end' - const insetCls = - position.startsWith('top') - ? 'top-0 bottom-auto' - : 'bottom-0 top-auto' + const insetCls = + position.startsWith('top') + ? 'top-0 bottom-auto' + : 'bottom-0 top-auto' - return ( - - {children} + 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() + {/* Live region */} +
+
+
+ {toasts.map((t) => { + const { Icon, cls } = iconFor(t.type) + const title = (t.title || '').trim() || titleDefault(t.type) + const msg = (t.message || '').trim() + const img = (t.imageUrl || '').trim() + const imgAlt = (t.imageAlt || title).trim() - return ( - -
-
-
-
-
+ return ( + +
+
+
+ {img ? ( +
+ {imgAlt} +
+ ) : ( +
+
+ )} -
-

- {title} -

- {msg ? ( -

- {msg} +

+

+ {title}

- ) : null} -
+ {msg ? ( +

+ {msg} +

+ ) : null} +
- + +
-
- - ) - })} + + ) + })} +
-
- - ) + + ) } export function useToast() { diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 16c0c8b..d8a92a7 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,3 +1,5 @@ +// frontend\src\main.tsx + import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css'