diff --git a/backend/chaturbate_online.go b/backend/chaturbate_online.go new file mode 100644 index 0000000..4f71a50 --- /dev/null +++ b/backend/chaturbate_online.go @@ -0,0 +1,263 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" +) + +// Chaturbate Affiliates API (Online Rooms) +// https://chaturbate.com/affiliates/api/onlinerooms/?format=json&wm=827SM +const chaturbateOnlineRoomsURL = "https://chaturbate.com/affiliates/api/onlinerooms/?format=json&wm=827SM" + +// ChaturbateRoom bildet die Felder ab, die die Online-Rooms API liefert. +// (Du kannst das später problemlos erweitern, wenn du weitere Felder brauchst.) +type ChaturbateRoom struct { + Gender string `json:"gender"` + Location string `json:"location"` + CurrentShow string `json:"current_show"` // public / private / hidden / away + Username string `json:"username"` + RoomSubject string `json:"room_subject"` + Tags []string `json:"tags"` + IsNew bool `json:"is_new"` + NumUsers int `json:"num_users"` + NumFollowers int `json:"num_followers"` + Country string `json:"country"` + SpokenLanguages string `json:"spoken_languages"` + DisplayName string `json:"display_name"` + Birthday string `json:"birthday"` + IsHD bool `json:"is_hd"` + Age int `json:"age"` + SecondsOnline int `json:"seconds_online"` + ImageURL string `json:"image_url"` + ImageURL360 string `json:"image_url_360x270"` + ChatRoomURL string `json:"chat_room_url"` + ChatRoomURLRS string `json:"chat_room_url_revshare"` + IframeEmbed string `json:"iframe_embed"` + IframeEmbedRS string `json:"iframe_embed_revshare"` + BlockCountries string `json:"block_from_countries"` + BlockStates string `json:"block_from_states"` + Recorded string `json:"recorded"` // kommt in der API als String "true"/"false" + Slug string `json:"slug"` +} + +type chaturbateCache struct { + Rooms []ChaturbateRoom + FetchedAt time.Time + LastErr string +} + +var ( + cbHTTP = &http.Client{Timeout: 12 * time.Second} + cbMu sync.RWMutex + cb chaturbateCache +) + +func fetchChaturbateOnlineRooms(ctx context.Context) ([]ChaturbateRoom, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, chaturbateOnlineRoomsURL, nil) + if err != nil { + return nil, err + } + // ein "normaler" UA reduziert manchmal Block/Rate-Limit Probleme + req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + req.Header.Set("Accept", "application/json") + + resp, err := cbHTTP.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10)) + return nil, fmt.Errorf("chaturbate online rooms: HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(b))) + } + + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var rooms []ChaturbateRoom + if err := json.Unmarshal(data, &rooms); err != nil { + return nil, err + } + return rooms, nil +} + +// startChaturbateOnlinePoller pollt die API alle paar Sekunden, +// aber nur, wenn der Settings-Switch "useChaturbateApi" aktiviert ist. +func startChaturbateOnlinePoller() { + const interval = 5 * time.Second + + // nur loggen, wenn sich etwas ändert (sonst spammt es alle 5s) + lastLoggedCount := -1 + lastLoggedErr := "" + + // sofort ein initialer Tick + first := time.NewTimer(0) + defer first.Stop() + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-first.C: + case <-ticker.C: + } + + if !getSettings().UseChaturbateAPI { + continue + } + + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + rooms, err := fetchChaturbateOnlineRooms(ctx) + cancel() + + cbMu.Lock() + if err != nil { + // ❗️WICHTIG: bei Fehler NICHT fetchedAt aktualisieren, + // sonst wirkt der Cache "frisch", obwohl rooms alt sind. + cb.LastErr = err.Error() + + // ❗️Damit offline Models nicht hängen bleiben: rooms leeren + cb.Rooms = nil + + cbMu.Unlock() + + if cb.LastErr != lastLoggedErr { + fmt.Println("❌ [chaturbate] online rooms fetch failed:", cb.LastErr) + lastLoggedErr = cb.LastErr + } + continue + } + + // ✅ Erfolg: komplette Liste ersetzen + fetchedAt setzen + cb.LastErr = "" + cb.Rooms = rooms + cb.FetchedAt = time.Now() + cbMu.Unlock() + + cb.LastErr = "" + cb.Rooms = rooms + cbMu.Unlock() + + // success logging only on changes + if lastLoggedErr != "" { + fmt.Println("✅ [chaturbate] online rooms fetch recovered") + lastLoggedErr = "" + } + if len(rooms) != lastLoggedCount { + fmt.Println("✅ [chaturbate] online rooms:", len(rooms)) + lastLoggedCount = len(rooms) + } + } +} + +func chaturbateOnlineHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Nur GET erlaubt", http.StatusMethodNotAllowed) + return + } + + enabled := getSettings().UseChaturbateAPI + + if !enabled { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "enabled": false, + "fetchedAt": time.Time{}, + "count": 0, + "lastError": "", + "rooms": []ChaturbateRoom{}, + }) + return + } + + // optional: ?refresh=1 triggert einen direkten Fetch (falls aktiviert) + q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("refresh"))) + wantRefresh := q == "1" || q == "true" || q == "yes" + + // Snapshot des Caches + cbMu.RLock() + rooms := cb.Rooms + fetchedAt := cb.FetchedAt + lastErr := cb.LastErr + cbMu.RUnlock() + + // Wenn aktiviert aber Cache noch nie gefüllt wurde, einmalig automatisch fetchen. + // (Das verhindert das "count=0 / fetchedAt=0001" Verhalten direkt nach Neustart.) + const staleAfter = 20 * time.Second + isStale := fetchedAt.IsZero() || time.Since(fetchedAt) > staleAfter + + if enabled && (wantRefresh || isStale) { + + ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) + freshRooms, err := fetchChaturbateOnlineRooms(ctx) + cancel() + cbMu.Lock() + if err != nil { + cb.LastErr = err.Error() + + // ❗️WICHTIG: keine alten rooms weitergeben + cb.Rooms = nil + + // ❗️FetchedAt NICHT aktualisieren (bleibt letzte erfolgreiche Zeit) + } else { + cb.LastErr = "" + cb.Rooms = freshRooms + cb.FetchedAt = time.Now() + } + + rooms = cb.Rooms + fetchedAt = cb.FetchedAt + lastErr = cb.LastErr + cbMu.Unlock() + + } + + // nil-slice vermeiden -> Frontend bekommt [] statt null + if rooms == nil { + rooms = []ChaturbateRoom{} + } + + // optional: ?show=public,private,hidden,away + showFilter := strings.TrimSpace(r.URL.Query().Get("show")) + if showFilter != "" { + allowed := map[string]bool{} + for _, s := range strings.Split(showFilter, ",") { + s = strings.ToLower(strings.TrimSpace(s)) + if s != "" { + allowed[s] = true + } + } + if len(allowed) > 0 { + filtered := make([]ChaturbateRoom, 0, len(rooms)) + for _, rm := range rooms { + if allowed[strings.ToLower(strings.TrimSpace(rm.CurrentShow))] { + filtered = append(filtered, rm) + } + } + rooms = filtered + } + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + + // Wir liefern ein kleines Meta-Objekt, damit du im UI sofort siehst, ob der Cache aktuell ist. + out := map[string]any{ + "enabled": enabled, + "fetchedAt": fetchedAt, + "count": len(rooms), + "lastError": lastErr, + "rooms": rooms, + } + _ = json.NewEncoder(w).Encode(out) +} diff --git a/backend/cookies_api.go b/backend/cookies_api.go new file mode 100644 index 0000000..ac1b16e --- /dev/null +++ b/backend/cookies_api.go @@ -0,0 +1,86 @@ +package main + +import ( + "io" + "encoding/json" + "net/http" +) + +// GET /api/cookies -> {"cookies": {"name":"value",...}} +// POST /api/cookies -> accepts either {"cookies": {...}} or a plain JSON object {...} +// DELETE /api/cookies -> clears stored cookies +func cookiesHandler(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + s := getSettings() + cookies, err := decryptCookieMap(s.EncryptedCookies) + if err != nil { + http.Error(w, "could not decrypt cookies: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{"cookies": cookies}) + return + + case http.MethodPost: + // body can be {"cookies": {...}} or just {...} + b, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "could not read body: "+err.Error(), http.StatusBadRequest) + return + } + + type payload struct { + Cookies map[string]string `json:"cookies"` + } + var p payload + if err := json.Unmarshal(b, &p); err != nil { + http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest) + return + } + cookies := p.Cookies + if cookies == nil { + // fallback: plain object + var m map[string]string + if err := json.Unmarshal(b, &m); err == nil { + cookies = m + } + } + if cookies == nil { + http.Error(w, "invalid json: expected {\"cookies\":{...}} or {...}", http.StatusBadRequest) + return + } + + blob, err := encryptCookieMap(cookies) + if err != nil { + http.Error(w, "could not encrypt cookies: "+err.Error(), http.StatusInternalServerError) + return + } + + settingsMu.Lock() + s := settings + s.EncryptedCookies = blob + settings = s + settingsMu.Unlock() + saveSettingsToDisk() + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "count": len(normalizeCookieMap(cookies))}) + return + + case http.MethodDelete: + settingsMu.Lock() + s := settings + s.EncryptedCookies = "" + settings = s + settingsMu.Unlock() + saveSettingsToDisk() + w.WriteHeader(http.StatusNoContent) + return + + default: + http.Error(w, "Nur GET/POST/DELETE erlaubt", http.StatusMethodNotAllowed) + return + } +} diff --git a/backend/cookies_crypto.go b/backend/cookies_crypto.go new file mode 100644 index 0000000..249a645 --- /dev/null +++ b/backend/cookies_crypto.go @@ -0,0 +1,149 @@ +package main + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// cookieKeyPath returns the filesystem path where the local encryption key is stored. +// The key is intentionally NOT stored in recorder_settings.json. +func cookieKeyPath() (string, error) { + // Prefer ./data (you already use it for models_store.db) + p, err := resolvePathRelativeToApp("data/cookies.key") + if err == nil && strings.TrimSpace(p) != "" { + _ = os.MkdirAll(filepath.Dir(p), 0o755) + return p, nil + } + + // Fallback: next to the executable + p2, err2 := resolvePathRelativeToApp("cookies.key") + if err2 != nil { + return "", err2 + } + _ = os.MkdirAll(filepath.Dir(p2), 0o755) + return p2, nil +} + +func loadOrCreateCookieKey() ([]byte, error) { + p, err := cookieKeyPath() + if err != nil { + return nil, err + } + + if b, err := os.ReadFile(p); err == nil { + // accept exactly 32 bytes, or trim if longer + if len(b) >= 32 { + return b[:32], nil + } + } + + key := make([]byte, 32) + if _, err := io.ReadFull(rand.Reader, key); err != nil { + return nil, err + } + // 0600 is best-effort; on Windows this is still fine. + if err := os.WriteFile(p, key, 0o600); err != nil { + return nil, err + } + return key, nil +} + +func normalizeCookieMap(in map[string]string) map[string]string { + out := map[string]string{} + for k, v := range in { + kk := strings.ToLower(strings.TrimSpace(k)) + vv := strings.TrimSpace(v) + if kk == "" || vv == "" { + continue + } + out[kk] = vv + } + return out +} + +func encryptCookieMap(cookies map[string]string) (string, error) { + clean := normalizeCookieMap(cookies) + plain, err := json.Marshal(clean) + if err != nil { + return "", err + } + return encryptBytesToBase64(plain) +} + +func decryptCookieMap(blob string) (map[string]string, error) { + blob = strings.TrimSpace(blob) + if blob == "" { + return map[string]string{}, nil + } + plain, err := decryptBase64ToBytes(blob) + if err != nil { + return nil, err + } + var out map[string]string + if err := json.Unmarshal(plain, &out); err != nil { + return nil, err + } + return normalizeCookieMap(out), nil +} + +func encryptBytesToBase64(plain []byte) (string, error) { + key, err := loadOrCreateCookieKey() + if err != nil { + return "", err + } + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + + nonce := make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return "", err + } + ciphertext := gcm.Seal(nil, nonce, plain, nil) + buf := append(nonce, ciphertext...) + return base64.StdEncoding.EncodeToString(buf), nil +} + +func decryptBase64ToBytes(blob string) ([]byte, error) { + key, err := loadOrCreateCookieKey() + if err != nil { + return nil, err + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + + buf, err := base64.StdEncoding.DecodeString(blob) + if err != nil { + return nil, err + } + ns := gcm.NonceSize() + if len(buf) < ns { + return nil, fmt.Errorf("encrypted cookies: invalid length") + } + nonce := buf[:ns] + ciphertext := buf[ns:] + plain, err := gcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + return nil, err + } + return plain, nil +} diff --git a/backend/data/cookies.key b/backend/data/cookies.key new file mode 100644 index 0000000..9be28d8 --- /dev/null +++ b/backend/data/cookies.key @@ -0,0 +1,2 @@ +GY$Oa{xkPT +iPGkkU \ No newline at end of file diff --git a/backend/data/models_store.db b/backend/data/models_store.db index 4410bda..df6cb78 100644 Binary files a/backend/data/models_store.db and b/backend/data/models_store.db differ diff --git a/backend/data/models_store.db-shm b/backend/data/models_store.db-shm index dad2464..f60b8fb 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 d208ae5..dc3fbf6 100644 Binary files a/backend/data/models_store.db-wal and b/backend/data/models_store.db-wal differ diff --git a/backend/main.go b/backend/main.go index c4330e6..f454619 100644 --- a/backend/main.go +++ b/backend/main.go @@ -51,6 +51,12 @@ type RecordJob struct { PreviewImage string `json:"-"` previewCmd *exec.Cmd `json:"-"` + // Thumbnail cache (verhindert, dass pro HTTP-Request ffmpeg läuft) + previewMu sync.Mutex `json:"-"` + previewJpeg []byte `json:"-"` + previewJpegAt time.Time `json:"-"` + previewGen bool `json:"-"` + cancel context.CancelFunc `json:"-"` } @@ -71,6 +77,11 @@ type RecorderSettings struct { AutoAddToDownloadList bool `json:"autoAddToDownloadList,omitempty"` AutoStartAddedDownloads bool `json:"autoStartAddedDownloads,omitempty"` + + UseChaturbateAPI bool `json:"useChaturbateApi,omitempty"` + + // EncryptedCookies contains base64(nonce+ciphertext) of a JSON cookie map. + EncryptedCookies string `json:"encryptedCookies,omitempty"` } var ( @@ -82,6 +93,9 @@ var ( AutoAddToDownloadList: false, AutoStartAddedDownloads: false, + + UseChaturbateAPI: false, + EncryptedCookies: "", } settingsFile = "recorder_settings.json" ) @@ -209,6 +223,9 @@ func recordSettingsHandler(w http.ResponseWriter, r *http.Request) { return } + current := getSettings() + in.EncryptedCookies = current.EncryptedCookies + settingsMu.Lock() settings = in settingsMu.Unlock() @@ -523,48 +540,69 @@ func recordPreview(w http.ResponseWriter, r *http.Request) { jobsMu.Unlock() if ok { - // 1️⃣ Bevorzugt: aktuelles Bild aus HLS-Preview-Segmenten - previewDir := strings.TrimSpace(job.PreviewDir) - if previewDir != "" { - if img, err := extractLastFrameFromPreviewDir(previewDir); err == nil { - // dynamischer Snapshot – Frontend hängt ?v=... dran, - // damit der Browser ihn neu lädt - servePreviewJPEGBytes(w, img) - return - } + // ✅ Thumbnail-Caching: nicht pro HTTP-Request ffmpeg starten. + job.previewMu.Lock() + cached := job.previewJpeg + cachedAt := job.previewJpegAt + fresh := len(cached) > 0 && !cachedAt.IsZero() && time.Since(cachedAt) < 10*time.Second + + // Wenn nicht frisch, ggf. im Hintergrund aktualisieren (einmal gleichzeitig) + if !fresh && !job.previewGen { + job.previewGen = true + go func(j *RecordJob, jobID string) { + defer func() { + j.previewMu.Lock() + j.previewGen = false + j.previewMu.Unlock() + }() + + var img []byte + var genErr error + + // 1) aus Preview-Segmenten + previewDir := strings.TrimSpace(j.PreviewDir) + if previewDir != "" { + img, genErr = extractLastFrameFromPreviewDir(previewDir) + } + + // 2) Fallback: aus der Ausgabedatei + if genErr != nil || len(img) == 0 { + outPath := strings.TrimSpace(j.Output) + if outPath != "" { + outPath = filepath.Clean(outPath) + if !filepath.IsAbs(outPath) { + if abs, err := resolvePathRelativeToApp(outPath); err == nil { + outPath = abs + } + } + if fi, err := os.Stat(outPath); err == nil && !fi.IsDir() && fi.Size() > 0 { + img, genErr = extractLastFrameJPEG(outPath) + if genErr != nil { + img, _ = extractFirstFrameJPEG(outPath) + } + } + } + } + + if len(img) > 0 { + j.previewMu.Lock() + j.previewJpeg = img + j.previewJpegAt = time.Now() + j.previewMu.Unlock() + } + }(job, id) } - // 2️⃣ Fallback: direkt aus der Ausgabedatei (TS/MP4), z.B. wenn Preview noch nicht läuft - outPath := strings.TrimSpace(job.Output) - if outPath == "" { - http.Error(w, "preview nicht verfügbar", http.StatusNotFound) + // Wir liefern entweder ein frisches Bild, oder das zuletzt gecachte. + out := cached + job.previewMu.Unlock() + if len(out) > 0 { + servePreviewJPEGBytes(w, out) return } - outPath = filepath.Clean(outPath) - - if !filepath.IsAbs(outPath) { - if abs, err := resolvePathRelativeToApp(outPath); err == nil { - outPath = abs - } - } - - fi, err := os.Stat(outPath) - if err != nil || fi.IsDir() || fi.Size() == 0 { - http.Error(w, "preview nicht verfügbar", http.StatusNotFound) - return - } - - img, err := extractLastFrameJPEG(outPath) - if err != nil { - img2, err2 := extractFirstFrameJPEG(outPath) - if err2 != nil { - http.Error(w, "konnte preview nicht erzeugen: "+err.Error(), http.StatusInternalServerError) - return - } - img = img2 - } - - servePreviewJPEGBytes(w, img) + // noch kein Bild verfügbar -> 204 (Frontend zeigt Placeholder und retry) + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNoContent) return } @@ -777,24 +815,10 @@ func startPreviewHLS(ctx context.Context, jobID, m3u8URL, previewDir, httpCookie baseURL := fmt.Sprintf("/api/record/preview?id=%s&file=", url.QueryEscape(jobID)) - // LOW (ohne Audio – spart Bandbreite) - lowArgs := append(commonIn, - "-vf", "scale=160:-2", - "-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency", - "-g", "48", "-keyint_min", "48", "-sc_threshold", "0", - "-an", - "-f", "hls", - "-hls_time", "2", - "-hls_list_size", "4", - "-hls_flags", "delete_segments+append_list+independent_segments", - "-hls_segment_filename", filepath.Join(previewDir, "seg_low_%05d.ts"), - "-hls_base_url", baseURL, - filepath.Join(previewDir, "index.m3u8"), - ) - - // HQ (mit Audio) + // ✅ Nur EIN Preview-Transcode pro Job (sonst wird es bei vielen Downloads sehr teuer). + // Wir nutzen das HQ-Playlist-Format (index_hq.m3u8), aber skalieren etwas kleiner. hqArgs := append(commonIn, - "-vf", "scale=640:-2", + "-vf", "scale=480:-2", "-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency", "-g", "48", "-keyint_min", "48", "-sc_threshold", "0", "-c:a", "aac", "-b:a", "128k", "-ac", "2", @@ -807,16 +831,7 @@ func startPreviewHLS(ctx context.Context, jobID, m3u8URL, previewDir, httpCookie filepath.Join(previewDir, "index_hq.m3u8"), ) - // beide Prozesse starten (einfach & robust) - go func(kind string, args []string) { - cmd := exec.CommandContext(ctx, ffmpegPath, args...) - var stderr bytes.Buffer - cmd.Stderr = &stderr - if err := cmd.Run(); err != nil && ctx.Err() == nil { - fmt.Printf("⚠️ preview %s ffmpeg failed: %v (%s)\n", kind, err, strings.TrimSpace(stderr.String())) - } - }("low", lowArgs) - + // Preview-Prozess starten (einfach & robust) go func(kind string, args []string) { cmd := exec.CommandContext(ctx, ffmpegPath, args...) var stderr bytes.Buffer @@ -902,6 +917,10 @@ func registerRoutes(mux *http.ServeMux) { mux.HandleFunc("/api/record/list", recordList) mux.HandleFunc("/api/record/video", recordVideo) mux.HandleFunc("/api/record/done", recordDoneList) + mux.HandleFunc("/api/record/delete", recordDeleteVideo) + mux.HandleFunc("/api/record/toggle-hot", recordToggleHot) + + mux.HandleFunc("/api/chaturbate/online", chaturbateOnlineHandler) modelsPath, _ := resolvePathRelativeToApp("data/models_store.db") fmt.Println("📦 Models DB:", modelsPath) @@ -922,8 +941,8 @@ func main() { mux := http.NewServeMux() registerRoutes(mux) - fmt.Println("🌐 HTTP-API aktiv: http://localhost:8080") - if err := http.ListenAndServe(":8080", mux); err != nil { + fmt.Println("🌐 HTTP-API aktiv: http://localhost:9999") + if err := http.ListenAndServe(":9999", mux); err != nil { fmt.Println("❌ HTTP-Server Fehler:", err) os.Exit(1) } @@ -1086,9 +1105,9 @@ func runJob(ctx context.Context, job *RecordJob, req RecordRequest) { } func recordVideo(w http.ResponseWriter, r *http.Request) { - // ✅ NEU: Wiedergabe über Dateiname (für doneDir / recordDir) - if raw := r.URL.Query().Get("file"); strings.TrimSpace(raw) != "" { - // ✅ explizit decoden (zur Sicherheit) + // ✅ 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) @@ -1096,7 +1115,7 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { } file = strings.TrimSpace(file) - // ✅ kein Pfad, keine Backslashes, kein Traversal + // kein Pfad, keine Backslashes, kein Traversal if file == "" || strings.Contains(file, "/") || strings.Contains(file, "\\") || @@ -1112,12 +1131,30 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { } s := getSettings() - recordAbs, _ := resolvePathRelativeToApp(s.RecordDir) - doneAbs, _ := resolvePathRelativeToApp(s.DoneDir) + 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 doneDir, dann recordDir candidates := []string{ - filepath.Join(doneAbs, file), // bevorzugt doneDir - filepath.Join(recordAbs, file), // fallback recordDir + filepath.Join(doneAbs, file), + filepath.Join(recordAbs, file), + } + + // Falls UI noch ".ts" kennt, die Datei aber schon als ".mp4" existiert: + if ext == ".ts" { + mp4File := strings.TrimSuffix(file, ext) + ".mp4" + candidates = append(candidates, + filepath.Join(doneAbs, mp4File), + filepath.Join(recordAbs, mp4File), + ) } var outPath string @@ -1128,24 +1165,40 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { break } } - if outPath == "" { http.Error(w, "datei nicht gefunden", http.StatusNotFound) return } - if ext == ".mp4" { - w.Header().Set("Content-Type", "video/mp4") - } else { - w.Header().Set("Content-Type", "video/mp2t") + // TS kann der Browser nicht zuverlässig direkt -> on-demand remux nach MP4 + 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 = 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 + } } + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "video/mp4") http.ServeFile(w, r, outPath) return } - // --- ALT: Wiedergabe über Job-ID (funktioniert nur solange Job im RAM existiert) --- - id := r.URL.Query().Get("id") + // ✅ 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 @@ -1168,7 +1221,7 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { if !filepath.IsAbs(outPath) { abs, err := resolvePathRelativeToApp(outPath) if err != nil { - http.Error(w, "pfad auflösung fehlgeschlagen", http.StatusInternalServerError) + http.Error(w, "pfad auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) return } outPath = abs @@ -1180,14 +1233,28 @@ func recordVideo(w http.ResponseWriter, r *http.Request) { return } - ext := strings.ToLower(filepath.Ext(outPath)) - if ext == ".mp4" { - w.Header().Set("Content-Type", "video/mp4") - } else if ext == ".ts" { - w.Header().Set("Content-Type", "video/mp2t") + // TS kann der Browser nicht zuverlässig direkt -> on-demand remux nach MP4 + if strings.ToLower(filepath.Ext(outPath)) == ".ts" { + newOut, err := maybeRemuxTS(outPath) + if err != nil { + http.Error(w, "TS 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 = 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) + return + } } w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Type", "video/mp4") http.ServeFile(w, r, outPath) } @@ -1265,6 +1332,172 @@ func recordDoneList(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(list) } +func recordDeleteVideo(w http.ResponseWriter, r *http.Request) { + // Frontend nutzt aktuell POST (siehe FinishedDownloads), daher erlauben wir POST + DELETE + if r.Method != http.MethodPost && r.Method != http.MethodDelete { + http.Error(w, "Nur POST oder DELETE erlaubt", http.StatusMethodNotAllowed) + return + } + + raw := strings.TrimSpace(r.URL.Query().Get("file")) + if raw == "" { + http.Error(w, "file fehlt", http.StatusBadRequest) + return + } + + // sicher decoden + file, err := url.QueryUnescape(raw) + if err != nil { + http.Error(w, "ungültiger file", http.StatusBadRequest) + return + } + file = strings.TrimSpace(file) + + // 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) + return + } + + ext := strings.ToLower(filepath.Ext(file)) + if ext != ".mp4" && ext != ".ts" { + http.Error(w, "nicht erlaubt", http.StatusForbidden) + return + } + + s := getSettings() + doneAbs, err := resolvePathRelativeToApp(s.DoneDir) + if err != nil { + http.Error(w, "doneDir auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + if strings.TrimSpace(doneAbs) == "" { + http.Error(w, "doneDir ist leer", http.StatusBadRequest) + return + } + + target := filepath.Join(doneAbs, file) + + fi, err := os.Stat(target) + if err != nil { + if os.IsNotExist(err) { + http.Error(w, "datei nicht gefunden", http.StatusNotFound) + return + } + http.Error(w, "stat fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + if fi.IsDir() { + http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) + return + } + + if err := os.Remove(target); err != nil { + http.Error(w, "löschen fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "ok": true, + "file": file, + }) +} + +func recordToggleHot(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Nur POST", http.StatusMethodNotAllowed) + return + } + + raw := strings.TrimSpace(r.URL.Query().Get("file")) + if raw == "" { + http.Error(w, "file fehlt", http.StatusBadRequest) + return + } + + file, err := url.QueryUnescape(raw) + if err != nil { + http.Error(w, "ungültiger file", http.StatusBadRequest) + return + } + file = strings.TrimSpace(file) + + // 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) + return + } + + ext := strings.ToLower(filepath.Ext(file)) + if ext != ".mp4" && ext != ".ts" { + http.Error(w, "nicht erlaubt", http.StatusForbidden) + return + } + + s := getSettings() + doneAbs, err := resolvePathRelativeToApp(s.DoneDir) + if err != nil { + http.Error(w, "doneDir auflösung fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + if strings.TrimSpace(doneAbs) == "" { + http.Error(w, "doneDir ist leer", http.StatusBadRequest) + return + } + + src := filepath.Join(doneAbs, file) + fi, err := os.Stat(src) + if err != nil { + if os.IsNotExist(err) { + http.Error(w, "datei nicht gefunden", http.StatusNotFound) + return + } + http.Error(w, "stat fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + if fi.IsDir() { + http.Error(w, "ist ein verzeichnis", http.StatusBadRequest) + return + } + + newFile := file + if strings.HasPrefix(file, "HOT ") { + newFile = strings.TrimPrefix(file, "HOT ") + } else { + newFile = "HOT " + file + } + + dst := filepath.Join(doneAbs, newFile) + if _, err := os.Stat(dst); err == nil { + http.Error(w, "ziel existiert bereits", http.StatusConflict) + return + } else if !os.IsNotExist(err) { + http.Error(w, "stat ziel fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + + if err := os.Rename(src, dst); err != nil { + http.Error(w, "rename fehlgeschlagen: "+err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "ok": true, + "oldFile": file, + "newFile": newFile, + }) +} + func maybeRemuxTS(path string) (string, error) { path = strings.TrimSpace(path) if path == "" { diff --git a/backend/models_api.go b/backend/models_api.go index 7ee81ba..7e8c2f1 100644 --- a/backend/models_api.go +++ b/backend/models_api.go @@ -1,10 +1,13 @@ package main import ( + "encoding/csv" "encoding/json" "errors" + "io" "net/http" "net/url" + "strconv" "strings" ) @@ -102,6 +105,106 @@ func parseModelFromURL(raw string) (ParsedModelDTO, error) { }, nil } +type importResult struct { + Processed int `json:"processed"` + Inserted int `json:"inserted"` + Updated int `json:"updated"` + Skipped int `json:"skipped"` +} + +func importModelsCSV(store *ModelStore, r io.Reader, kind string) (importResult, error) { + cr := csv.NewReader(r) + cr.Comma = ';' + cr.FieldsPerRecord = -1 + cr.TrimLeadingSpace = true + + header, err := cr.Read() + if err != nil { + return importResult{}, errors.New("CSV: header fehlt") + } + + idx := map[string]int{} + for i, h := range header { + idx[strings.ToLower(strings.TrimSpace(h))] = i + } + + need := []string{"url", "last_stream", "tags", "watch"} + for _, k := range need { + if _, ok := idx[k]; !ok { + return importResult{}, errors.New("CSV: Spalte fehlt: " + k) + } + } + + seen := map[string]bool{} + out := importResult{} + + for { + rec, err := cr.Read() + if err == io.EOF { + break + } + if err != nil { + return out, errors.New("CSV: ungültige Zeile") + } + + get := func(key string) string { + i := idx[key] + if i < 0 || i >= len(rec) { + return "" + } + return strings.TrimSpace(rec[i]) + } + + urlRaw := get("url") + if urlRaw == "" { + out.Skipped++ + continue + } + + dto, err := parseModelFromURL(urlRaw) + if err != nil { + out.Skipped++ + continue + } + + tags := get("tags") + lastStream := get("last_stream") + + watchStr := get("watch") + watch := false + if watchStr != "" { + if n, err := strconv.Atoi(watchStr); err == nil { + watch = n != 0 + } else { + // "true"/"false" fallback + watch = strings.EqualFold(watchStr, "true") || strings.EqualFold(watchStr, "yes") + } + } + + // dedupe innerhalb der Datei (host:modelKey) + key := strings.ToLower(dto.Host) + ":" + strings.ToLower(dto.ModelKey) + if seen[key] { + continue + } + seen[key] = true + + _, inserted, err := store.UpsertFromImport(dto, tags, lastStream, watch, kind) + if err != nil { + out.Skipped++ + continue + } + + out.Processed++ + if inserted { + out.Inserted++ + } else { + out.Updated++ + } + } + + return out, nil +} + func RegisterModelAPI(mux *http.ServeMux, store *ModelStore) { // ✅ NEU: Parse-Endpoint (nur URL erlaubt) @@ -123,7 +226,16 @@ func RegisterModelAPI(mux *http.ServeMux, store *ModelStore) { modelsWriteJSON(w, http.StatusOK, dto) }) - mux.HandleFunc("/api/models/list", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/api/models/meta", func(w http.ResponseWriter, r *http.Request) { + modelsWriteJSON(w, http.StatusOK, store.Meta()) +}) + +mux.HandleFunc("/api/models/watched", func(w http.ResponseWriter, r *http.Request) { + host := strings.TrimSpace(r.URL.Query().Get("host")) + modelsWriteJSON(w, http.StatusOK, store.ListWatchedLite(host)) +}) + +mux.HandleFunc("/api/models/list", func(w http.ResponseWriter, r *http.Request) { modelsWriteJSON(w, http.StatusOK, store.List()) }) @@ -152,6 +264,39 @@ func RegisterModelAPI(mux *http.ServeMux, store *ModelStore) { modelsWriteJSON(w, http.StatusOK, m) }) + mux.HandleFunc("/api/models/import", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + modelsWriteJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + + if err := r.ParseMultipartForm(32 << 20); err != nil { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid multipart form"}) + return + } + + kind := strings.ToLower(strings.TrimSpace(r.FormValue("kind"))) + if kind != "favorite" && kind != "liked" { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": `kind must be "favorite" or "liked"`}) + return + } + + f, _, err := r.FormFile("file") + if err != nil { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": "missing file"}) + return + } + defer f.Close() + + res, err := importModelsCSV(store, f, kind) + if err != nil { + modelsWriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) + return + } + + modelsWriteJSON(w, http.StatusOK, res) + }) + mux.HandleFunc("/api/models/flags", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { modelsWriteJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) diff --git a/backend/models_store.go b/backend/models_store.go index ada8e61..2d70bb2 100644 --- a/backend/models_store.go +++ b/backend/models_store.go @@ -16,12 +16,14 @@ import ( ) type StoredModel struct { - ID string `json:"id"` // unique (wir verwenden host:modelKey) - Input string `json:"input"` // Original-URL/Eingabe - IsURL bool `json:"isUrl"` // vom Parser - Host string `json:"host,omitempty"` - Path string `json:"path,omitempty"` - ModelKey string `json:"modelKey"` // Display/Key + ID string `json:"id"` // unique (wir verwenden host:modelKey) + Input string `json:"input"` // Original-URL/Eingabe + IsURL bool `json:"isUrl"` // vom Parser + Host string `json:"host,omitempty"` + Path string `json:"path,omitempty"` + ModelKey string `json:"modelKey"` // Display/Key + Tags string `json:"tags,omitempty"` + LastStream string `json:"lastStream,omitempty"` Watching bool `json:"watching"` Favorite bool `json:"favorite"` @@ -33,6 +35,20 @@ type StoredModel struct { UpdatedAt string `json:"updatedAt"` } +type ModelsMeta struct { + Count int `json:"count"` + UpdatedAt string `json:"updatedAt"` +} + +// Kleine Payload für "watched" Listen (für Autostart/Abgleich) +type WatchedModelLite struct { + ID string `json:"id"` + Input string `json:"input"` + Host string `json:"host,omitempty"` + ModelKey string `json:"modelKey"` + Watching bool `json:"watching"` +} + type ParsedModelDTO struct { Input string `json:"input"` IsURL bool `json:"isUrl"` @@ -117,18 +133,22 @@ func (s *ModelStore) init() error { _, _ = db.Exec(`PRAGMA journal_mode = WAL;`) _, _ = db.Exec(`PRAGMA synchronous = NORMAL;`) + // ✅ zuerst Schema/Columns auf "db" erstellen if err := createModelsSchema(db); err != nil { _ = db.Close() return err } + if err := ensureModelsColumns(db); err != nil { + _ = db.Close() + return err + } + // ✅ erst danach in den Store übernehmen s.db = db // 1x Migration: wenn DB leer ist und Legacy JSON existiert if s.legacyJSONPath != "" { if err := s.migrateFromJSONIfEmpty(); err != nil { - // Migration-Fehler nicht hart killen, aber zurückgeben ist auch ok. - // Ich gebe zurück, damit du es direkt siehst. return err } } @@ -145,6 +165,9 @@ CREATE TABLE IF NOT EXISTS models ( host TEXT, path TEXT, model_key TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '', + last_stream TEXT, + watching INTEGER NOT NULL DEFAULT 0, favorite INTEGER NOT NULL DEFAULT 0, @@ -166,6 +189,39 @@ CREATE TABLE IF NOT EXISTS models ( return nil } +func ensureModelsColumns(db *sql.DB) error { + cols := map[string]bool{} + + rows, err := db.Query(`PRAGMA table_info(models);`) + if err != nil { + return err + } + defer rows.Close() + + for rows.Next() { + var cid int + var name, typ string + var notnull, pk int + var dflt sql.NullString + if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err != nil { + return err + } + cols[name] = true + } + + if !cols["tags"] { + if _, err := db.Exec(`ALTER TABLE models ADD COLUMN tags TEXT NOT NULL DEFAULT '';`); err != nil { + return err + } + } + if !cols["last_stream"] { + if _, err := db.Exec(`ALTER TABLE models ADD COLUMN last_stream TEXT;`); err != nil { + return err + } + } + return nil +} + func canonicalHost(host string) string { h := strings.ToLower(strings.TrimSpace(host)) h = strings.TrimPrefix(h, "www.") @@ -242,6 +298,7 @@ func (s *ModelStore) migrateFromJSONIfEmpty() error { stmt, err := tx.Prepare(` INSERT INTO models ( id,input,is_url,host,path,model_key, + tags,last_stream, watching,favorite,hot,keep,liked, created_at,updated_at ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) @@ -322,6 +379,7 @@ func (s *ModelStore) List() []StoredModel { rows, err := s.db.Query(` SELECT id,input,is_url,host,path,model_key, + tags,last_stream, watching,favorite,hot,keep,liked, created_at,updated_at FROM models @@ -336,12 +394,13 @@ ORDER BY updated_at DESC; for rows.Next() { var ( - id, input, host, path, modelKey, createdAt, updatedAt string - isURL, watching, favorite, hot, keep int64 - liked sql.NullInt64 + id, input, host, path, modelKey, tags, lastStream, createdAt, updatedAt string + isURL, watching, favorite, hot, keep int64 + liked sql.NullInt64 ) if err := rows.Scan( &id, &input, &isURL, &host, &path, &modelKey, + &tags, &lastStream, &watching, &favorite, &hot, &keep, &liked, &createdAt, &updatedAt, ); err != nil { @@ -349,25 +408,91 @@ ORDER BY updated_at DESC; } out = append(out, StoredModel{ - ID: id, - Input: input, - IsURL: isURL != 0, - Host: host, - Path: path, - ModelKey: modelKey, - Watching: watching != 0, - Favorite: favorite != 0, - Hot: hot != 0, - Keep: keep != 0, - Liked: ptrLikedFromNull(liked), - CreatedAt: createdAt, - UpdatedAt: updatedAt, + ID: id, + Input: input, + IsURL: isURL != 0, + Host: host, + Path: path, + ModelKey: modelKey, + Watching: watching != 0, + Tags: tags, + LastStream: lastStream, + Favorite: favorite != 0, + Hot: hot != 0, + Keep: keep != 0, + Liked: ptrLikedFromNull(liked), + CreatedAt: createdAt, + UpdatedAt: updatedAt, }) } return out } +func (s *ModelStore) Meta() ModelsMeta { + if err := s.ensureInit(); err != nil { + return ModelsMeta{Count: 0, UpdatedAt: ""} + } + + var count int + var updatedAt string + err := s.db.QueryRow(`SELECT COUNT(*), COALESCE(MAX(updated_at), '') FROM models;`).Scan(&count, &updatedAt) + if err != nil { + return ModelsMeta{Count: 0, UpdatedAt: ""} + } + return ModelsMeta{Count: count, UpdatedAt: updatedAt} +} + +// hostFilter: z.B. "chaturbate.com" (leer => alle Hosts) +func (s *ModelStore) ListWatchedLite(hostFilter string) []WatchedModelLite { + if err := s.ensureInit(); err != nil { + return []WatchedModelLite{} + } + + hostFilter = canonicalHost(hostFilter) + + var ( + rows *sql.Rows + err error + ) + if hostFilter == "" { + rows, err = s.db.Query(` +SELECT id,input,host,model_key,watching +FROM models +WHERE watching = 1 +ORDER BY updated_at DESC; +`) + } else { + rows, err = s.db.Query(` +SELECT id,input,host,model_key,watching +FROM models +WHERE watching = 1 AND host = ? +ORDER BY updated_at DESC; +`, hostFilter) + } + if err != nil { + return []WatchedModelLite{} + } + defer rows.Close() + + out := make([]WatchedModelLite, 0, 64) + for rows.Next() { + var id, input, host, modelKey string + var watching int64 + if err := rows.Scan(&id, &input, &host, &modelKey, &watching); err != nil { + continue + } + out = append(out, WatchedModelLite{ + ID: id, + Input: input, + Host: host, + ModelKey: modelKey, + Watching: watching != 0, + }) + } + return out +} + func (s *ModelStore) UpsertFromParsed(p ParsedModelDTO) (StoredModel, error) { if err := s.ensureInit(); err != nil { return StoredModel{}, err @@ -401,6 +526,7 @@ func (s *ModelStore) UpsertFromParsed(p ParsedModelDTO) (StoredModel, error) { _, err = s.db.Exec(` INSERT INTO models ( id,input,is_url,host,path,model_key, + tags,last_stream, watching,favorite,hot,keep,liked, created_at,updated_at ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) @@ -509,22 +635,100 @@ func (s *ModelStore) Delete(id string) error { return err } +func (s *ModelStore) UpsertFromImport(p ParsedModelDTO, tags, lastStream string, watch bool, kind string) (StoredModel, bool, error) { + if err := s.ensureInit(); err != nil { + return StoredModel{}, false, err + } + + input := strings.TrimSpace(p.Input) + if input == "" || !p.IsURL { + return StoredModel{}, false, errors.New("Nur URL erlaubt.") + } + u, err := url.Parse(input) + if err != nil || u.Scheme == "" || u.Hostname() == "" { + return StoredModel{}, false, errors.New("Ungültige URL.") + } + + host := canonicalHost(p.Host) + modelKey := strings.TrimSpace(p.ModelKey) + id := canonicalID(host, modelKey) + + now := time.Now().UTC().Format(time.RFC3339Nano) + + // kind: "favorite" | "liked" + fav := int64(0) + var likedArg any = nil + if kind == "favorite" { + fav = int64(1) + } + if kind == "liked" { + likedArg = int64(1) + } + + s.mu.Lock() + defer s.mu.Unlock() + + // exists? + inserted := false + var dummy int + err = s.db.QueryRow(`SELECT 1 FROM models WHERE id=? LIMIT 1;`, id).Scan(&dummy) + if err == sql.ErrNoRows { + inserted = true + } else if err != nil { + return StoredModel{}, false, err + } + + _, err = s.db.Exec(` +INSERT INTO models ( + id,input,is_url,host,path,model_key, + tags,last_stream, + watching,favorite,hot,keep,liked, + created_at,updated_at +) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) +ON CONFLICT(id) DO UPDATE SET + input=excluded.input, + is_url=excluded.is_url, + host=excluded.host, + path=excluded.path, + model_key=excluded.model_key, + tags=excluded.tags, + last_stream=excluded.last_stream, + watching=excluded.watching, + favorite=CASE WHEN excluded.favorite=1 THEN 1 ELSE favorite END, + liked=CASE WHEN excluded.liked IS NOT NULL THEN excluded.liked ELSE liked END, + updated_at=excluded.updated_at; +`, + id, u.String(), int64(1), host, p.Path, modelKey, + tags, lastStream, + boolToInt(watch), fav, int64(0), int64(0), likedArg, + now, now, + ) + if err != nil { + return StoredModel{}, false, err + } + + m, err := s.getByID(id) + return m, inserted, err +} + func (s *ModelStore) getByID(id string) (StoredModel, error) { var ( - input, host, path, modelKey, createdAt, updatedAt string - isURL, watching, favorite, hot, keep int64 - liked sql.NullInt64 + input, host, path, modelKey, tags, lastStream, createdAt, updatedAt string + isURL, watching, favorite, hot, keep int64 + liked sql.NullInt64 ) err := s.db.QueryRow(` SELECT input,is_url,host,path,model_key, + tags, lastStream, watching,favorite,hot,keep,liked, created_at,updated_at FROM models WHERE id=?; `, id).Scan( &input, &isURL, &host, &path, &modelKey, + &tags, &lastStream, &watching, &favorite, &hot, &keep, &liked, &createdAt, &updatedAt, ) @@ -536,18 +740,20 @@ WHERE id=?; } return StoredModel{ - ID: id, - Input: input, - IsURL: isURL != 0, - Host: host, - Path: path, - ModelKey: modelKey, - Watching: watching != 0, - Favorite: favorite != 0, - Hot: hot != 0, - Keep: keep != 0, - Liked: ptrLikedFromNull(liked), - CreatedAt: createdAt, - UpdatedAt: updatedAt, + ID: id, + Input: input, + IsURL: isURL != 0, + Host: host, + Path: path, + ModelKey: modelKey, + Tags: tags, + LastStream: lastStream, + Watching: watching != 0, + Favorite: favorite != 0, + Hot: hot != 0, + Keep: keep != 0, + Liked: ptrLikedFromNull(liked), + CreatedAt: createdAt, + UpdatedAt: updatedAt, }, nil } diff --git a/backend/myapp.exe b/backend/myapp.exe deleted file mode 100644 index 4ce1ff0..0000000 Binary files a/backend/myapp.exe and /dev/null differ diff --git a/backend/nsfwapp.exe b/backend/nsfwapp.exe new file mode 100644 index 0000000..3a7e805 Binary files /dev/null and b/backend/nsfwapp.exe differ diff --git a/backend/web/dist/assets/index-WtXLd9dH.css b/backend/web/dist/assets/index-WtXLd9dH.css new file mode 100644 index 0000000..da20c5b --- /dev/null +++ b/backend/web/dist/assets/index-WtXLd9dH.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-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-leading:initial;--tw-font-weight: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-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-800:oklch(47.3% .137 46.201);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-700:oklch(52.7% .154 150.069);--color-emerald-50:oklch(97.9% .021 166.113);--color-emerald-100:oklch(95% .052 163.051);--color-emerald-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-sky-50:oklch(97.7% .013 236.62);--color-sky-200:oklch(90.1% .058 230.902);--color-sky-500:oklch(68.5% .169 237.323);--color-sky-700:oklch(50% .134 242.749);--color-blue-50:oklch(97% .014 254.604);--color-blue-100:oklch(93.2% .032 255.585);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-indigo-50:oklch(96.2% .018 272.314);--color-indigo-100:oklch(93% .034 272.788);--color-indigo-200:oklch(87% .065 274.039);--color-indigo-300:oklch(78.5% .115 274.713);--color-indigo-400:oklch(67.3% .182 276.935);--color-indigo-500:oklch(58.5% .233 277.117);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-rose-500:oklch(64.5% .246 16.439);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--container-7xl:80rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--font-weight-medium:500;--font-weight-semibold:600;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--ease-in:cubic-bezier(.4,0,1,1);--ease-out:cubic-bezier(0,0,.2,1);--ease-in-out:cubic-bezier(.4,0,.2,1);--animate-spin:spin 1s linear infinite;--blur-sm:8px;--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-none{pointer-events:none}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.inset-6{inset:calc(var(--spacing)*6)}.inset-x-0{inset-inline:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.right-4{right:calc(var(--spacing)*4)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-4{bottom:calc(var(--spacing)*4)}.left-0{left:calc(var(--spacing)*0)}.isolate{isolation:isolate}.z-10{z-index:10}.z-40{z-index:40}.z-50{z-index:50}.col-span-1{grid-column:span 1/span 1}.col-start-1{grid-column-start:1}.row-start-1{grid-row-start:1}.mx-2{margin-inline:calc(var(--spacing)*2)}.mx-auto{margin-inline:auto}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mt-4{margin-top:calc(var(--spacing)*4)}.mt-6{margin-top:calc(var(--spacing)*6)}.mt-8{margin-top:calc(var(--spacing)*8)}.-mr-0\.5{margin-right:calc(var(--spacing)*-.5)}.mr-2{margin-right:calc(var(--spacing)*2)}.-mb-px{margin-bottom:-1px}.mb-4{margin-bottom:calc(var(--spacing)*4)}.-ml-0\.5{margin-left:calc(var(--spacing)*-.5)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-3{margin-left:calc(var(--spacing)*3)}.block{display:block}.flex{display:flex}.flow-root{display:flow-root}.grid{display:grid}.hidden{display:none}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.aspect-video{aspect-ratio:var(--aspect-video)}.size-3{width:calc(var(--spacing)*3);height:calc(var(--spacing)*3)}.size-4{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.size-5{width:calc(var(--spacing)*5);height:calc(var(--spacing)*5)}.size-full{width:100%;height:100%}.h-0\.5{height:calc(var(--spacing)*.5)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-12{height:calc(var(--spacing)*12)}.h-16{height:calc(var(--spacing)*16)}.h-full{height:100%}.min-h-0{min-height:calc(var(--spacing)*0)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-9{width:calc(var(--spacing)*9)}.w-10{width:calc(var(--spacing)*10)}.w-11{width:calc(var(--spacing)*11)}.w-12{width:calc(var(--spacing)*12)}.w-20{width:calc(var(--spacing)*20)}.w-\[220px\]{width:220px}.w-\[360px\]{width:360px}.w-\[380px\]{width:380px}.w-\[420px\]{width:420px}.w-full{width:100%}.max-w-7xl{max-width:var(--container-7xl)}.max-w-\[11rem\]{max-width:11rem}.max-w-\[240px\]{max-width:240px}.max-w-\[520px\]{max-width:520px}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\[220px\]{min-width:220px}.min-w-full{min-width:100%}.flex-1{flex:1}.flex-none{flex:none}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.translate-x-5{--tw-translate-x:calc(var(--spacing)*5);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-4{--tw-translate-y:calc(var(--spacing)*4);translate:var(--tw-translate-x)var(--tw-translate-y)}.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-spin{animation:var(--animate-spin)}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize{resize:both}.appearance-none{appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}.gap-x-1\.5{column-gap:calc(var(--spacing)*1.5)}.gap-x-8{column-gap:calc(var(--spacing)*8)}:where(.-space-x-px>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(-1px*var(--tw-space-x-reverse));margin-inline-end:calc(-1px*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*4)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-8>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*8)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-x-reverse)))}:where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px*var(--tw-divide-x-reverse));border-inline-end-width:calc(1px*calc(1 - var(--tw-divide-x-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-gray-200>:not(:last-child)){border-color:var(--color-gray-200)}:where(.divide-gray-300>:not(:last-child)){border-color:var(--color-gray-300)}.self-center{align-self:center}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-l-lg{border-top-left-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.rounded-l-md{border-top-left-radius:var(--radius-md);border-bottom-left-radius:var(--radius-md)}.rounded-r-lg{border-top-right-radius:var(--radius-lg);border-bottom-right-radius:var(--radius-lg)}.rounded-r-md{border-top-right-radius:var(--radius-md);border-bottom-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-gray-200{border-color:var(--color-gray-200)}.border-gray-300{border-color:var(--color-gray-300)}.border-indigo-500{border-color:var(--color-indigo-500)}.border-transparent{border-color:#0000}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-black{background-color:var(--color-black)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.bg-black\/5{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab,red,red)){.bg-black\/40{background-color:color-mix(in oklab,var(--color-black)40%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-emerald-50{background-color:var(--color-emerald-50)}.bg-emerald-600{background-color:var(--color-emerald-600)}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-100{background-color:var(--color-gray-100)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-gray-500\/75{background-color:#6a7282bf}@supports (color:color-mix(in lab,red,red)){.bg-gray-500\/75{background-color:color-mix(in oklab,var(--color-gray-500)75%,transparent)}}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-indigo-50{background-color:var(--color-indigo-50)}.bg-indigo-100{background-color:var(--color-indigo-100)}.bg-indigo-500{background-color:var(--color-indigo-500)}.bg-indigo-600{background-color:var(--color-indigo-600)}.bg-red-50{background-color:var(--color-red-50)}.bg-red-600{background-color:var(--color-red-600)}.bg-sky-50{background-color:var(--color-sky-50)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/60{background-color:#fff9}@supports (color:color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white)60%,transparent)}}.bg-white\/70{background-color:#ffffffb3}@supports (color:color-mix(in lab,red,red)){.bg-white\/70{background-color:color-mix(in oklab,var(--color-white)70%,transparent)}}.fill-gray-500{fill:var(--color-gray-500)}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-0\.5{padding:calc(var(--spacing)*.5)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.px-1{padding-inline:calc(var(--spacing)*1)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-2\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-3\.5{padding-inline:calc(var(--spacing)*3.5)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-0\.5{padding-block:calc(var(--spacing)*.5)}.py-1{padding-block:calc(var(--spacing)*1)}.py-1\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-2\.5{padding-block:calc(var(--spacing)*2.5)}.py-3{padding-block:calc(var(--spacing)*3)}.py-3\.5{padding-block:calc(var(--spacing)*3.5)}.py-4{padding-block:calc(var(--spacing)*4)}.py-5{padding-block:calc(var(--spacing)*5)}.py-6{padding-block:calc(var(--spacing)*6)}.pt-4{padding-top:calc(var(--spacing)*4)}.pr-8{padding-right:calc(var(--spacing)*8)}.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}.leading-none{--tw-leading:1;line-height:1}.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)}.whitespace-nowrap{white-space:nowrap}.text-amber-500{color:var(--color-amber-500)}.text-amber-600{color:var(--color-amber-600)}.text-amber-800{color:var(--color-amber-800)}.text-blue-600{color:var(--color-blue-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-gray-400{color:var(--color-gray-400)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-800{color:var(--color-gray-800)}.text-gray-900{color:var(--color-gray-900)}.text-green-700{color:var(--color-green-700)}.text-indigo-500{color:var(--color-indigo-500)}.text-indigo-600{color:var(--color-indigo-600)}.text-indigo-700{color:var(--color-indigo-700)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-rose-500{color:var(--color-rose-500)}.text-sky-700{color:var(--color-sky-700)}.text-white{color:var(--color-white)}.italic{font-style:italic}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-100{opacity:1}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(1px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.inset-ring{--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-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-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)}}.inset-ring-gray-300{--tw-inset-ring-color:var(--color-gray-300)}.inset-ring-gray-900\/5{--tw-inset-ring-color:#1018280d}@supports (color:color-mix(in lab,red,red)){.inset-ring-gray-900\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-gray-900)5%,transparent)}}.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:-1px}.outline-offset-2{outline-offset:2px}.outline-black\/5{outline-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.outline-black\/5{outline-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.outline-gray-300{outline-color:var(--color-gray-300)}.outline-indigo-600{outline-color:var(--color-indigo-600)}.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-filter{-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-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-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-none{-webkit-user-select:none;user-select:none}@media(hover:hover){.group-hover\:pointer-events-auto:is(:where(.group):hover *){pointer-events:auto}.group-hover\:visible:is(:where(.group):hover *){visibility:visible}.group-hover\:text-gray-500:is(:where(.group):hover *){color:var(--color-gray-500)}.group-hover\:opacity-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\:border-gray-300:hover{border-color:var(--color-gray-300)}.hover\:border-transparent:hover{border-color:#0000}.hover\:bg-amber-100:hover{background-color:var(--color-amber-100)}.hover\:bg-amber-400:hover{background-color:var(--color-amber-400)}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab,var(--color-black)5%,transparent)}}.hover\:bg-black\/10:hover{background-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/10:hover{background-color:color-mix(in oklab,var(--color-black)10%,transparent)}}.hover\:bg-blue-100:hover{background-color:var(--color-blue-100)}.hover\:bg-blue-500:hover{background-color:var(--color-blue-500)}.hover\:bg-emerald-100:hover{background-color:var(--color-emerald-100)}.hover\:bg-emerald-500:hover{background-color:var(--color-emerald-500)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-indigo-100:hover{background-color:var(--color-indigo-100)}.hover\:bg-indigo-500:hover{background-color:var(--color-indigo-500)}.hover\:bg-red-50:hover{background-color:var(--color-red-50)}.hover\:bg-red-100:hover{background-color:var(--color-red-100)}.hover\:bg-red-500:hover{background-color:var(--color-red-500)}.hover\:bg-transparent:hover{background-color:#0000}.hover\:text-gray-500:hover{color:var(--color-gray-500)}.hover\:text-gray-700:hover{color:var(--color-gray-700)}.hover\:text-gray-800:hover{color:var(--color-gray-800)}.hover\:text-inherit:hover{color:inherit}.hover\:underline:hover{text-decoration-line:underline}.hover\:file\:bg-gray-200:hover::file-selector-button{background-color:var(--color-gray-200)}}.focus\:z-10:focus{z-index:10}.focus\:z-20:focus{z-index:20}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus\:outline-2:focus{outline-style:var(--tw-outline-style);outline-width:2px}.focus\:-outline-offset-2:focus{outline-offset:-2px}.focus\:outline-offset-0:focus{outline-offset:0px}.focus\:outline-indigo-600:focus{outline-color:var(--color-indigo-600)}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.focus-visible\:outline-blue-600:focus-visible{outline-color:var(--color-blue-600)}.focus-visible\:outline-emerald-600:focus-visible{outline-color:var(--color-emerald-600)}.focus-visible\:outline-indigo-600:focus-visible{outline-color:var(--color-indigo-600)}.focus-visible\:outline-red-600:focus-visible{outline-color:var(--color-red-600)}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-focus-visible\:outline-2:has(:focus-visible){outline-style:var(--tw-outline-style);outline-width:2px}@media(min-width:40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:col-span-3{grid-column:span 3/span 3}.sm\:col-span-9{grid-column:span 9/span 9}.sm\:mt-0{margin-top:calc(var(--spacing)*0)}.sm\:ml-16{margin-left:calc(var(--spacing)*16)}.sm\:block{display:block}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:flex-1{flex:1}.sm\:flex-auto{flex:auto}.sm\:flex-none{flex:none}.sm\:translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.sm\:scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x)var(--tw-scale-y)}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:calc(var(--spacing)*4)}.sm\:rounded-lg{border-radius:var(--radius-lg)}.sm\:p-0{padding:calc(var(--spacing)*0)}.sm\:p-6{padding:calc(var(--spacing)*6)}.sm\:px-6{padding-inline:calc(var(--spacing)*6)}}@media(min-width:48rem){.md\:inline-block{display:inline-block}}@media(min-width:64rem){.lg\:px-8{padding-inline:calc(var(--spacing)*8)}}@media(prefers-color-scheme:dark){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){:where(.dark\:divide-white\/10>:not(:last-child)){border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}:where(.dark\:divide-white\/15>:not(:last-child)){border-color:#ffffff26}@supports (color:color-mix(in lab,red,red)){:where(.dark\:divide-white\/15>:not(:last-child)){border-color:color-mix(in oklab,var(--color-white)15%,transparent)}}.dark\:border-indigo-400{border-color:var(--color-indigo-400)}.dark\:border-white\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:border-white\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:bg-amber-500{background-color:var(--color-amber-500)}.dark\:bg-amber-500\/20{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.dark\:bg-amber-500\/20{background-color:color-mix(in oklab,var(--color-amber-500)20%,transparent)}}.dark\:bg-blue-500{background-color:var(--color-blue-500)}.dark\:bg-blue-500\/20{background-color:#3080ff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-blue-500\/20{background-color:color-mix(in oklab,var(--color-blue-500)20%,transparent)}}.dark\:bg-emerald-500{background-color:var(--color-emerald-500)}.dark\:bg-emerald-500\/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\/75{background-color:#1e2939bf}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-800\/75{background-color:color-mix(in oklab,var(--color-gray-800)75%,transparent)}}.dark\:bg-gray-900{background-color:var(--color-gray-900)}.dark\:bg-gray-900\/50{background-color:#10182880}@supports (color:color-mix(in lab,red,red)){.dark\:bg-gray-900\/50{background-color:color-mix(in oklab,var(--color-gray-900)50%,transparent)}}.dark\:bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.dark\:bg-indigo-400{background-color:var(--color-indigo-400)}.dark\:bg-indigo-500{background-color:var(--color-indigo-500)}.dark\:bg-indigo-500\/10{background-color:#625fff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/10{background-color:color-mix(in oklab,var(--color-indigo-500)10%,transparent)}}.dark\:bg-indigo-500\/20{background-color:#625fff33}@supports (color:color-mix(in lab,red,red)){.dark\:bg-indigo-500\/20{background-color:color-mix(in oklab,var(--color-indigo-500)20%,transparent)}}.dark\:bg-red-500{background-color:var(--color-red-500)}.dark\:bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.dark\:bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.dark\:bg-red-500\/20{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.dark\:bg-sky-500\/10{background-color:#00a5ef1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sky-500\/10{background-color:color-mix(in oklab,var(--color-sky-500)10%,transparent)}}.dark\:bg-transparent{background-color:#0000}.dark\:bg-white\/5{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/5{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:fill-gray-400{fill:var(--color-gray-400)}.dark\:text-amber-300{color:var(--color-amber-300)}.dark\:text-amber-400{color:var(--color-amber-400)}.dark\:text-blue-400{color:var(--color-blue-400)}.dark\:text-emerald-400{color:var(--color-emerald-400)}.dark\:text-gray-100{color:var(--color-gray-100)}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-300{color:var(--color-gray-300)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-gray-500{color:var(--color-gray-500)}.dark\:text-gray-600{color:var(--color-gray-600)}.dark\:text-green-200{color:var(--color-green-200)}.dark\:text-indigo-200{color:var(--color-indigo-200)}.dark\:text-indigo-300{color:var(--color-indigo-300)}.dark\:text-indigo-400{color:var(--color-indigo-400)}.dark\:text-indigo-500{color:var(--color-indigo-500)}.dark\:text-red-200{color:var(--color-red-200)}.dark\:text-red-300{color:var(--color-red-300)}.dark\:text-red-400{color:var(--color-red-400)}.dark\:text-sky-200{color:var(--color-sky-200)}.dark\:text-white{color:var(--color-white)}.dark\:shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.dark\:ring-white\/10{--tw-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:ring-white\/10{--tw-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:inset-ring-gray-700{--tw-inset-ring-color:var(--color-gray-700)}.dark\:inset-ring-white\/5{--tw-inset-ring-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/5{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:inset-ring-white\/10{--tw-inset-ring-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:inset-ring-white\/10{--tw-inset-ring-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:outline{outline-style:var(--tw-outline-style);outline-width:1px}.dark\:-outline-offset-1{outline-offset:-1px}.dark\:outline-indigo-500{outline-color:var(--color-indigo-500)}.dark\:outline-white\/10{outline-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:outline-white\/10{outline-color:color-mix(in oklab,var(--color-white)10%,transparent)}}:is(.dark\:\*\:bg-gray-800>*){background-color:var(--color-gray-800)}@media(hover:hover){.dark\:group-hover\:text-gray-400:is(:where(.group):hover *){color:var(--color-gray-400)}}.dark\:file\:bg-white\/10::file-selector-button{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:file\:bg-white\/10::file-selector-button{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:file\:text-white::file-selector-button{color:var(--color-white)}.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.dark\:even\:bg-gray-800\/50:nth-child(2n){background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}}@media(hover:hover){.dark\:hover\:border-white\/20:hover{border-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:border-white\/20:hover{border-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:bg-amber-400:hover{background-color:var(--color-amber-400)}.dark\:hover\:bg-amber-500\/30:hover{background-color:#f99c004d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-amber-500\/30:hover{background-color:color-mix(in oklab,var(--color-amber-500)30%,transparent)}}.dark\:hover\:bg-blue-400:hover{background-color:var(--color-blue-400)}.dark\:hover\:bg-blue-500\/30:hover{background-color:#3080ff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-blue-500\/30:hover{background-color:color-mix(in oklab,var(--color-blue-500)30%,transparent)}}.dark\:hover\:bg-emerald-400:hover{background-color:var(--color-emerald-400)}.dark\:hover\:bg-emerald-500\/30:hover{background-color:#00bb7f4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-emerald-500\/30:hover{background-color:color-mix(in oklab,var(--color-emerald-500)30%,transparent)}}.dark\:hover\:bg-indigo-400:hover{background-color:var(--color-indigo-400)}.dark\:hover\:bg-indigo-500\/30:hover{background-color:#625fff4d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-indigo-500\/30:hover{background-color:color-mix(in oklab,var(--color-indigo-500)30%,transparent)}}.dark\:hover\:bg-red-400:hover{background-color:var(--color-red-400)}.dark\:hover\:bg-red-500\/10:hover{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-red-500\/10:hover{background-color:color-mix(in oklab,var(--color-red-500)10%,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-white\/5:hover{background-color:#ffffff0d}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/5:hover{background-color:color-mix(in oklab,var(--color-white)5%,transparent)}}.dark\:hover\:bg-white\/10:hover{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/10:hover{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.dark\:hover\:bg-white\/15:hover{background-color:#ffffff26}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/15:hover{background-color:color-mix(in oklab,var(--color-white)15%,transparent)}}.dark\:hover\:bg-white\/20:hover{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-white\/20:hover{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}.dark\:hover\:text-gray-200:hover{color:var(--color-gray-200)}.dark\:hover\:text-gray-300:hover{color:var(--color-gray-300)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}.dark\:hover\:text-white:hover{color:var(--color-white)}.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:file\:bg-white\/20:hover::file-selector-button{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}}}.dark\:focus\:outline-indigo-500:focus{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:outline-amber-500:focus-visible{outline-color:var(--color-amber-500)}.dark\:focus-visible\:outline-blue-500:focus-visible{outline-color:var(--color-blue-500)}.dark\:focus-visible\:outline-emerald-500:focus-visible{outline-color:var(--color-emerald-500)}.dark\:focus-visible\:outline-indigo-500:focus-visible{outline-color:var(--color-indigo-500)}.dark\:focus-visible\:outline-red-500:focus-visible{outline-color:var(--color-red-500)}}}:root{color-scheme:light dark;color:#ffffffde;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:#242424;font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}.plyr-mini .plyr__controls [data-plyr=rewind],.plyr-mini .plyr__controls [data-plyr=fast-forward],.plyr-mini .plyr__controls [data-plyr=volume],.plyr-mini .plyr__controls [data-plyr=settings],.plyr-mini .plyr__controls [data-plyr=pip],.plyr-mini .plyr__controls [data-plyr=airplay],.plyr-mini .plyr__time--duration{display:none!important}@media(prefers-color-scheme:light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{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-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@keyframes spin{to{transform:rotate(360deg)}}.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-iDPthw87.js b/backend/web/dist/assets/index-iDPthw87.js new file mode 100644 index 0000000..10684a7 --- /dev/null +++ b/backend/web/dist/assets/index-iDPthw87.js @@ -0,0 +1,257 @@ +function qI(s,e){for(var t=0;ti[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const r of n)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const r={};return n.integrity&&(r.integrity=n.integrity),n.referrerPolicy&&(r.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?r.credentials="include":n.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(n){if(n.ep)return;n.ep=!0;const r=t(n);fetch(n.href,r)}})();var Tp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function zI(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 R0={exports:{}},dd={};var ax;function KI(){if(ax)return dd;ax=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var o=null;if(r!==void 0&&(o=""+r),n.key!==void 0&&(o=""+n.key),"key"in n){r={};for(var u in n)u!=="key"&&(r[u]=n[u])}else r=n;return n=r.ref,{$$typeof:s,type:i,key:o,ref:n!==void 0?n:null,props:r}}return dd.Fragment=e,dd.jsx=t,dd.jsxs=t,dd}var ox;function YI(){return ox||(ox=1,R0.exports=KI()),R0.exports}var U=YI(),k0={exports:{}},ct={};var lx;function WI(){if(lx)return ct;lx=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),m=Symbol.iterator;function v($){return $===null||typeof $!="object"?null:($=m&&$[m]||$["@@iterator"],typeof $=="function"?$:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b=Object.assign,E={};function w($,se,he){this.props=$,this.context=se,this.refs=E,this.updater=he||_}w.prototype.isReactComponent={},w.prototype.setState=function($,se){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,se,"setState")},w.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function L(){}L.prototype=w.prototype;function I($,se,he){this.props=$,this.context=se,this.refs=E,this.updater=he||_}var F=I.prototype=new L;F.constructor=I,b(F,w.prototype),F.isPureReactComponent=!0;var B=Array.isArray;function V(){}var N={H:null,A:null,T:null,S:null},q=Object.prototype.hasOwnProperty;function R($,se,he){var Se=he.ref;return{$$typeof:s,type:$,key:se,ref:Se!==void 0?Se:null,props:he}}function P($,se){return R($.type,se,$.props)}function z($){return typeof $=="object"&&$!==null&&$.$$typeof===s}function ee($){var se={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(he){return se[he]})}var ie=/\/+/g;function Q($,se){return typeof $=="object"&&$!==null&&$.key!=null?ee(""+$.key):se.toString(36)}function oe($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(V,V):($.status="pending",$.then(function(se){$.status==="pending"&&($.status="fulfilled",$.value=se)},function(se){$.status==="pending"&&($.status="rejected",$.reason=se)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function H($,se,he,Se,be){var Pe=typeof $;(Pe==="undefined"||Pe==="boolean")&&($=null);var Ae=!1;if($===null)Ae=!0;else switch(Pe){case"bigint":case"string":case"number":Ae=!0;break;case"object":switch($.$$typeof){case s:case e:Ae=!0;break;case f:return Ae=$._init,H(Ae($._payload),se,he,Se,be)}}if(Ae)return be=be($),Ae=Se===""?"."+Q($,0):Se,B(be)?(he="",Ae!=null&&(he=Ae.replace(ie,"$&/")+"/"),H(be,se,he,"",function(Je){return Je})):be!=null&&(z(be)&&(be=P(be,he+(be.key==null||$&&$.key===be.key?"":(""+be.key).replace(ie,"$&/")+"/")+Ae)),se.push(be)),1;Ae=0;var Be=Se===""?".":Se+":";if(B($))for(var $e=0;$e<$.length;$e++)Se=$[$e],Pe=Be+Q(Se,$e),Ae+=H(Se,se,he,Pe,be);else if($e=v($),typeof $e=="function")for($=$e.call($),$e=0;!(Se=$.next()).done;)Se=Se.value,Pe=Be+Q(Se,$e++),Ae+=H(Se,se,he,Pe,be);else if(Pe==="object"){if(typeof $.then=="function")return H(oe($),se,he,Se,be);throw se=String($),Error("Objects are not valid as a React child (found: "+(se==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":se)+"). If you meant to render a collection of children, use an array instead.")}return Ae}function X($,se,he){if($==null)return $;var Se=[],be=0;return H($,Se,"","",function(Pe){return se.call(he,Pe,be++)}),Se}function te($){if($._status===-1){var se=$._result;se=se(),se.then(function(he){($._status===0||$._status===-1)&&($._status=1,$._result=he)},function(he){($._status===0||$._status===-1)&&($._status=2,$._result=he)}),$._status===-1&&($._status=0,$._result=se)}if($._status===1)return $._result.default;throw $._result}var ae=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var se=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(se))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},ce={map:X,forEach:function($,se,he){X($,function(){se.apply(this,arguments)},he)},count:function($){var se=0;return X($,function(){se++}),se},toArray:function($){return X($,function(se){return se})||[]},only:function($){if(!z($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return ct.Activity=g,ct.Children=ce,ct.Component=w,ct.Fragment=t,ct.Profiler=n,ct.PureComponent=I,ct.StrictMode=i,ct.Suspense=c,ct.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=N,ct.__COMPILER_RUNTIME={__proto__:null,c:function($){return N.H.useMemoCache($)}},ct.cache=function($){return function(){return $.apply(null,arguments)}},ct.cacheSignal=function(){return null},ct.cloneElement=function($,se,he){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var Se=b({},$.props),be=$.key;if(se!=null)for(Pe in se.key!==void 0&&(be=""+se.key),se)!q.call(se,Pe)||Pe==="key"||Pe==="__self"||Pe==="__source"||Pe==="ref"&&se.ref===void 0||(Se[Pe]=se[Pe]);var Pe=arguments.length-2;if(Pe===1)Se.children=he;else if(1>>1,ce=H[ae];if(0>>1;ae<$;){var se=2*(ae+1)-1,he=H[se],Se=se+1,be=H[Se];if(0>n(he,te))Sen(be,he)?(H[ae]=be,H[Se]=te,ae=Se):(H[ae]=he,H[se]=te,ae=se);else if(Sen(be,te))H[ae]=be,H[Se]=te,ae=Se;else break e}}return X}function n(H,X){var te=H.sortIndex-X.sortIndex;return te!==0?te:H.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 o=Date,u=o.now();s.unstable_now=function(){return o.now()-u}}var c=[],d=[],f=1,g=null,m=3,v=!1,_=!1,b=!1,E=!1,w=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function F(H){for(var X=t(d);X!==null;){if(X.callback===null)i(d);else if(X.startTime<=H)i(d),X.sortIndex=X.expirationTime,e(c,X);else break;X=t(d)}}function B(H){if(b=!1,F(H),!_)if(t(c)!==null)_=!0,V||(V=!0,ee());else{var X=t(d);X!==null&&oe(B,X.startTime-H)}}var V=!1,N=-1,q=5,R=-1;function P(){return E?!0:!(s.unstable_now()-RH&&P());){var ae=g.callback;if(typeof ae=="function"){g.callback=null,m=g.priorityLevel;var ce=ae(g.expirationTime<=H);if(H=s.unstable_now(),typeof ce=="function"){g.callback=ce,F(H),X=!0;break t}g===t(c)&&i(c),F(H)}else i(c);g=t(c)}if(g!==null)X=!0;else{var $=t(d);$!==null&&oe(B,$.startTime-H),X=!1}}break e}finally{g=null,m=te,v=!1}X=void 0}}finally{X?ee():V=!1}}}var ee;if(typeof I=="function")ee=function(){I(z)};else if(typeof MessageChannel<"u"){var ie=new MessageChannel,Q=ie.port2;ie.port1.onmessage=z,ee=function(){Q.postMessage(null)}}else ee=function(){w(z,0)};function oe(H,X){N=w(function(){H(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(H){H.callback=null},s.unstable_forceFrameRate=function(H){0>H||125ae?(H.sortIndex=te,e(d,H),t(c)===null&&H===t(d)&&(b?(L(N),N=-1):b=!0,oe(B,te-ae))):(H.sortIndex=ce,e(c,H),_||v||(_=!0,V||(V=!0,ee()))),H},s.unstable_shouldYield=P,s.unstable_wrapCallback=function(H){var X=m;return function(){var te=m;m=X;try{return H.apply(this,arguments)}finally{m=te}}}})(M0)),M0}var hx;function QI(){return hx||(hx=1,P0.exports=XI()),P0.exports}var N0={exports:{}},Ts={};var fx;function ZI(){if(fx)return Ts;fx=1;var s=eg();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(),N0.exports=ZI(),N0.exports}var gx;function JI(){if(gx)return hd;gx=1;var s=QI(),e=eg(),t=B2();function i(a){var l="https://react.dev/errors/"+a;if(1ce||(a.current=ae[ce],ae[ce]=null,ce--)}function he(a,l){ce++,ae[ce]=a.current,a.current=l}var Se=$(null),be=$(null),Pe=$(null),Ae=$(null);function Be(a,l){switch(he(Pe,l),he(be,a),he(Se,null),l.nodeType){case 9:case 11:a=(a=l.documentElement)&&(a=a.namespaceURI)?LS(a):0;break;default:if(a=l.tagName,l=l.namespaceURI)l=LS(l),a=IS(l,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}se(Se),he(Se,a)}function $e(){se(Se),se(be),se(Pe)}function Je(a){a.memoizedState!==null&&he(Ae,a);var l=Se.current,h=IS(l,a.type);l!==h&&(he(be,a),he(Se,h))}function ht(a){be.current===a&&(se(Se),se(be)),Ae.current===a&&(se(Ae),od._currentValue=te)}var Tt,Ni;function It(a){if(Tt===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);Tt=l&&l[1]||"",Ni=-1)":-1T||ue[p]!==Te[T]){var Le=` +`+ue[p].replace(" at new "," at ");return a.displayName&&Le.includes("")&&(Le=Le.replace("",a.displayName)),Le}while(1<=p&&0<=T);break}}}finally{Li=!1,Error.prepareStackTrace=h}return(h=a?a.displayName||a.name:"")?It(h):""}function Jt(a,l){switch(a.tag){case 26:case 27:case 5:return It(a.type);case 16:return It("Lazy");case 13:return a.child!==l&&l!==null?It("Suspense Fallback"):It("Suspense");case 19:return It("SuspenseList");case 0:case 15:return We(a.type,!1);case 11:return We(a.type.render,!1);case 1:return We(a.type,!0);case 31:return It("Activity");default:return""}}function Bt(a){try{var l="",h=null;do l+=Jt(a,h),h=a,a=a.return;while(a);return l}catch(p){return` +Error generating stack: `+p.message+` +`+p.stack}}var oi=Object.prototype.hasOwnProperty,Xe=s.unstable_scheduleCallback,_t=s.unstable_cancelCallback,Ct=s.unstable_shouldYield,Gi=s.unstable_requestPaint,$t=s.unstable_now,xs=s.unstable_getCurrentPriorityLevel,Oe=s.unstable_ImmediatePriority,Fe=s.unstable_UserBlockingPriority,je=s.unstable_NormalPriority,Qe=s.unstable_LowPriority,rt=s.unstable_IdlePriority,pt=s.log,et=s.unstable_setDisableYieldValue,ei=null,Ft=null;function ti(a){if(typeof pt=="function"&&et(a),Ft&&typeof Ft.setStrictMode=="function")try{Ft.setStrictMode(ei,a)}catch{}}var vi=Math.clz32?Math.clz32:xi,Fn=Math.log,Rt=Math.LN2;function xi(a){return a>>>=0,a===0?32:31-(Fn(a)/Rt|0)|0}var Os=256,Tn=262144,Ao=4194304;function j(a){var l=a&42;if(l!==0)return l;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function K(a,l,h){var p=a.pendingLanes;if(p===0)return 0;var T=0,S=a.suspendedLanes,O=a.pingedLanes;a=a.warmLanes;var G=p&134217727;return G!==0?(p=G&~S,p!==0?T=j(p):(O&=G,O!==0?T=j(O):h||(h=G&~a,h!==0&&(T=j(h))))):(G=p&~S,G!==0?T=j(G):O!==0?T=j(O):h||(h=p&~a,h!==0&&(T=j(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 le(a,l){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&l)===0}function xe(a,l){switch(a){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Me(){var a=Ao;return Ao<<=1,(Ao&62914560)===0&&(Ao=4194304),a}function tt(a){for(var l=[],h=0;31>h;h++)l.push(a);return l}function Ot(a,l){a.pendingLanes|=l,l!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function Yi(a,l,h,p,T,S){var O=a.pendingLanes;a.pendingLanes=h,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=h,a.entangledLanes&=h,a.errorRecoveryDisabledLanes&=h,a.shellSuspendCounter=0;var G=a.entanglements,ue=a.expirationTimes,Te=a.hiddenUpdates;for(h=O&~h;0"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var ir=/[\n"\\]/g;function rs(a){return a.replace(ir,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function hc(a,l,h,p,T,S,O,G){a.name="",O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"?a.type=O:a.removeAttribute("type"),l!=null?O==="number"?(l===0&&a.value===""||a.value!=l)&&(a.value=""+Wi(l)):a.value!==""+Wi(l)&&(a.value=""+Wi(l)):O!=="submit"&&O!=="reset"||a.removeAttribute("value"),l!=null?Lo(a,O,Wi(l)):h!=null?Lo(a,O,Wi(h)):p!=null&&a.removeAttribute("value"),T==null&&S!=null&&(a.defaultChecked=!!S),T!=null&&(a.checked=T&&typeof T!="function"&&typeof T!="symbol"),G!=null&&typeof G!="function"&&typeof G!="symbol"&&typeof G!="boolean"?a.name=""+Wi(G):a.removeAttribute("name")}function Rl(a,l,h,p,T,S,O,G){if(S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(a.type=S),l!=null||h!=null){if(!(S!=="submit"&&S!=="reset"||l!=null)){Ll(a);return}h=h!=null?""+Wi(h):"",l=l!=null?""+Wi(l):h,G||l===a.value||(a.value=l),a.defaultValue=l}p=p??T,p=typeof p!="function"&&typeof p!="symbol"&&!!p,a.checked=G?a.checked:!!p,a.defaultChecked=!!p,O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"&&(a.name=O),Ll(a)}function Lo(a,l,h){l==="number"&&Il(a.ownerDocument)===a||a.defaultValue===""+h||(a.defaultValue=""+h)}function Xi(a,l,h,p){if(a=a.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Fl=!1;if(Ps)try{var Ro={};Object.defineProperty(Ro,"passive",{get:function(){Fl=!0}}),window.addEventListener("test",Ro,Ro),window.removeEventListener("test",Ro,Ro)}catch{Fl=!1}var nr=null,Ul=null,ko=null;function hh(){if(ko)return ko;var a,l=Ul,h=l.length,p,T="value"in nr?nr.value:nr.textContent,S=T.length;for(a=0;a=Fo),xh=" ",yc=!1;function Kl(a,l){switch(a){case"keyup":return Wg.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Eh(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var Ca=!1;function Xg(a,l){switch(a){case"compositionend":return Eh(l);case"keypress":return l.which!==32?null:(yc=!0,xh);case"textInput":return a=l.data,a===xh&&yc?null:a;default:return null}}function vc(a,l){if(Ca)return a==="compositionend"||!Aa&&Kl(a,l)?(a=hh(),ko=Ul=nr=null,Ca=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1=l)return{node:h,offset:l-a};a=p}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=wa(h)}}function qr(a,l){return a&&l?a===l?!0:a&&a.nodeType===3?!1:l&&l.nodeType===3?qr(a,l.parentNode):"contains"in a?a.contains(l):a.compareDocumentPosition?!!(a.compareDocumentPosition(l)&16):!1:!1}function Yl(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var l=Il(a.document);l instanceof a.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)a=l.contentWindow;else break;l=Il(a.document)}return l}function Ec(a){var l=a&&a.nodeName&&a.nodeName.toLowerCase();return l&&(l==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||l==="textarea"||a.contentEditable==="true")}var im=Ps&&"documentMode"in document&&11>=document.documentMode,La=null,Ac=null,Ia=null,Wl=!1;function Cc(a,l,h){var p=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Wl||La==null||La!==Il(p)||(p=La,"selectionStart"in p&&Ec(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),Ia&&ar(Ia,p)||(Ia=p,p=vf(Ac,"onSelect"),0>=O,T-=O,nn=1<<32-vi(l)+T|h<gt?(Lt=Ke,Ke=null):Lt=Ke.sibling;var Nt=_e(pe,Ke,ve[gt],Re);if(Nt===null){Ke===null&&(Ke=Lt);break}a&&Ke&&Nt.alternate===null&&l(pe,Ke),de=S(Nt,de,gt),Mt===null?Ze=Nt:Mt.sibling=Nt,Mt=Nt,Ke=Lt}if(gt===ve.length)return h(pe,Ke),xt&&mt(pe,gt),Ze;if(Ke===null){for(;gtgt?(Lt=Ke,Ke=null):Lt=Ke.sibling;var to=_e(pe,Ke,Nt.value,Re);if(to===null){Ke===null&&(Ke=Lt);break}a&&Ke&&to.alternate===null&&l(pe,Ke),de=S(to,de,gt),Mt===null?Ze=to:Mt.sibling=to,Mt=to,Ke=Lt}if(Nt.done)return h(pe,Ke),xt&&mt(pe,gt),Ze;if(Ke===null){for(;!Nt.done;gt++,Nt=ve.next())Nt=ke(pe,Nt.value,Re),Nt!==null&&(de=S(Nt,de,gt),Mt===null?Ze=Nt:Mt.sibling=Nt,Mt=Nt);return xt&&mt(pe,gt),Ze}for(Ke=p(Ke);!Nt.done;gt++,Nt=ve.next())Nt=Ce(Ke,pe,gt,Nt.value,Re),Nt!==null&&(a&&Nt.alternate!==null&&Ke.delete(Nt.key===null?gt:Nt.key),de=S(Nt,de,gt),Mt===null?Ze=Nt:Mt.sibling=Nt,Mt=Nt);return a&&Ke.forEach(function(VI){return l(pe,VI)}),xt&&mt(pe,gt),Ze}function Xt(pe,de,ve,Re){if(typeof ve=="object"&&ve!==null&&ve.type===b&&ve.key===null&&(ve=ve.props.children),typeof ve=="object"&&ve!==null){switch(ve.$$typeof){case v:e:{for(var Ze=ve.key;de!==null;){if(de.key===Ze){if(Ze=ve.type,Ze===b){if(de.tag===7){h(pe,de.sibling),Re=T(de,ve.props.children),Re.return=pe,pe=Re;break e}}else if(de.elementType===Ze||typeof Ze=="object"&&Ze!==null&&Ze.$$typeof===q&&Wo(Ze)===de.type){h(pe,de.sibling),Re=T(de,ve.props),Fc(Re,ve),Re.return=pe,pe=Re;break e}h(pe,de);break}else l(pe,de);de=de.sibling}ve.type===b?(Re=lr(ve.props.children,pe.mode,Re,ve.key),Re.return=pe,pe=Re):(Re=Oc(ve.type,ve.key,ve.props,null,pe.mode,Re),Fc(Re,ve),Re.return=pe,pe=Re)}return O(pe);case _:e:{for(Ze=ve.key;de!==null;){if(de.key===Ze)if(de.tag===4&&de.stateNode.containerInfo===ve.containerInfo&&de.stateNode.implementation===ve.implementation){h(pe,de.sibling),Re=T(de,ve.children||[]),Re.return=pe,pe=Re;break e}else{h(pe,de);break}else l(pe,de);de=de.sibling}Re=Ma(ve,pe.mode,Re),Re.return=pe,pe=Re}return O(pe);case q:return ve=Wo(ve),Xt(pe,de,ve,Re)}if(oe(ve))return ze(pe,de,ve,Re);if(ee(ve)){if(Ze=ee(ve),typeof Ze!="function")throw Error(i(150));return ve=Ze.call(ve),st(pe,de,ve,Re)}if(typeof ve.then=="function")return Xt(pe,de,jh(ve),Re);if(ve.$$typeof===I)return Xt(pe,de,ot(pe,ve),Re);Hh(pe,ve)}return typeof ve=="string"&&ve!==""||typeof ve=="number"||typeof ve=="bigint"?(ve=""+ve,de!==null&&de.tag===6?(h(pe,de.sibling),Re=T(de,ve),Re.return=pe,pe=Re):(h(pe,de),Re=Vo(ve,pe.mode,Re),Re.return=pe,pe=Re),O(pe)):h(pe,de)}return function(pe,de,ve,Re){try{Bc=0;var Ze=Xt(pe,de,ve,Re);return tu=null,Ze}catch(Ke){if(Ke===eu||Ke===Uh)throw Ke;var Mt=Ei(29,Ke,null,pe.mode);return Mt.lanes=Re,Mt.return=pe,Mt}}}var Qo=__(!0),b_=__(!1),Fa=!1;function om(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function lm(a,l){a=a.updateQueue,l.updateQueue===a&&(l.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function Ua(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function $a(a,l,h){var p=a.updateQueue;if(p===null)return null;if(p=p.shared,(Ut&2)!==0){var T=p.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),p.pending=l,l=Zl(a),Ph(a,null,h),l}return Ql(a,p,l,h),Zl(a)}function Uc(a,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var p=l.lanes;p&=a.pendingLanes,h|=p,l.lanes=h,ns(a,h)}}function um(a,l){var h=a.updateQueue,p=a.alternate;if(p!==null&&(p=p.updateQueue,h===p)){var T=null,S=null;if(h=h.firstBaseUpdate,h!==null){do{var O={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};S===null?T=S=O:S=S.next=O,h=h.next}while(h!==null);S===null?T=S=l:S=S.next=l}else T=S=l;h={baseState:p.baseState,firstBaseUpdate:T,lastBaseUpdate:S,shared:p.shared,callbacks:p.callbacks},a.updateQueue=h;return}a=h.lastBaseUpdate,a===null?h.firstBaseUpdate=l:a.next=l,h.lastBaseUpdate=l}var cm=!1;function $c(){if(cm){var a=Qi;if(a!==null)throw a}}function jc(a,l,h,p){cm=!1;var T=a.updateQueue;Fa=!1;var S=T.firstBaseUpdate,O=T.lastBaseUpdate,G=T.shared.pending;if(G!==null){T.shared.pending=null;var ue=G,Te=ue.next;ue.next=null,O===null?S=Te:O.next=Te,O=ue;var Le=a.alternate;Le!==null&&(Le=Le.updateQueue,G=Le.lastBaseUpdate,G!==O&&(G===null?Le.firstBaseUpdate=Te:G.next=Te,Le.lastBaseUpdate=ue))}if(S!==null){var ke=T.baseState;O=0,Le=Te=ue=null,G=S;do{var _e=G.lane&-536870913,Ce=_e!==G.lane;if(Ce?(wt&_e)===_e:(p&_e)===_e){_e!==0&&_e===xn&&(cm=!0),Le!==null&&(Le=Le.next={lane:0,tag:G.tag,payload:G.payload,callback:null,next:null});e:{var ze=a,st=G;_e=l;var Xt=h;switch(st.tag){case 1:if(ze=st.payload,typeof ze=="function"){ke=ze.call(Xt,ke,_e);break e}ke=ze;break e;case 3:ze.flags=ze.flags&-65537|128;case 0:if(ze=st.payload,_e=typeof ze=="function"?ze.call(Xt,ke,_e):ze,_e==null)break e;ke=g({},ke,_e);break e;case 2:Fa=!0}}_e=G.callback,_e!==null&&(a.flags|=64,Ce&&(a.flags|=8192),Ce=T.callbacks,Ce===null?T.callbacks=[_e]:Ce.push(_e))}else Ce={lane:_e,tag:G.tag,payload:G.payload,callback:G.callback,next:null},Le===null?(Te=Le=Ce,ue=ke):Le=Le.next=Ce,O|=_e;if(G=G.next,G===null){if(G=T.shared.pending,G===null)break;Ce=G,G=Ce.next,Ce.next=null,T.lastBaseUpdate=Ce,T.shared.pending=null}}while(!0);Le===null&&(ue=ke),T.baseState=ue,T.firstBaseUpdate=Te,T.lastBaseUpdate=Le,S===null&&(T.shared.lanes=0),qa|=O,a.lanes=O,a.memoizedState=ke}}function S_(a,l){if(typeof a!="function")throw Error(i(191,a));a.call(l)}function x_(a,l){var h=a.callbacks;if(h!==null)for(a.callbacks=null,a=0;aS?S:8;var O=H.T,G={};H.T=G,Lm(a,!1,l,h);try{var ue=T(),Te=H.S;if(Te!==null&&Te(G,ue),ue!==null&&typeof ue=="object"&&typeof ue.then=="function"){var Le=OL(ue,p);Vc(a,l,Le,un(a))}else Vc(a,l,p,un(a))}catch(ke){Vc(a,l,{then:function(){},status:"rejected",reason:ke},un())}finally{X.p=S,O!==null&&G.types!==null&&(O.types=G.types),H.T=O}}function UL(){}function Dm(a,l,h,p){if(a.tag!==5)throw Error(i(476));var T=tb(a).queue;eb(a,T,l,te,h===null?UL:function(){return ib(a),h(p)})}function tb(a){var l=a.memoizedState;if(l!==null)return l;l={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Xr,lastRenderedState:te},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Xr,lastRenderedState:h},next:null},a.memoizedState=l,a=a.alternate,a!==null&&(a.memoizedState=l),l}function ib(a){var l=tb(a);l.next===null&&(l=a.alternate.memoizedState),Vc(a,l.next.queue,{},un())}function wm(){return Ge(od)}function sb(){return Oi().memoizedState}function nb(){return Oi().memoizedState}function $L(a){for(var l=a.return;l!==null;){switch(l.tag){case 24:case 3:var h=un();a=Ua(h);var p=$a(l,a,h);p!==null&&(Vs(p,l,h),Uc(p,l,h)),l={cache:Yr()},a.payload=l;return}l=l.return}}function jL(a,l,h){var p=un();h={lane:p,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},Zh(a)?ab(l,h):(h=Rc(a,l,h,p),h!==null&&(Vs(h,a,p),ob(h,l,p)))}function rb(a,l,h){var p=un();Vc(a,l,h,p)}function Vc(a,l,h,p){var T={lane:p,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(Zh(a))ab(l,T);else{var S=a.alternate;if(a.lanes===0&&(S===null||S.lanes===0)&&(S=l.lastRenderedReducer,S!==null))try{var O=l.lastRenderedState,G=S(O,h);if(T.hasEagerState=!0,T.eagerState=G,ys(G,O))return Ql(a,l,T,0),si===null&&Xl(),!1}catch{}if(h=Rc(a,l,T,p),h!==null)return Vs(h,a,p),ob(h,l,p),!0}return!1}function Lm(a,l,h,p){if(p={lane:2,revertLane:o0(),gesture:null,action:p,hasEagerState:!1,eagerState:null,next:null},Zh(a)){if(l)throw Error(i(479))}else l=Rc(a,h,p,2),l!==null&&Vs(l,a,2)}function Zh(a){var l=a.alternate;return a===ft||l!==null&&l===ft}function ab(a,l){su=qh=!0;var h=a.pending;h===null?l.next=l:(l.next=h.next,h.next=l),a.pending=l}function ob(a,l,h){if((h&4194048)!==0){var p=l.lanes;p&=a.pendingLanes,h|=p,l.lanes=h,ns(a,h)}}var qc={readContext:Ge,use:Yh,useCallback:Ai,useContext:Ai,useEffect:Ai,useImperativeHandle:Ai,useLayoutEffect:Ai,useInsertionEffect:Ai,useMemo:Ai,useReducer:Ai,useRef:Ai,useState:Ai,useDebugValue:Ai,useDeferredValue:Ai,useTransition:Ai,useSyncExternalStore:Ai,useId:Ai,useHostTransitionStatus:Ai,useFormState:Ai,useActionState:Ai,useOptimistic:Ai,useMemoCache:Ai,useCacheRefresh:Ai};qc.useEffectEvent=Ai;var lb={readContext:Ge,use:Yh,useCallback:function(a,l){return Ds().memoizedState=[a,l===void 0?null:l],a},useContext:Ge,useEffect:q_,useImperativeHandle:function(a,l,h){h=h!=null?h.concat([a]):null,Xh(4194308,4,W_.bind(null,l,a),h)},useLayoutEffect:function(a,l){return Xh(4194308,4,a,l)},useInsertionEffect:function(a,l){Xh(4,2,a,l)},useMemo:function(a,l){var h=Ds();l=l===void 0?null:l;var p=a();if(Zo){ti(!0);try{a()}finally{ti(!1)}}return h.memoizedState=[p,l],p},useReducer:function(a,l,h){var p=Ds();if(h!==void 0){var T=h(l);if(Zo){ti(!0);try{h(l)}finally{ti(!1)}}}else T=l;return p.memoizedState=p.baseState=T,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:T},p.queue=a,a=a.dispatch=jL.bind(null,ft,a),[p.memoizedState,a]},useRef:function(a){var l=Ds();return a={current:a},l.memoizedState=a},useState:function(a){a=Sm(a);var l=a.queue,h=rb.bind(null,ft,l);return l.dispatch=h,[a.memoizedState,h]},useDebugValue:Am,useDeferredValue:function(a,l){var h=Ds();return Cm(h,a,l)},useTransition:function(){var a=Sm(!1);return a=eb.bind(null,ft,a.queue,!0,!1),Ds().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,l,h){var p=ft,T=Ds();if(xt){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),si===null)throw Error(i(349));(wt&127)!==0||L_(p,l,h)}T.memoizedState=h;var S={value:h,getSnapshot:l};return T.queue=S,q_(R_.bind(null,p,S,a),[a]),p.flags|=2048,ru(9,{destroy:void 0},I_.bind(null,p,S,h,l),null),h},useId:function(){var a=Ds(),l=si.identifierPrefix;if(xt){var h=as,p=nn;h=(p&~(1<<32-vi(p)-1)).toString(32)+h,l="_"+l+"R_"+h,h=zh++,0<\/script>",S=S.removeChild(S.firstChild);break;case"select":S=typeof p.is=="string"?O.createElement("select",{is:p.is}):O.createElement("select"),p.multiple?S.multiple=!0:p.size&&(S.size=p.size);break;default:S=typeof p.is=="string"?O.createElement(T,{is:p.is}):O.createElement(T)}}S[Pt]=l,S[Dt]=p;e:for(O=l.child;O!==null;){if(O.tag===5||O.tag===6)S.appendChild(O.stateNode);else if(O.tag!==4&&O.tag!==27&&O.child!==null){O.child.return=O,O=O.child;continue}if(O===l)break e;for(;O.sibling===null;){if(O.return===null||O.return===l)break e;O=O.return}O.sibling.return=O.return,O=O.sibling}l.stateNode=S;e:switch(ls(S,T,p),T){case"button":case"input":case"select":case"textarea":p=!!p.autoFocus;break e;case"img":p=!0;break e;default:p=!1}p&&Zr(l)}}return hi(l),Gm(l,l.type,a===null?null:a.memoizedProps,l.pendingProps,h),null;case 6:if(a&&l.stateNode!=null)a.memoizedProps!==p&&Zr(l);else{if(typeof p!="string"&&l.stateNode===null)throw Error(i(166));if(a=Pe.current,y(l)){if(a=l.stateNode,h=l.memoizedProps,p=null,T=Fi,T!==null)switch(T.tag){case 27:case 5:p=T.memoizedProps}a[Pt]=l,a=!!(a.nodeValue===h||p!==null&&p.suppressHydrationWarning===!0||DS(a.nodeValue,h)),a||hr(l,!0)}else a=Tf(a).createTextNode(p),a[Pt]=l,l.stateNode=a}return hi(l),null;case 31:if(h=l.memoizedState,a===null||a.memoizedState!==null){if(p=y(l),h!==null){if(a===null){if(!p)throw Error(i(318));if(a=l.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(i(557));a[Pt]=l}else x(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;hi(l),a=!1}else h=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=h),a=!0;if(!a)return l.flags&256?(an(l),l):(an(l),null);if((l.flags&128)!==0)throw Error(i(558))}return hi(l),null;case 13:if(p=l.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(T=y(l),p!==null&&p.dehydrated!==null){if(a===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[Pt]=l}else x(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;hi(l),T=!1}else T=C(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(an(l),l):(an(l),null)}return an(l),(l.flags&128)!==0?(l.lanes=h,l):(h=p!==null,a=a!==null&&a.memoizedState!==null,h&&(p=l.child,T=null,p.alternate!==null&&p.alternate.memoizedState!==null&&p.alternate.memoizedState.cachePool!==null&&(T=p.alternate.memoizedState.cachePool.pool),S=null,p.memoizedState!==null&&p.memoizedState.cachePool!==null&&(S=p.memoizedState.cachePool.pool),S!==T&&(p.flags|=2048)),h!==a&&h&&(l.child.flags|=8192),nf(l,l.updateQueue),hi(l),null);case 4:return $e(),a===null&&d0(l.stateNode.containerInfo),hi(l),null;case 10:return J(l.type),hi(l),null;case 19:if(se(ki),p=l.memoizedState,p===null)return hi(l),null;if(T=(l.flags&128)!==0,S=p.rendering,S===null)if(T)Kc(p,!1);else{if(Ci!==0||a!==null&&(a.flags&128)!==0)for(a=l.child;a!==null;){if(S=Vh(a),S!==null){for(l.flags|=128,Kc(p,!1),a=S.updateQueue,l.updateQueue=a,nf(l,a),l.subtreeFlags=0,a=h,h=l.child;h!==null;)Mh(h,a),h=h.sibling;return he(ki,ki.current&1|2),xt&&mt(l,p.treeForkCount),l.child}a=a.sibling}p.tail!==null&&$t()>uf&&(l.flags|=128,T=!0,Kc(p,!1),l.lanes=4194304)}else{if(!T)if(a=Vh(S),a!==null){if(l.flags|=128,T=!0,a=a.updateQueue,l.updateQueue=a,nf(l,a),Kc(p,!0),p.tail===null&&p.tailMode==="hidden"&&!S.alternate&&!xt)return hi(l),null}else 2*$t()-p.renderingStartTime>uf&&h!==536870912&&(l.flags|=128,T=!0,Kc(p,!1),l.lanes=4194304);p.isBackwards?(S.sibling=l.child,l.child=S):(a=p.last,a!==null?a.sibling=S:l.child=S,p.last=S)}return p.tail!==null?(a=p.tail,p.rendering=a,p.tail=a.sibling,p.renderingStartTime=$t(),a.sibling=null,h=ki.current,he(ki,T?h&1|2:h&1),xt&&mt(l,p.treeForkCount),a):(hi(l),null);case 22:case 23:return an(l),hm(),p=l.memoizedState!==null,a!==null?a.memoizedState!==null!==p&&(l.flags|=8192):p&&(l.flags|=8192),p?(h&536870912)!==0&&(l.flags&128)===0&&(hi(l),l.subtreeFlags&6&&(l.flags|=8192)):hi(l),h=l.updateQueue,h!==null&&nf(l,h.retryQueue),h=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(h=a.memoizedState.cachePool.pool),p=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(p=l.memoizedState.cachePool.pool),p!==h&&(l.flags|=2048),a!==null&&se(Yo),null;case 24:return h=null,a!==null&&(h=a.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),J(ui),hi(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function zL(a,l){switch(Fs(l),l.tag){case 1:return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 3:return J(ui),$e(),a=l.flags,(a&65536)!==0&&(a&128)===0?(l.flags=a&-65537|128,l):null;case 26:case 27:case 5:return ht(l),null;case 31:if(l.memoizedState!==null){if(an(l),l.alternate===null)throw Error(i(340));x()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 13:if(an(l),a=l.memoizedState,a!==null&&a.dehydrated!==null){if(l.alternate===null)throw Error(i(340));x()}return a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 19:return se(ki),null;case 4:return $e(),null;case 10:return J(l.type),null;case 22:case 23:return an(l),hm(),a!==null&&se(Yo),a=l.flags,a&65536?(l.flags=a&-65537|128,l):null;case 24:return J(ui),null;case 25:return null;default:return null}}function kb(a,l){switch(Fs(l),l.tag){case 3:J(ui),$e();break;case 26:case 27:case 5:ht(l);break;case 4:$e();break;case 31:l.memoizedState!==null&&an(l);break;case 13:an(l);break;case 19:se(ki);break;case 10:J(l.type);break;case 22:case 23:an(l),hm(),a!==null&&se(Yo);break;case 24:J(ui)}}function Yc(a,l){try{var h=l.updateQueue,p=h!==null?h.lastEffect:null;if(p!==null){var T=p.next;h=T;do{if((h.tag&a)===a){p=void 0;var S=h.create,O=h.inst;p=S(),O.destroy=p}h=h.next}while(h!==T)}}catch(G){Vt(l,l.return,G)}}function Ga(a,l,h){try{var p=l.updateQueue,T=p!==null?p.lastEffect:null;if(T!==null){var S=T.next;p=S;do{if((p.tag&a)===a){var O=p.inst,G=O.destroy;if(G!==void 0){O.destroy=void 0,T=l;var ue=h,Te=G;try{Te()}catch(Le){Vt(T,ue,Le)}}}p=p.next}while(p!==S)}}catch(Le){Vt(l,l.return,Le)}}function Ob(a){var l=a.updateQueue;if(l!==null){var h=a.stateNode;try{x_(l,h)}catch(p){Vt(a,a.return,p)}}}function Pb(a,l,h){h.props=Jo(a.type,a.memoizedProps),h.state=a.memoizedState;try{h.componentWillUnmount()}catch(p){Vt(a,l,p)}}function Wc(a,l){try{var h=a.ref;if(h!==null){switch(a.tag){case 26:case 27:case 5:var p=a.stateNode;break;case 30:p=a.stateNode;break;default:p=a.stateNode}typeof h=="function"?a.refCleanup=h(p):h.current=p}}catch(T){Vt(a,l,T)}}function gr(a,l){var h=a.ref,p=a.refCleanup;if(h!==null)if(typeof p=="function")try{p()}catch(T){Vt(a,l,T)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){Vt(a,l,T)}else h.current=null}function Mb(a){var l=a.type,h=a.memoizedProps,p=a.stateNode;try{e:switch(l){case"button":case"input":case"select":case"textarea":h.autoFocus&&p.focus();break e;case"img":h.src?p.src=h.src:h.srcSet&&(p.srcset=h.srcSet)}}catch(T){Vt(a,a.return,T)}}function Vm(a,l,h){try{var p=a.stateNode;pI(p,a.type,h,l),p[Dt]=l}catch(T){Vt(a,a.return,T)}}function Nb(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&Xa(a.type)||a.tag===4}function qm(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||Nb(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&Xa(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function zm(a,l,h){var p=a.tag;if(p===5||p===6)a=a.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(a,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(a),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=jn));else if(p!==4&&(p===27&&Xa(a.type)&&(h=a.stateNode,l=null),a=a.child,a!==null))for(zm(a,l,h),a=a.sibling;a!==null;)zm(a,l,h),a=a.sibling}function rf(a,l,h){var p=a.tag;if(p===5||p===6)a=a.stateNode,l?h.insertBefore(a,l):h.appendChild(a);else if(p!==4&&(p===27&&Xa(a.type)&&(h=a.stateNode),a=a.child,a!==null))for(rf(a,l,h),a=a.sibling;a!==null;)rf(a,l,h),a=a.sibling}function Bb(a){var l=a.stateNode,h=a.memoizedProps;try{for(var p=a.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);ls(l,p,h),l[Pt]=a,l[Dt]=h}catch(S){Vt(a,a.return,S)}}var Jr=!1,ji=!1,Km=!1,Fb=typeof WeakSet=="function"?WeakSet:Set,Zi=null;function KL(a,l){if(a=a.containerInfo,p0=Cf,a=Yl(a),Ec(a)){if("selectionStart"in a)var h={start:a.selectionStart,end:a.selectionEnd};else e:{h=(h=a.ownerDocument)&&h.defaultView||window;var p=h.getSelection&&h.getSelection();if(p&&p.rangeCount!==0){h=p.anchorNode;var T=p.anchorOffset,S=p.focusNode;p=p.focusOffset;try{h.nodeType,S.nodeType}catch{h=null;break e}var O=0,G=-1,ue=-1,Te=0,Le=0,ke=a,_e=null;t:for(;;){for(var Ce;ke!==h||T!==0&&ke.nodeType!==3||(G=O+T),ke!==S||p!==0&&ke.nodeType!==3||(ue=O+p),ke.nodeType===3&&(O+=ke.nodeValue.length),(Ce=ke.firstChild)!==null;)_e=ke,ke=Ce;for(;;){if(ke===a)break t;if(_e===h&&++Te===T&&(G=O),_e===S&&++Le===p&&(ue=O),(Ce=ke.nextSibling)!==null)break;ke=_e,_e=ke.parentNode}ke=Ce}h=G===-1||ue===-1?null:{start:G,end:ue}}else h=null}h=h||{start:0,end:0}}else h=null;for(g0={focusedElem:a,selectionRange:h},Cf=!1,Zi=l;Zi!==null;)if(l=Zi,a=l.child,(l.subtreeFlags&1028)!==0&&a!==null)a.return=l,Zi=a;else for(;Zi!==null;){switch(l=Zi,S=l.alternate,a=l.flags,l.tag){case 0:if((a&4)!==0&&(a=l.updateQueue,a=a!==null?a.events:null,a!==null))for(h=0;h title"))),ls(S,p,h),S[Pt]=a,Bi(S),p=S;break e;case"link":var O=VS("link","href",T).get(p+(h.href||""));if(O){for(var G=0;GXt&&(O=Xt,Xt=st,st=O);var pe=fi(G,st),de=fi(G,Xt);if(pe&&de&&(Ce.rangeCount!==1||Ce.anchorNode!==pe.node||Ce.anchorOffset!==pe.offset||Ce.focusNode!==de.node||Ce.focusOffset!==de.offset)){var ve=ke.createRange();ve.setStart(pe.node,pe.offset),Ce.removeAllRanges(),st>Xt?(Ce.addRange(ve),Ce.extend(de.node,de.offset)):(ve.setEnd(de.node,de.offset),Ce.addRange(ve))}}}}for(ke=[],Ce=G;Ce=Ce.parentNode;)Ce.nodeType===1&&ke.push({element:Ce,left:Ce.scrollLeft,top:Ce.scrollTop});for(typeof G.focus=="function"&&G.focus(),G=0;Gh?32:h,H.T=null,h=e0,e0=null;var S=Ka,O=na;if(qi=0,cu=Ka=null,na=0,(Ut&6)!==0)throw Error(i(331));var G=Ut;if(Ut|=4,Wb(S.current),zb(S,S.current,O,h),Ut=G,td(0,!1),Ft&&typeof Ft.onPostCommitFiberRoot=="function")try{Ft.onPostCommitFiberRoot(ei,S)}catch{}return!0}finally{X.p=T,H.T=p,fS(a,l)}}function gS(a,l,h){l=Ns(h,l),l=Om(a.stateNode,l,2),a=$a(a,l,2),a!==null&&(Ot(a,2),mr(a))}function Vt(a,l,h){if(a.tag===3)gS(a,a,h);else for(;l!==null;){if(l.tag===3){gS(l,a,h);break}else if(l.tag===1){var p=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(za===null||!za.has(p))){a=Ns(h,a),h=mb(2),p=$a(l,h,2),p!==null&&(yb(h,p,l,a),Ot(p,2),mr(p));break}}l=l.return}}function n0(a,l,h){var p=a.pingCache;if(p===null){p=a.pingCache=new XL;var T=new Set;p.set(l,T)}else T=p.get(l),T===void 0&&(T=new Set,p.set(l,T));T.has(h)||(Xm=!0,T.add(h),a=tI.bind(null,a,l,h),l.then(a,a))}function tI(a,l,h){var p=a.pingCache;p!==null&&p.delete(l),a.pingedLanes|=a.suspendedLanes&h,a.warmLanes&=~h,si===a&&(wt&h)===h&&(Ci===4||Ci===3&&(wt&62914560)===wt&&300>$t()-lf?(Ut&2)===0&&du(a,0):Qm|=h,uu===wt&&(uu=0)),mr(a)}function mS(a,l){l===0&&(l=Me()),a=Kr(a,l),a!==null&&(Ot(a,l),mr(a))}function iI(a){var l=a.memoizedState,h=0;l!==null&&(h=l.retryLane),mS(a,h)}function sI(a,l){var h=0;switch(a.tag){case 31:case 13:var p=a.stateNode,T=a.memoizedState;T!==null&&(h=T.retryLane);break;case 19:p=a.stateNode;break;case 22:p=a.stateNode._retryCache;break;default:throw Error(i(314))}p!==null&&p.delete(l),mS(a,h)}function nI(a,l){return Xe(a,l)}var gf=null,fu=null,r0=!1,mf=!1,a0=!1,Wa=0;function mr(a){a!==fu&&a.next===null&&(fu===null?gf=fu=a:fu=fu.next=a),mf=!0,r0||(r0=!0,aI())}function td(a,l){if(!a0&&mf){a0=!0;do for(var h=!1,p=gf;p!==null;){if(a!==0){var T=p.pendingLanes;if(T===0)var S=0;else{var O=p.suspendedLanes,G=p.pingedLanes;S=(1<<31-vi(42|a)+1)-1,S&=T&~(O&~G),S=S&201326741?S&201326741|1:S?S|2:0}S!==0&&(h=!0,_S(p,S))}else S=wt,S=K(p,p===si?S:0,p.cancelPendingCommit!==null||p.timeoutHandle!==-1),(S&3)===0||le(p,S)||(h=!0,_S(p,S));p=p.next}while(h);a0=!1}}function rI(){yS()}function yS(){mf=r0=!1;var a=0;Wa!==0&&mI()&&(a=Wa);for(var l=$t(),h=null,p=gf;p!==null;){var T=p.next,S=vS(p,l);S===0?(p.next=null,h===null?gf=T:h.next=T,T===null&&(fu=h)):(h=p,(a!==0||(S&3)!==0)&&(mf=!0)),p=T}qi!==0&&qi!==5||td(a),Wa!==0&&(Wa=0)}function vS(a,l){for(var h=a.suspendedLanes,p=a.pingedLanes,T=a.expirationTimes,S=a.pendingLanes&-62914561;0G)break;var Le=ue.transferSize,ke=ue.initiatorType;Le&&wS(ke)&&(ue=ue.responseEnd,O+=Le*(ue"u"?null:document;function $S(a,l,h){var p=pu;if(p&&typeof l=="string"&&l){var T=rs(l);T='link[rel="'+a+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),US.has(T)||(US.add(T),a={rel:a,crossOrigin:h,href:l},p.querySelector(T)===null&&(l=p.createElement("link"),ls(l,"link",a),Bi(l),p.head.appendChild(l)))}}function AI(a){ra.D(a),$S("dns-prefetch",a,null)}function CI(a,l){ra.C(a,l),$S("preconnect",a,l)}function DI(a,l,h){ra.L(a,l,h);var p=pu;if(p&&a&&l){var T='link[rel="preload"][as="'+rs(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+rs(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+rs(h.imageSizes)+'"]')):T+='[href="'+rs(a)+'"]';var S=T;switch(l){case"style":S=gu(a);break;case"script":S=mu(a)}Cn.has(S)||(a=g({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:a,as:l},h),Cn.set(S,a),p.querySelector(T)!==null||l==="style"&&p.querySelector(rd(S))||l==="script"&&p.querySelector(ad(S))||(l=p.createElement("link"),ls(l,"link",a),Bi(l),p.head.appendChild(l)))}}function wI(a,l){ra.m(a,l);var h=pu;if(h&&a){var p=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+rs(p)+'"][href="'+rs(a)+'"]',S=T;switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":S=mu(a)}if(!Cn.has(S)&&(a=g({rel:"modulepreload",href:a},l),Cn.set(S,a),h.querySelector(T)===null)){switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(ad(S)))return}p=h.createElement("link"),ls(p,"link",a),Bi(p),h.head.appendChild(p)}}}function LI(a,l,h){ra.S(a,l,h);var p=pu;if(p&&a){var T=Ta(p).hoistableStyles,S=gu(a);l=l||"default";var O=T.get(S);if(!O){var G={loading:0,preload:null};if(O=p.querySelector(rd(S)))G.loading=5;else{a=g({rel:"stylesheet",href:a,"data-precedence":l},h),(h=Cn.get(S))&&S0(a,h);var ue=O=p.createElement("link");Bi(ue),ls(ue,"link",a),ue._p=new Promise(function(Te,Le){ue.onload=Te,ue.onerror=Le}),ue.addEventListener("load",function(){G.loading|=1}),ue.addEventListener("error",function(){G.loading|=2}),G.loading|=4,bf(O,l,p)}O={type:"stylesheet",instance:O,count:1,state:G},T.set(S,O)}}}function II(a,l){ra.X(a,l);var h=pu;if(h&&a){var p=Ta(h).hoistableScripts,T=mu(a),S=p.get(T);S||(S=h.querySelector(ad(T)),S||(a=g({src:a,async:!0},l),(l=Cn.get(T))&&x0(a,l),S=h.createElement("script"),Bi(S),ls(S,"link",a),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},p.set(T,S))}}function RI(a,l){ra.M(a,l);var h=pu;if(h&&a){var p=Ta(h).hoistableScripts,T=mu(a),S=p.get(T);S||(S=h.querySelector(ad(T)),S||(a=g({src:a,async:!0,type:"module"},l),(l=Cn.get(T))&&x0(a,l),S=h.createElement("script"),Bi(S),ls(S,"link",a),h.head.appendChild(S)),S={type:"script",instance:S,count:1,state:null},p.set(T,S))}}function jS(a,l,h,p){var T=(T=Pe.current)?_f(T):null;if(!T)throw Error(i(446));switch(a){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=gu(h.href),h=Ta(T).hoistableStyles,p=h.get(l),p||(p={type:"style",instance:null,count:0,state:null},h.set(l,p)),p):{type:"void",instance:null,count:0,state:null};case"link":if(h.rel==="stylesheet"&&typeof h.href=="string"&&typeof h.precedence=="string"){a=gu(h.href);var S=Ta(T).hoistableStyles,O=S.get(a);if(O||(T=T.ownerDocument||T,O={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},S.set(a,O),(S=T.querySelector(rd(a)))&&!S._p&&(O.instance=S,O.state.loading=5),Cn.has(a)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},Cn.set(a,h),S||kI(T,a,h,O.state))),l&&p===null)throw Error(i(528,""));return O}if(l&&p!==null)throw Error(i(529,""));return null;case"script":return l=h.async,h=h.src,typeof h=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=mu(h),h=Ta(T).hoistableScripts,p=h.get(l),p||(p={type:"script",instance:null,count:0,state:null},h.set(l,p)),p):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,a))}}function gu(a){return'href="'+rs(a)+'"'}function rd(a){return'link[rel="stylesheet"]['+a+"]"}function HS(a){return g({},a,{"data-precedence":a.precedence,precedence:null})}function kI(a,l,h,p){a.querySelector('link[rel="preload"][as="style"]['+l+"]")?p.loading=1:(l=a.createElement("link"),p.preload=l,l.addEventListener("load",function(){return p.loading|=1}),l.addEventListener("error",function(){return p.loading|=2}),ls(l,"link",h),Bi(l),a.head.appendChild(l))}function mu(a){return'[src="'+rs(a)+'"]'}function ad(a){return"script[async]"+a}function GS(a,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var p=a.querySelector('style[data-href~="'+rs(h.href)+'"]');if(p)return l.instance=p,Bi(p),p;var T=g({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return p=(a.ownerDocument||a).createElement("style"),Bi(p),ls(p,"style",T),bf(p,h.precedence,a),l.instance=p;case"stylesheet":T=gu(h.href);var S=a.querySelector(rd(T));if(S)return l.state.loading|=4,l.instance=S,Bi(S),S;p=HS(h),(T=Cn.get(T))&&S0(p,T),S=(a.ownerDocument||a).createElement("link"),Bi(S);var O=S;return O._p=new Promise(function(G,ue){O.onload=G,O.onerror=ue}),ls(S,"link",p),l.state.loading|=4,bf(S,h.precedence,a),l.instance=S;case"script":return S=mu(h.src),(T=a.querySelector(ad(S)))?(l.instance=T,Bi(T),T):(p=h,(T=Cn.get(S))&&(p=g({},h),x0(p,T)),a=a.ownerDocument||a,T=a.createElement("script"),Bi(T),ls(T,"link",p),a.head.appendChild(T),l.instance=T);case"void":return null;default:throw Error(i(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(p=l.instance,l.state.loading|=4,bf(p,h.precedence,a));return l.instance}function bf(a,l,h){for(var p=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=p.length?p[p.length-1]:null,S=T,O=0;O title"):null)}function OI(a,l,h){if(h===1||l.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(a=l.disabled,typeof l.precedence=="string"&&a==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function zS(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function PI(a,l,h,p){if(h.type==="stylesheet"&&(typeof p.media!="string"||matchMedia(p.media).matches!==!1)&&(h.state.loading&4)===0){if(h.instance===null){var T=gu(p.href),S=l.querySelector(rd(T));if(S){l=S._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(a.count++,a=xf.bind(a),l.then(a,a)),h.state.loading|=4,h.instance=S,Bi(S);return}S=l.ownerDocument||l,p=HS(p),(T=Cn.get(T))&&S0(p,T),S=S.createElement("link"),Bi(S);var O=S;O._p=new Promise(function(G,ue){O.onload=G,O.onerror=ue}),ls(S,"link",p),h.instance=S}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(a.count++,h=xf.bind(a),l.addEventListener("load",h),l.addEventListener("error",h))}}var E0=0;function MI(a,l){return a.stylesheets&&a.count===0&&Af(a,a.stylesheets),0E0?50:800)+l);return a.unsuspend=h,function(){a.unsuspend=null,clearTimeout(p),clearTimeout(T)}}:null}function xf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Af(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var Ef=null;function Af(a,l){a.stylesheets=null,a.unsuspend!==null&&(a.count++,Ef=new Map,l.forEach(NI,a),Ef=null,xf.call(a))}function NI(a,l){if(!(l.state.loading&4)){var h=Ef.get(a);if(h)var p=h.get(null);else{h=new Map,Ef.set(a,h);for(var T=a.querySelectorAll("link[data-precedence],style[data-precedence]"),S=0;S"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),O0.exports=JI(),O0.exports}var tR=eR();function iR(...s){return s.filter(Boolean).join(" ")}const sR="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",nR={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},rR={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"},aR={indigo:{primary:"bg-indigo-600 text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30"},blue:{primary:"bg-blue-600 text-white shadow-xs hover:bg-blue-500 focus-visible:outline-blue-600 dark:bg-blue-500 dark:shadow-none dark:hover:bg-blue-400 dark:focus-visible:outline-blue-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30"},emerald:{primary:"bg-emerald-600 text-white shadow-xs hover:bg-emerald-500 focus-visible:outline-emerald-600 dark:bg-emerald-500 dark:shadow-none dark:hover:bg-emerald-400 dark:focus-visible:outline-emerald-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30"},red:{primary:"bg-red-600 text-white shadow-xs hover:bg-red-500 focus-visible:outline-red-600 dark:bg-red-500 dark:shadow-none dark:hover:bg-red-400 dark:focus-visible:outline-red-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-red-50 text-red-700 shadow-xs hover:bg-red-100 dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30"},amber:{primary:"bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:outline-amber-500 dark:bg-amber-500 dark:shadow-none dark:hover:bg-amber-400 dark:focus-visible:outline-amber-500",secondary:"bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20",soft:"bg-amber-50 text-amber-800 shadow-xs hover:bg-amber-100 dark:bg-amber-500/20 dark:text-amber-300 dark:shadow-none dark:hover:bg-amber-500/30"}};function oR(){return U.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[U.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),U.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function ci({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:o,isLoading:u=!1,disabled:c,className:d,type:f="button",...g}){const m=r||o||u?"gap-x-1.5":"";return U.jsxs("button",{type:f,disabled:c||u,className:iR(sR,nR[n],rR[i],aR[t][e],m,d),...g,children:[u?U.jsx("span",{className:"-ml-0.5",children:U.jsx(oR,{})}):r&&U.jsx("span",{className:"-ml-0.5",children:r}),U.jsx("span",{children:s}),o&&!u&&U.jsx("span",{className:"-mr-0.5",children:o})]})}function F2(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?lR(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,B0=(s,e,t)=>(uR(s,typeof e!="symbol"?e+"":e,t),t);let cR=class{constructor(){B0(this,"current",this.detect()),B0(this,"handoffState","pending"),B0(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"}},Rr=new cR;function Qd(s){var e;return Rr.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function Zy(s){var e,t;return Rr.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function U2(s){var e,t;return(t=(e=Zy(s))==null?void 0:e.activeElement)!=null?t:null}function dR(s){return U2(s)===s}function ig(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function va(){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 ig(()=>{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=va();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 sg(){let[s]=Y.useState(va);return Y.useEffect(()=>()=>s.dispose(),[s]),s}let Qs=(s,e)=>{Rr.isServer?Y.useEffect(s,e):Y.useLayoutEffect(s,e)};function Al(s){let e=Y.useRef(s);return Qs(()=>{e.current=s},[s]),e}let ri=function(s){let e=Al(s);return lt.useCallback((...t)=>e.current(...t),[e])};function Zd(s){return Y.useMemo(()=>s,Object.values(s))}let hR=Y.createContext(void 0);function fR(){return Y.useContext(hR)}function Jy(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function ma(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,ma),i}var _p=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(_p||{}),mo=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(mo||{});function Mn(){let s=gR();return Y.useCallback(e=>pR({mergeRefs:s,...e}),[s])}function pR({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:o,mergeRefs:u}){u=u??mR;let c=$2(e,s);if(r)return Of(c,t,i,o,u);let d=n??0;if(d&2){let{static:f=!1,...g}=c;if(f)return Of(g,t,i,o,u)}if(d&1){let{unmount:f=!0,...g}=c;return ma(f?0:1,{0(){return null},1(){return Of({...g,hidden:!0,style:{display:"none"}},t,i,o,u)}})}return Of(c,t,i,o,u)}function Of(s,e={},t,i,n){let{as:r=t,children:o,refName:u="ref",...c}=F0(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof o=="function"?o(e):o;"className"in c&&c.className&&typeof c.className=="function"&&(c.className=c.className(e)),c["aria-labelledby"]&&c["aria-labelledby"]===c.id&&(c["aria-labelledby"]=void 0);let g={};if(e){let m=!1,v=[];for(let[_,b]of Object.entries(e))typeof b=="boolean"&&(m=!0),b===!0&&v.push(_.replace(/([A-Z])/g,E=>`-${E.toLowerCase()}`));if(m){g["data-headlessui-state"]=v.join(" ");for(let _ of v)g[`data-${_}`]=""}}if(Dd(r)&&(Object.keys(ol(c)).length>0||Object.keys(ol(g)).length>0))if(!Y.isValidElement(f)||Array.isArray(f)&&f.length>1||vR(f)){if(Object.keys(ol(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(ol(c)).concat(Object.keys(ol(g))).map(m=>` - ${m}`).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(m=>` - ${m}`).join(` +`)].join(` +`))}else{let m=f.props,v=m?.className,_=typeof v=="function"?(...w)=>Jy(v(...w),c.className):Jy(v,c.className),b=_?{className:_}:{},E=$2(f.props,ol(F0(c,["ref"])));for(let w in g)w in E&&delete g[w];return Y.cloneElement(f,Object.assign({},E,g,d,{ref:n(yR(f),d.ref)},b))}return Y.createElement(r,Object.assign({},F0(c,["ref"]),!Dd(r)&&d,!Dd(r)&&g),f)}function gR(){let s=Y.useRef([]),e=Y.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 mR(...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 $2(...s){if(s.length===0)return{};if(s.length===1)return s[0];let e={},t={};for(let i of s)for(let n in i)n.startsWith("on")&&typeof i[n]=="function"?(t[n]!=null||(t[n]=[]),t[n].push(i[n])):e[n]=i[n];if(e.disabled||e["aria-disabled"])for(let i in t)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(i)&&(t[i]=[n=>{var r;return(r=n?.preventDefault)==null?void 0:r.call(n)}]);for(let i in t)Object.assign(e,{[i](n,...r){let o=t[i];for(let u of o){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function Js(s){var e;return Object.assign(Y.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function ol(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function F0(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function yR(s){return lt.version.split(".")[0]>="19"?s.props.ref:s.ref}function Dd(s){return s===Y.Fragment||s===Symbol.for("react.fragment")}function vR(s){return Dd(s.type)}let TR="span";var bp=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(bp||{});function _R(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 Mn()({ourProps:r,theirProps:n,slot:{},defaultTag:TR,name:"Hidden"})}let ev=Js(_R);function bR(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function vo(s){return bR(s)&&"tagName"in s}function bl(s){return vo(s)&&"accessKey"in s}function yo(s){return vo(s)&&"tabIndex"in s}function SR(s){return vo(s)&&"style"in s}function xR(s){return bl(s)&&s.nodeName==="IFRAME"}function ER(s){return bl(s)&&s.nodeName==="INPUT"}let j2=Symbol();function AR(s,e=!0){return Object.assign(s,{[j2]:e})}function Br(...s){let e=Y.useRef(s);Y.useEffect(()=>{e.current=s},[s]);let t=ri(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[j2])?void 0:t}let Jv=Y.createContext(null);Jv.displayName="DescriptionContext";function H2(){let s=Y.useContext(Jv);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,H2),e}return s}function CR(){let[s,e]=Y.useState([]);return[s.length>0?s.join(" "):void 0,Y.useMemo(()=>function(t){let i=ri(r=>(e(o=>[...o,r]),()=>e(o=>{let u=o.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=Y.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 lt.createElement(Jv.Provider,{value:n},t.children)},[e])]}let DR="p";function wR(s,e){let t=Y.useId(),i=fR(),{id:n=`headlessui-description-${t}`,...r}=s,o=H2(),u=Br(e);Qs(()=>o.register(n),[n,o.register]);let c=Zd({...o.slot,disabled:i||!1}),d={ref:u,...o.props,id:n};return Mn()({ourProps:d,theirProps:r,slot:c,defaultTag:DR,name:o.name||"Description"})}let LR=Js(wR),IR=Object.assign(LR,{});var G2=(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))(G2||{});let RR=Y.createContext(()=>{});function kR({value:s,children:e}){return lt.createElement(RR.Provider,{value:s},e)}let V2=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 OR=Object.defineProperty,PR=(s,e,t)=>e in s?OR(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,MR=(s,e,t)=>(PR(s,e+"",t),t),q2=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Dn=(s,e,t)=>(q2(s,e,"read from private field"),t?t.call(s):e.get(s)),U0=(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)},yx=(s,e,t,i)=>(q2(s,e,"write to private field"),e.set(s,t),t),_r,_d,bd;let NR=class{constructor(e){U0(this,_r,{}),U0(this,_d,new V2(()=>new Set)),U0(this,bd,new Set),MR(this,"disposables",va()),yx(this,_r,e),Rr.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return Dn(this,_r)}subscribe(e,t){if(Rr.isServer)return()=>{};let i={selector:e,callback:t,current:e(Dn(this,_r))};return Dn(this,bd).add(i),this.disposables.add(()=>{Dn(this,bd).delete(i)})}on(e,t){return Rr.isServer?()=>{}:(Dn(this,_d).get(e).add(t),this.disposables.add(()=>{Dn(this,_d).get(e).delete(t)}))}send(e){let t=this.reduce(Dn(this,_r),e);if(t!==Dn(this,_r)){yx(this,_r,t);for(let i of Dn(this,bd)){let n=i.selector(Dn(this,_r));z2(i.current,n)||(i.current=n,i.callback(n))}for(let i of Dn(this,_d).get(e.type))i(Dn(this,_r),e)}}};_r=new WeakMap,_d=new WeakMap,bd=new WeakMap;function z2(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:$0(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:$0(s.entries(),e.entries()):vx(s)&&vx(e)?$0(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function $0(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 vx(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var BR=Object.defineProperty,FR=(s,e,t)=>e in s?BR(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tx=(s,e,t)=>(FR(s,typeof e!="symbol"?e+"":e,t),t),UR=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(UR||{});let $R={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}}},jR=class K2 extends NR{constructor(){super(...arguments),Tx(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),Tx(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new K2({stack:[]})}reduce(e,t){return ma(t.type,$R,e,t)}};const Y2=new V2(()=>jR.new());var j0={exports:{}},H0={};var _x;function HR(){if(_x)return H0;_x=1;var s=eg();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var t=typeof Object.is=="function"?Object.is:e,i=s.useSyncExternalStore,n=s.useRef,r=s.useEffect,o=s.useMemo,u=s.useDebugValue;return H0.useSyncExternalStoreWithSelector=function(c,d,f,g,m){var v=n(null);if(v.current===null){var _={hasValue:!1,value:null};v.current=_}else _=v.current;v=o(function(){function E(B){if(!w){if(w=!0,L=B,B=g(B),m!==void 0&&_.hasValue){var V=_.value;if(m(V,B))return I=V}return I=B}if(V=I,t(L,B))return V;var N=g(B);return m!==void 0&&m(V,N)?(L=B,V):(L=B,I=N)}var w=!1,L,I,F=f===void 0?null:f;return[function(){return E(d())},F===null?void 0:function(){return E(F())}]},[d,f,g,m]);var b=i(c,v[0],v[1]);return r(function(){_.hasValue=!0,_.value=b},[b]),u(b),b},H0}var bx;function GR(){return bx||(bx=1,j0.exports=HR()),j0.exports}var VR=GR();function W2(s,e,t=z2){return VR.useSyncExternalStoreWithSelector(ri(i=>s.subscribe(qR,i)),ri(()=>s.state),ri(()=>s.state),ri(e),t)}function qR(s){return s}function Jd(s,e){let t=Y.useId(),i=Y2.get(e),[n,r]=W2(i,Y.useCallback(o=>[i.selectors.isTop(o,t),i.selectors.inStack(o,t)],[i,t]));return Qs(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let tv=new Map,wd=new Map;function Sx(s){var e;let t=(e=wd.get(s))!=null?e:0;return wd.set(s,t+1),t!==0?()=>xx(s):(tv.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>xx(s))}function xx(s){var e;let t=(e=wd.get(s))!=null?e:1;if(t===1?wd.delete(s):wd.set(s,t-1),t!==1)return;let i=tv.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,tv.delete(s))}function zR(s,{allowed:e,disallowed:t}={}){let i=Jd(s,"inert-others");Qs(()=>{var n,r;if(!i)return;let o=va();for(let c of(n=t?.())!=null?n:[])c&&o.add(Sx(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=Qd(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let g of f.children)u.some(m=>g.contains(m))||o.add(Sx(g));f=f.parentElement}}return o.dispose},[i,e,t])}function KR(s,e,t){let i=Al(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});Y.useEffect(()=>{if(!s)return;let n=e===null?null:bl(e)?e:e.current;if(!n)return;let r=va();if(typeof ResizeObserver<"u"){let o=new ResizeObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}if(typeof IntersectionObserver<"u"){let o=new IntersectionObserver(()=>i.current(n));o.observe(n),r.add(()=>o.disconnect())}return()=>r.dispose()},[e,i,s])}let 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(","),YR=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var da=(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))(da||{}),iv=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(iv||{}),WR=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(WR||{});function XR(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 QR(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(YR)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var X2=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(X2||{});function ZR(s,e=0){var t;return s===((t=Qd(s))==null?void 0:t.body)?!1:ma(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 JR=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(JR||{});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 pa(s){s?.focus({preventScroll:!0})}let ek=["textarea","input"].join(",");function tk(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,ek))!=null?t:!1}function ik(s,e=t=>t){return s.slice().sort((t,i)=>{let n=e(t),r=e(i);if(n===null||r===null)return 0;let o=n.compareDocumentPosition(r);return o&Node.DOCUMENT_POSITION_FOLLOWING?-1:o&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function Ld(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?Zy(s[0]):document:Zy(s),o=Array.isArray(s)?t?ik(s):s:e&64?QR(s):XR(s);n.length>0&&o.length>1&&(o=o.filter(v=>!n.some(_=>_!=null&&"current"in _?_?.current===v:_===v))),i=i??r?.activeElement;let u=(()=>{if(e&5)return 1;if(e&10)return-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),c=(()=>{if(e&1)return 0;if(e&2)return Math.max(0,o.indexOf(i))-1;if(e&4)return Math.max(0,o.indexOf(i))+1;if(e&8)return o.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,g=o.length,m;do{if(f>=g||f+g<=0)return 0;let v=c+f;if(e&16)v=(v+g)%g;else{if(v<0)return 3;if(v>=g)return 1}m=o[v],m?.focus(d),f+=u}while(m!==U2(m));return e&6&&tk(m)&&m.select(),2}function Q2(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function sk(){return/Android/gi.test(window.navigator.userAgent)}function Ex(){return Q2()||sk()}function Pf(s,e,t,i){let n=Al(t);Y.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function Z2(s,e,t,i){let n=Al(t);Y.useEffect(()=>{if(!s)return;function r(o){n.current(o)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const Ax=30;function nk(s,e,t){let i=Al(t),n=Y.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 g(m){return typeof m=="function"?g(m()):Array.isArray(m)||m instanceof Set?m:[m]})(e);for(let g of f)if(g!==null&&(g.contains(d)||u.composed&&u.composedPath().includes(g)))return;return!ZR(d,X2.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=Y.useRef(null);Pf(s,"pointerdown",u=>{var c,d;Ex()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),Pf(s,"pointerup",u=>{if(Ex()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let o=Y.useRef({x:0,y:0});Pf(s,"touchstart",u=>{o.current.x=u.touches[0].clientX,o.current.y=u.touches[0].clientY},!0),Pf(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-o.current.x)>=Ax||Math.abs(c.y-o.current.y)>=Ax))return n(u,()=>yo(u.target)?u.target:null)},!0),Z2(s,"blur",u=>n(u,()=>xR(window.document.activeElement)?window.document.activeElement:null),!0)}function eT(...s){return Y.useMemo(()=>Qd(...s),[...s])}function J2(s,e,t,i){let n=Al(t);Y.useEffect(()=>{s=s??window;function r(o){n.current(o)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function rk(s){return Y.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function ak(s,e){let t=s(),i=new Set;return{getSnapshot(){return t},subscribe(n){return i.add(n),()=>i.delete(n)},dispatch(n,...r){let o=e[n].call(t,...r);o&&(t=o,i.forEach(u=>u()))}}}function ok(){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 lk(){return Q2()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let o of r())if(o.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=va();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,o=null;e.addEventListener(s,"click",u=>{if(yo(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);yo(f)&&!i(f)&&(o=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),yo(c.target)&&SR(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(yo(u.target)){if(ER(u.target))return;if(i(u.target)){let c=u.target;for(;c.parentElement&&c.dataset.headlessuiPortal!==""&&!(c.scrollHeight>c.clientHeight||c.scrollWidth>c.clientWidth);)c=c.parentElement;c.dataset.headlessuiPortal===""&&u.preventDefault()}else u.preventDefault()}},{passive:!1}),e.add(()=>{var u;let c=(u=window.scrollY)!=null?u:window.pageYOffset;r!==c&&window.scrollTo(0,r),o&&o.isConnected&&(o.scrollIntoView({block:"nearest"}),o=null)})})}}:{}}function uk(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function Cx(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let hl=ak(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:va(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=Cx(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=Cx(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[lk(),ok(),uk()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});hl.subscribe(()=>{let s=hl.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)&&hl.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&hl.dispatch("TEARDOWN",t)}});function ck(s,e,t=()=>({containers:[]})){let i=rk(hl),n=e?i.get(e):void 0,r=n?n.count>0:!1;return Qs(()=>{if(!(!e||!s))return hl.dispatch("PUSH",e,t),()=>hl.dispatch("POP",e,t)},[s,e]),r}function dk(s,e,t=()=>[document.body]){let i=Jd(s,"scroll-lock");ck(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function hk(s=0){let[e,t]=Y.useState(s),i=Y.useCallback(c=>t(c),[]),n=Y.useCallback(c=>t(d=>d|c),[]),r=Y.useCallback(c=>(e&c)===c,[e]),o=Y.useCallback(c=>t(d=>d&~c),[]),u=Y.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:o,toggleFlag:u}}var fk={},Dx,wx;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((Dx=process==null?void 0:fk)==null?void 0:Dx.NODE_ENV)==="test"&&typeof((wx=Element?.prototype)==null?void 0:wx.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 pk=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(pk||{});function gk(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function mk(s,e,t,i){let[n,r]=Y.useState(t),{hasFlag:o,addFlag:u,removeFlag:c}=hk(s&&n?3:0),d=Y.useRef(!1),f=Y.useRef(!1),g=sg();return Qs(()=>{var m;if(s){if(t&&r(!0),!e){t&&u(3);return}return(m=i?.start)==null||m.call(i,t),yk(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&&_k(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,g]),s?[n,{closed:o(1),enter:o(2),leave:o(4),transition:o(2)||o(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function yk(s,{prepare:e,run:t,done:i,inFlight:n}){let r=va();return Tk(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(vk(s,i))})}),r.dispose}function vk(s,e){var t,i;let n=va();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let o=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return o.length===0?(e(),n.dispose):(Promise.allSettled(o.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function Tk(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 _k(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 tT(s,e){let t=Y.useRef([]),i=ri(s);Y.useEffect(()=>{let n=[...t.current];for(let[r,o]of e.entries())if(t.current[r]!==o){let u=i(e,n);return t.current=e,u}},[i,...e])}let ng=Y.createContext(null);ng.displayName="OpenClosedContext";var Qn=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(Qn||{});function rg(){return Y.useContext(ng)}function bk({value:s,children:e}){return lt.createElement(ng.Provider,{value:s},e)}function Sk({children:s}){return lt.createElement(ng.Provider,{value:null},s)}function xk(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let go=[];xk(()=>{function s(e){if(!yo(e.target)||e.target===document.body||go[0]===e.target)return;let t=e.target;t=t.closest(Sp),go.unshift(t??e.target),go=go.filter(i=>i!=null&&i.isConnected),go.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 eA(s){let e=ri(s),t=Y.useRef(!1);Y.useEffect(()=>(t.current=!1,()=>{t.current=!0,ig(()=>{t.current&&e()})}),[e])}let tA=Y.createContext(!1);function Ek(){return Y.useContext(tA)}function Lx(s){return lt.createElement(tA.Provider,{value:s.force},s.children)}function Ak(s){let e=Ek(),t=Y.useContext(sA),[i,n]=Y.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(Rr.isServer)return null;let o=s?.getElementById("headlessui-portal-root");if(o)return o;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return Y.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),Y.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let iA=Y.Fragment,Ck=Js(function(s,e){let{ownerDocument:t=null,...i}=s,n=Y.useRef(null),r=Br(AR(m=>{n.current=m}),e),o=eT(n.current),u=t??o,c=Ak(u),d=Y.useContext(sv),f=sg(),g=Mn();return eA(()=>{var m;c&&c.childNodes.length<=0&&((m=c.parentElement)==null||m.removeChild(c))}),c?tg.createPortal(lt.createElement("div",{"data-headlessui-portal":"",ref:m=>{f.dispose(),d&&m&&f.add(d.register(m))}},g({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:iA,name:"Portal"})),c):null});function Dk(s,e){let t=Br(e),{enabled:i=!0,ownerDocument:n,...r}=s,o=Mn();return i?lt.createElement(Ck,{...r,ownerDocument:n,ref:t}):o({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:iA,name:"Portal"})}let wk=Y.Fragment,sA=Y.createContext(null);function Lk(s,e){let{target:t,...i}=s,n={ref:Br(e)},r=Mn();return lt.createElement(sA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:wk,name:"Popover.Group"}))}let sv=Y.createContext(null);function Ik(){let s=Y.useContext(sv),e=Y.useRef([]),t=ri(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=ri(r=>{let o=e.current.indexOf(r);o!==-1&&e.current.splice(o,1),s&&s.unregister(r)}),n=Y.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,Y.useMemo(()=>function({children:r}){return lt.createElement(sv.Provider,{value:n},r)},[n])]}let Rk=Js(Dk),nA=Js(Lk),kk=Object.assign(Rk,{Group:nA});function Ok(s,e=typeof document<"u"?document.defaultView:null,t){let i=Jd(s,"escape");J2(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===G2.Escape&&t(n))})}function Pk(){var s;let[e]=Y.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=Y.useState((s=e?.matches)!=null?s:!1);return Qs(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function Mk({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=ri(()=>{var n,r;let o=Qd(t),u=[];for(let c of s)c!==null&&(vo(c)?u.push(c):"current"in c&&vo(c.current)&&u.push(c.current));if(e!=null&&e.current)for(let c of e.current)u.push(c);for(let c of(n=o?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&vo(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:ri(n=>i().some(r=>r.contains(n)))}}let rA=Y.createContext(null);function Ix({children:s,node:e}){let[t,i]=Y.useState(null),n=aA(e??t);return lt.createElement(rA.Provider,{value:n},s,n===null&<.createElement(ev,{features:bp.Hidden,ref:r=>{var o,u;if(r){for(let c of(u=(o=Qd(r))==null?void 0:o.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&vo(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function aA(s=null){var e;return(e=Y.useContext(rA))!=null?e:s}function Nk(){let s=typeof document>"u";return"useSyncExternalStore"in cx?(e=>e.useSyncExternalStore)(cx)(()=>()=>{},()=>!1,()=>!s):!1}function ag(){let s=Nk(),[e,t]=Y.useState(Rr.isHandoffComplete);return e&&Rr.isHandoffComplete===!1&&t(!1),Y.useEffect(()=>{e!==!0&&t(!0)},[e]),Y.useEffect(()=>Rr.handoff(),[]),s?!1:e}function iT(){let s=Y.useRef(!1);return Qs(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var Sd=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(Sd||{});function Bk(){let s=Y.useRef(0);return Z2(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function oA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)vo(t.current)&&e.add(t.current);return e}let Fk="div";var cl=(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))(cl||{});function Uk(s,e){let t=Y.useRef(null),i=Br(t,e),{initialFocus:n,initialFocusFallback:r,containers:o,features:u=15,...c}=s;ag()||(u=0);let d=eT(t.current);Gk(u,{ownerDocument:d});let f=Vk(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});qk(u,{ownerDocument:d,container:t,containers:o,previousActiveElement:f});let g=Bk(),m=ri(L=>{if(!bl(t.current))return;let I=t.current;(F=>F())(()=>{ma(g.current,{[Sd.Forwards]:()=>{Ld(I,da.First,{skipElements:[L.relatedTarget,r]})},[Sd.Backwards]:()=>{Ld(I,da.Last,{skipElements:[L.relatedTarget,r]})}})})}),v=Jd(!!(u&2),"focus-trap#tab-lock"),_=sg(),b=Y.useRef(!1),E={ref:i,onKeyDown(L){L.key=="Tab"&&(b.current=!0,_.requestAnimationFrame(()=>{b.current=!1}))},onBlur(L){if(!(u&4))return;let I=oA(o);bl(t.current)&&I.add(t.current);let F=L.relatedTarget;yo(F)&&F.dataset.headlessuiFocusGuard!=="true"&&(lA(I,F)||(b.current?Ld(t.current,ma(g.current,{[Sd.Forwards]:()=>da.Next,[Sd.Backwards]:()=>da.Previous})|da.WrapAround,{relativeTo:L.target}):yo(L.target)&&pa(L.target)))}},w=Mn();return lt.createElement(lt.Fragment,null,v&<.createElement(ev,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:m,features:bp.Focusable}),w({ourProps:E,theirProps:c,defaultTag:Fk,name:"FocusTrap"}),v&<.createElement(ev,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:m,features:bp.Focusable}))}let $k=Js(Uk),jk=Object.assign($k,{features:cl});function Hk(s=!0){let e=Y.useRef(go.slice());return tT(([t],[i])=>{i===!0&&t===!1&&ig(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=go.slice())},[s,go,e]),ri(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function Gk(s,{ownerDocument:e}){let t=!!(s&8),i=Hk(t);tT(()=>{t||dR(e?.body)&&pa(i())},[t]),eA(()=>{t&&pa(i())})}function Vk(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=Y.useRef(null),o=Jd(!!(s&1),"focus-trap#initial-focus"),u=iT();return tT(()=>{if(s===0)return;if(!o){n!=null&&n.current&&pa(n.current);return}let c=t.current;c&&ig(()=>{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)pa(i.current);else{if(s&16){if(Ld(c,da.First|da.AutoFocus)!==iv.Error)return}else if(Ld(c,da.First)!==iv.Error)return;if(n!=null&&n.current&&(pa(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,o,s]),r}function qk(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=iT(),o=!!(s&4);J2(e?.defaultView,"focus",u=>{if(!o||!r.current)return;let c=oA(i);bl(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;bl(f)?lA(c,f)?(n.current=f,pa(f)):(u.preventDefault(),u.stopPropagation(),pa(d)):pa(n.current)},!0)}function lA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function uA(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!Dd((e=s.as)!=null?e:dA)||lt.Children.count(s.children)===1}let og=Y.createContext(null);og.displayName="TransitionContext";var zk=(s=>(s.Visible="visible",s.Hidden="hidden",s))(zk||{});function Kk(){let s=Y.useContext(og);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function Yk(){let s=Y.useContext(lg);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let lg=Y.createContext(null);lg.displayName="NestingContext";function ug(s){return"children"in s?ug(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function cA(s,e){let t=Al(s),i=Y.useRef([]),n=iT(),r=sg(),o=ri((v,_=mo.Hidden)=>{let b=i.current.findIndex(({el:E})=>E===v);b!==-1&&(ma(_,{[mo.Unmount](){i.current.splice(b,1)},[mo.Hidden](){i.current[b].state="hidden"}}),r.microTask(()=>{var E;!ug(i)&&n.current&&((E=t.current)==null||E.call(t))}))}),u=ri(v=>{let _=i.current.find(({el:b})=>b===v);return _?_.state!=="visible"&&(_.state="visible"):i.current.push({el:v,state:"visible"}),()=>o(v,mo.Unmount)}),c=Y.useRef([]),d=Y.useRef(Promise.resolve()),f=Y.useRef({enter:[],leave:[]}),g=ri((v,_,b)=>{c.current.splice(0),e&&(e.chains.current[_]=e.chains.current[_].filter(([E])=>E!==v)),e?.chains.current[_].push([v,new Promise(E=>{c.current.push(E)})]),e?.chains.current[_].push([v,new Promise(E=>{Promise.all(f.current[_].map(([w,L])=>L)).then(()=>E())})]),_==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>b(_)):b(_)}),m=ri((v,_,b)=>{Promise.all(f.current[_].splice(0).map(([E,w])=>w)).then(()=>{var E;(E=c.current.shift())==null||E()}).then(()=>b(_))});return Y.useMemo(()=>({children:i,register:u,unregister:o,onStart:g,onStop:m,wait:d,chains:f}),[u,o,i,g,m,f,d])}let dA=Y.Fragment,hA=_p.RenderStrategy;function Wk(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:o,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:g,entered:m,leave:v,leaveFrom:_,leaveTo:b,...E}=s,[w,L]=Y.useState(null),I=Y.useRef(null),F=uA(s),B=Br(...F?[I,e,L]:e===null?[]:[e]),V=(t=E.unmount)==null||t?mo.Unmount:mo.Hidden,{show:N,appear:q,initial:R}=Kk(),[P,z]=Y.useState(N?"visible":"hidden"),ee=Yk(),{register:ie,unregister:Q}=ee;Qs(()=>ie(I),[ie,I]),Qs(()=>{if(V===mo.Hidden&&I.current){if(N&&P!=="visible"){z("visible");return}return ma(P,{hidden:()=>Q(I),visible:()=>ie(I)})}},[P,I,ie,Q,N,V]);let oe=ag();Qs(()=>{if(F&&oe&&P==="visible"&&I.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[I,P,oe,F]);let H=R&&!q,X=q&&N&&R,te=Y.useRef(!1),ae=cA(()=>{te.current||(z("hidden"),Q(I))},ee),ce=ri(Ae=>{te.current=!0;let Be=Ae?"enter":"leave";ae.onStart(I,Be,$e=>{$e==="enter"?r?.():$e==="leave"&&u?.()})}),$=ri(Ae=>{let Be=Ae?"enter":"leave";te.current=!1,ae.onStop(I,Be,$e=>{$e==="enter"?o?.():$e==="leave"&&c?.()}),Be==="leave"&&!ug(ae)&&(z("hidden"),Q(I))});Y.useEffect(()=>{F&&n||(ce(N),$(N))},[N,F,n]);let se=!(!n||!F||!oe||H),[,he]=mk(se,w,N,{start:ce,end:$}),Se=ol({ref:B,className:((i=Jy(E.className,X&&d,X&&f,he.enter&&d,he.enter&&he.closed&&f,he.enter&&!he.closed&&g,he.leave&&v,he.leave&&!he.closed&&_,he.leave&&he.closed&&b,!he.transition&&N&&m))==null?void 0:i.trim())||void 0,...gk(he)}),be=0;P==="visible"&&(be|=Qn.Open),P==="hidden"&&(be|=Qn.Closed),N&&P==="hidden"&&(be|=Qn.Opening),!N&&P==="visible"&&(be|=Qn.Closing);let Pe=Mn();return lt.createElement(lg.Provider,{value:ae},lt.createElement(bk,{value:be},Pe({ourProps:Se,theirProps:E,defaultTag:dA,features:hA,visible:P==="visible",name:"Transition.Child"})))}function Xk(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,o=Y.useRef(null),u=uA(s),c=Br(...u?[o,e]:e===null?[]:[e]);ag();let d=rg();if(t===void 0&&d!==null&&(t=(d&Qn.Open)===Qn.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,g]=Y.useState(t?"visible":"hidden"),m=cA(()=>{t||g("hidden")}),[v,_]=Y.useState(!0),b=Y.useRef([t]);Qs(()=>{v!==!1&&b.current[b.current.length-1]!==t&&(b.current.push(t),_(!1))},[b,t]);let E=Y.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);Qs(()=>{t?g("visible"):!ug(m)&&o.current!==null&&g("hidden")},[t,m]);let w={unmount:n},L=ri(()=>{var B;v&&_(!1),(B=s.beforeEnter)==null||B.call(s)}),I=ri(()=>{var B;v&&_(!1),(B=s.beforeLeave)==null||B.call(s)}),F=Mn();return lt.createElement(lg.Provider,{value:m},lt.createElement(og.Provider,{value:E},F({ourProps:{...w,as:Y.Fragment,children:lt.createElement(fA,{ref:c,...w,...r,beforeEnter:L,beforeLeave:I})},theirProps:{},defaultTag:Y.Fragment,features:hA,visible:f==="visible",name:"Transition"})))}function Qk(s,e){let t=Y.useContext(og)!==null,i=rg()!==null;return lt.createElement(lt.Fragment,null,!t&&i?lt.createElement(nv,{ref:e,...s}):lt.createElement(fA,{ref:e,...s}))}let nv=Js(Xk),fA=Js(Wk),sT=Js(Qk),op=Object.assign(nv,{Child:sT,Root:nv});var Zk=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(Zk||{}),Jk=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(Jk||{});let eO={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},nT=Y.createContext(null);nT.displayName="DialogContext";function cg(s){let e=Y.useContext(nT);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,cg),t}return e}function tO(s,e){return ma(e.type,eO,s,e)}let Rx=Js(function(s,e){let t=Y.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:o,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...g}=s,m=Y.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(m.current||(m.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=rg();n===void 0&&v!==null&&(n=(v&Qn.Open)===Qn.Open);let _=Y.useRef(null),b=Br(_,e),E=eT(_.current),w=n?0:1,[L,I]=Y.useReducer(tO,{titleId:null,descriptionId:null,panelRef:Y.createRef()}),F=ri(()=>r(!1)),B=ri(he=>I({type:0,id:he})),V=ag()?w===0:!1,[N,q]=Ik(),R={get current(){var he;return(he=L.panelRef.current)!=null?he:_.current}},P=aA(),{resolveContainers:z}=Mk({mainTreeNode:P,portals:N,defaultContainers:[R]}),ee=v!==null?(v&Qn.Closing)===Qn.Closing:!1;zR(d||ee?!1:V,{allowed:ri(()=>{var he,Se;return[(Se=(he=_.current)==null?void 0:he.closest("[data-headlessui-portal]"))!=null?Se:null]}),disallowed:ri(()=>{var he;return[(he=P?.closest("body > *:not(#headlessui-portal-root)"))!=null?he:null]})});let ie=Y2.get(null);Qs(()=>{if(V)return ie.actions.push(i),()=>ie.actions.pop(i)},[ie,i,V]);let Q=W2(ie,Y.useCallback(he=>ie.selectors.isTop(he,i),[ie,i]));nk(Q,z,he=>{he.preventDefault(),F()}),Ok(Q,E?.defaultView,he=>{he.preventDefault(),he.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),F()}),dk(d||ee?!1:V,E,z),KR(V,_,F);let[oe,H]=CR(),X=Y.useMemo(()=>[{dialogState:w,close:F,setTitleId:B,unmount:f},L],[w,F,B,f,L]),te=Zd({open:w===0}),ae={ref:b,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:w===0?!0:void 0,"aria-labelledby":L.titleId,"aria-describedby":oe,unmount:f},ce=!Pk(),$=cl.None;V&&!d&&($|=cl.RestoreFocus,$|=cl.TabLock,c&&($|=cl.AutoFocus),ce&&($|=cl.InitialFocus));let se=Mn();return lt.createElement(Sk,null,lt.createElement(Lx,{force:!0},lt.createElement(kk,null,lt.createElement(nT.Provider,{value:X},lt.createElement(nA,{target:_},lt.createElement(Lx,{force:!1},lt.createElement(H,{slot:te},lt.createElement(q,null,lt.createElement(jk,{initialFocus:o,initialFocusFallback:_,containers:z,features:$},lt.createElement(kR,{value:F},se({ourProps:ae,theirProps:g,slot:te,defaultTag:iO,features:sO,visible:w===0,name:"Dialog"})))))))))))}),iO="div",sO=_p.RenderStrategy|_p.Static;function nO(s,e){let{transition:t=!1,open:i,...n}=s,r=rg(),o=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!o&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!o)throw new Error("You provided an `onClose` prop to the `Dialog`, but forgot an `open` prop.");if(!u)throw new Error("You provided an `open` prop to the `Dialog`, but forgot an `onClose` prop.");if(!r&&typeof s.open!="boolean")throw new Error(`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${s.open}`);if(typeof s.onClose!="function")throw new Error(`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${s.onClose}`);return(i!==void 0||t)&&!n.static?lt.createElement(Ix,null,lt.createElement(op,{show:i,transition:t,unmount:n.unmount},lt.createElement(Rx,{ref:e,...n}))):lt.createElement(Ix,null,lt.createElement(Rx,{ref:e,open:i,...n}))}let rO="div";function aO(s,e){let t=Y.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:o,unmount:u},c]=cg("Dialog.Panel"),d=Br(e,c.panelRef),f=Zd({open:o===0}),g=ri(E=>{E.stopPropagation()}),m={ref:d,id:i,onClick:g},v=n?sT:Y.Fragment,_=n?{unmount:u}:{},b=Mn();return lt.createElement(v,{..._},b({ourProps:m,theirProps:r,slot:f,defaultTag:rO,name:"Dialog.Panel"}))}let oO="div";function lO(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=cg("Dialog.Backdrop"),o=Zd({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?sT:Y.Fragment,d=t?{unmount:r}:{},f=Mn();return lt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:o,defaultTag:oO,name:"Dialog.Backdrop"}))}let uO="h2";function cO(s,e){let t=Y.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:o}]=cg("Dialog.Title"),u=Br(e);Y.useEffect(()=>(o(i),()=>o(null)),[i,o]);let c=Zd({open:r===0}),d={ref:u,id:i};return Mn()({ourProps:d,theirProps:n,slot:c,defaultTag:uO,name:"Dialog.Title"})}let dO=Js(nO),hO=Js(aO);Js(lO);let fO=Js(cO),ku=Object.assign(dO,{Panel:hO,Title:fO,Description:IR});function pO({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=Y.useState(""),[o,u]=Y.useState(""),[c,d]=Y.useState([]),f=Y.useRef(!1);Y.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function g(){const _=n.trim(),b=o.trim();!_||!b||(d(E=>[...E.filter(L=>L.name!==_),{name:_,value:b}]),r(""),u(""))}function m(_){d(b=>b.filter(E=>E.name!==_))}function v(){t(c),e()}return U.jsxs(ku,{open:s,onClose:e,className:"relative z-50",children:[U.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),U.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:U.jsxs(ku.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:[U.jsx(ku.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),U.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[U.jsx("input",{value:n,onChange:_=>r(_.target.value),placeholder:"Name (z. B. cf_clearance)",className:"col-span-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),U.jsx("input",{value:o,onChange:_=>u(_.target.value),placeholder:"Wert",className:"col-span-1 sm:col-span-2 rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]}),U.jsx("div",{className:"mt-2",children:U.jsx(ci,{size:"sm",variant:"secondary",onClick:g,disabled:!n.trim()||!o.trim(),children:"Hinzufügen"})}),U.jsx("div",{className:"mt-4",children:c.length===0?U.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):U.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[U.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:U.jsxs("tr",{children:[U.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),U.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),U.jsx("th",{className:"px-3 py-2"})]})}),U.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(_=>U.jsxs("tr",{children:[U.jsx("td",{className:"px-3 py-2 font-mono",children:_.name}),U.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:_.value}),U.jsx("td",{className:"px-3 py-2 text-right",children:U.jsx("button",{onClick:()=>m(_.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},_.name))})]})}),U.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[U.jsx(ci,{variant:"secondary",onClick:e,children:"Abbrechen"}),U.jsx(ci,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function In({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:o=!1,className:u,bodyClassName:c,children:d}){const f=r;return U.jsxs("div",{className:kt("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&&U.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),U.jsx("div",{className:kt("min-h-0",o?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&U.jsx("div",{className:kt("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 gO({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 mO=Y.forwardRef(gO);function yO({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:o=!1}){if(!s?.length)return null;const u=s.find(m=>m.id===e)??s[0],c=kt("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=m=>kt(m?"bg-indigo-100 text-indigo-600 dark:bg-indigo-500/20 dark:text-indigo-400":"bg-gray-100 text-gray-900 dark:bg-white/10 dark:text-gray-300",o?"ml-3 hidden rounded-full px-2.5 py-0.5 text-xs font-medium md:inline-block":"ml-3 rounded-full px-2.5 py-0.5 text-xs font-medium"),f=(m,v)=>v.count===void 0?null:U.jsx("span",{className:d(m),children:v.count}),g=()=>{switch(r){case"underline":case"underlineIcons":return U.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:U.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(m=>{const v=m.id===u.id,_=!!m.disabled;return U.jsxs("button",{type:"button",onClick:()=>!_&&t(m.id),disabled:_,"aria-current":v?"page":void 0,className:kt(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",_&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[r==="underlineIcons"&&m.icon?U.jsx(m.icon,{"aria-hidden":"true",className:kt(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,U.jsx("span",{children:m.label}),f(v,m)]},m.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const m=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 U.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(_=>{const b=_.id===u.id,E=!!_.disabled;return U.jsxs("button",{type:"button",onClick:()=>!E&&t(_.id),disabled:E,"aria-current":b?"page":void 0,className:kt(b?m: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:[U.jsx("span",{children:_.label}),_.count!==void 0?U.jsx("span",{className:kt(b?"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:_.count}):null]},_.id)})})}case"fullWidthUnderline":return U.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:U.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(m=>{const v=m.id===u.id,_=!!m.disabled;return U.jsx("button",{type:"button",onClick:()=>!_&&t(m.id),disabled:_,"aria-current":v?"page":void 0,className:kt(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",_&&"cursor-not-allowed opacity-50 hover:border-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:m.label},m.id)})})});case"barUnderline":return U.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((m,v)=>{const _=m.id===u.id,b=!!m.disabled;return U.jsxs("button",{type:"button",onClick:()=>!b&&t(m.id),disabled:b,"aria-current":_?"page":void 0,className:kt(_?"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",b&&"cursor-not-allowed opacity-50 hover:bg-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[U.jsxs("span",{className:"inline-flex items-center justify-center",children:[m.label,m.count!==void 0?U.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:m.count}):null]}),U.jsx("span",{"aria-hidden":"true",className:kt(_?"bg-indigo-500 dark:bg-indigo-400":"bg-transparent","absolute inset-x-0 bottom-0 h-0.5")})]},m.id)})});case"simple":return U.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:U.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(m=>{const v=m.id===u.id,_=!!m.disabled;return U.jsx("li",{children:U.jsx("button",{type:"button",onClick:()=>!_&&t(m.id),disabled:_,"aria-current":v?"page":void 0,className:kt(v?"text-indigo-600 dark:text-indigo-400":"hover:text-gray-700 dark:hover:text-white",_&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:m.label})},m.id)})})});default:return null}};return U.jsxs("div",{className:i,children:[U.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[U.jsx("select",{value:u.id,onChange:m=>t(m.target.value),"aria-label":n,className:c,children:s.map(m=>U.jsx("option",{value:m.id,children:m.label},m.id))}),U.jsx(mO,{"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"})]}),U.jsx("div",{className:"hidden sm:block",children:g()})]})}function kx({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:o,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:g}){const m=_=>{n||e(_.target.checked)},v=kt("absolute inset-0 size-full appearance-none focus:outline-hidden",n&&"cursor-not-allowed");return d==="short"?U.jsxs("div",{className:kt("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",g),children:[U.jsx("span",{className:kt("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")}),U.jsx("span",{className:kt("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")}),U.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:m,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]}):U.jsxs("div",{className:kt("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",g),children:[f==="icon"?U.jsxs("span",{className:kt("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:[U.jsx("span",{"aria-hidden":"true",className:kt("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-in",s?"opacity-0 duration-100":"opacity-100 duration-200"),children:U.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:U.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),U.jsx("span",{"aria-hidden":"true",className:kt("absolute inset-0 flex size-full items-center justify-center transition-opacity ease-out",s?"opacity-100 duration-200":"opacity-0 duration-100"),children:U.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:U.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"})})})]}):U.jsx("span",{className:kt("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")}),U.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:m,disabled:n,required:r,"aria-label":o,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function G0({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const o=Y.useId(),u=i??`sw-${o}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?U.jsxs("div",{className:kt("flex items-center justify-between gap-3",n),children:[U.jsx(kx,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),U.jsxs("div",{className:"text-sm",children:[U.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?U.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):U.jsxs("div",{className:kt("flex items-center justify-between",n),children:[U.jsxs("span",{className:"flex grow flex-col",children:[U.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?U.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),U.jsx(kx,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}const il={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,autoStartAddedDownloads:!0,useChaturbateApi:!1};function vO(){const[s,e]=Y.useState(il),[t,i]=Y.useState(!1),[n,r]=Y.useState(null),[o,u]=Y.useState(null),[c,d]=Y.useState(null);Y.useEffect(()=>{let m=!0;return fetch("/api/settings",{cache:"no-store"}).then(async v=>{if(!v.ok)throw new Error(await v.text());return v.json()}).then(v=>{m&&e({recordDir:(v.recordDir||il.recordDir).toString(),doneDir:(v.doneDir||il.doneDir).toString(),ffmpegPath:String(v.ffmpegPath??il.ffmpegPath??""),autoAddToDownloadList:v.autoAddToDownloadList??il.autoAddToDownloadList,autoStartAddedDownloads:v.autoStartAddedDownloads??il.autoStartAddedDownloads,useChaturbateApi:v.useChaturbateApi??il.useChaturbateApi})}).catch(()=>{}),()=>{m=!1}},[]);async function f(m){d(null),u(null),r(m);try{window.focus();const v=await fetch(`/api/settings/browse?target=${m}`,{cache:"no-store"});if(v.status===204)return;if(!v.ok){const E=await v.text().catch(()=>"");throw new Error(E||`HTTP ${v.status}`)}const b=((await v.json()).path??"").trim();if(!b)return;e(E=>m==="record"?{...E,recordDir:b}:m==="done"?{...E,doneDir:b}:{...E,ffmpegPath:b})}catch(v){d(v?.message??String(v))}finally{r(null)}}async function g(){d(null),u(null);const m=s.recordDir.trim(),v=s.doneDir.trim(),_=(s.ffmpegPath??"").trim();if(!m||!v){d("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const b=!!s.autoAddToDownloadList,E=b?!!s.autoStartAddedDownloads:!1,w=!!s.useChaturbateApi;i(!0);try{const L=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:m,doneDir:v,ffmpegPath:_,autoAddToDownloadList:b,autoStartAddedDownloads:E,useChaturbateApi:w})});if(!L.ok){const I=await L.text().catch(()=>"");throw new Error(I||`HTTP ${L.status}`)}u("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(L){d(L?.message??String(L))}finally{i(!1)}}return U.jsx(In,{header:U.jsxs("div",{className:"flex items-center justify-between gap-4",children:[U.jsx("div",{children:U.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"})}),U.jsx(ci,{variant:"primary",onClick:g,disabled:t,children:"Speichern"})]}),grayBody:!0,children:U.jsxs("div",{className:"space-y-4",children:[c&&U.jsx("div",{className:"rounded-md bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-500/10 dark:text-red-200",children:c}),o&&U.jsx("div",{className:"rounded-md bg-green-50 px-3 py-2 text-sm text-green-700 dark:bg-green-500/10 dark:text-green-200",children:o}),U.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[U.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),U.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[U.jsx("input",{value:s.recordDir,onChange:m=>e(v=>({...v,recordDir:m.target.value})),placeholder:"records (oder absolut: C:\\records / /mnt/data/records)",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 + dark:bg-white/10 dark:text-white`}),U.jsx(ci,{variant:"secondary",onClick:()=>f("record"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),U.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[U.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),U.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[U.jsx("input",{value:s.doneDir,onChange:m=>e(v=>({...v,doneDir:m.target.value})),placeholder:"records/done",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 + dark:bg-white/10 dark:text-white`}),U.jsx(ci,{variant:"secondary",onClick:()=>f("done"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),U.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-12 sm:items-center",children:[U.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),U.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[U.jsx("input",{value:s.ffmpegPath??"",onChange:m=>e(v=>({...v,ffmpegPath:m.target.value})),placeholder:"Leer = automatisch (FFMPEG_PATH / ffmpeg im PATH)",className:`min-w-0 flex-1 rounded-md px-3 py-2 text-sm bg-white text-gray-900 + dark:bg-white/10 dark:text-white`}),U.jsx(ci,{variant:"secondary",onClick:()=>f("ffmpeg"),disabled:t||n!==null,children:"Durchsuchen..."})]})]}),U.jsx("div",{className:"mt-2 border-t border-gray-200 pt-4 dark:border-white/10",children:U.jsxs("div",{className:"space-y-3",children:[U.jsx(G0,{checked:!!s.autoAddToDownloadList,onChange:m=>e(v=>({...v,autoAddToDownloadList:m,autoStartAddedDownloads:m?v.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),U.jsx(G0,{checked:!!s.autoStartAddedDownloads,onChange:m=>e(v=>({...v,autoStartAddedDownloads:m})),disabled:!s.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),U.jsx(G0,{checked:!!s.useChaturbateApi,onChange:m=>e(v=>({...v,useChaturbateApi:m})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."})]})})]})})}function TO({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 _O=Y.forwardRef(TO);function bO({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 SO=Y.forwardRef(bO);function xO({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 EO=Y.forwardRef(xO);function qs(...s){return s.filter(Boolean).join(" ")}function Ox(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function AO(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function Px(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 dg({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:o=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:g=!1,emptyLabel:m="Keine Daten vorhanden.",className:v,onRowClick:_,onRowContextMenu:b,sort:E,onSortChange:w,defaultSort:L=null}){const I=f?"py-2":"py-4",F=f?"py-3":"py-3.5",B=E!==void 0,[V,N]=Y.useState(L),q=B?E:V,R=Y.useCallback(z=>{B||N(z),w?.(z)},[B,w]),P=Y.useMemo(()=>{if(!q)return e;const z=s.find(Q=>Q.key===q.key);if(!z)return e;const ee=q.direction==="asc"?1:-1,ie=e.map((Q,oe)=>({r:Q,i:oe}));return ie.sort((Q,oe)=>{let H=0;if(z.sortFn)H=z.sortFn(Q.r,oe.r);else{const X=z.sortValue?z.sortValue(Q.r):Q.r?.[z.key],te=z.sortValue?z.sortValue(oe.r):oe.r?.[z.key],ae=Px(X),ce=Px(te);ae.isNull&&!ce.isNull?H=1:!ae.isNull&&ce.isNull?H=-1:ae.kind==="number"&&ce.kind==="number"?H=ae.valuece.value?1:0:H=String(ae.value).localeCompare(String(ce.value),void 0,{numeric:!0})}return H===0?Q.i-oe.i:H*ee}),ie.map(Q=>Q.r)},[e,s,q]);return U.jsxs("div",{className:qs(o?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&U.jsxs("div",{className:"sm:flex sm:items-center",children:[U.jsxs("div",{className:"sm:flex-auto",children:[i&&U.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&U.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&U.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),U.jsx("div",{className:qs(i||n||r?"mt-8":""),children:U.jsx("div",{className:"flow-root",children:U.jsx("div",{className:"overflow-x-auto",children:U.jsx("div",{className:qs("inline-block min-w-full py-2 align-middle",o?"":"sm:px-6 lg:px-8"),children:U.jsx("div",{className:qs(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:U.jsxs("table",{className:"relative min-w-full divide-y divide-gray-300 dark:divide-white/15",children:[U.jsx("thead",{className:qs(u&&"bg-gray-50 dark:bg-gray-800/75",d&&"sticky top-0 z-10 backdrop-blur-sm backdrop-filter"),children:U.jsx("tr",{children:s.map(z=>{const ee=!!q&&q.key===z.key,ie=ee?q.direction:void 0,Q=z.sortable&&!z.srOnlyHeader?ee?ie==="asc"?"ascending":"descending":"none":void 0,oe=()=>{if(!(!z.sortable||z.srOnlyHeader))return R(ee?ie==="asc"?{key:z.key,direction:"desc"}:null:{key:z.key,direction:"asc"})};return U.jsx("th",{scope:"col","aria-sort":Q,className:qs(F,"px-3 text-sm font-semibold text-gray-900 dark:text-gray-200",Ox(z.align),z.widthClassName,z.headerClassName),children:z.srOnlyHeader?U.jsx("span",{className:"sr-only",children:z.header}):z.sortable?U.jsxs("button",{type:"button",onClick:oe,className:qs("group inline-flex w-full items-center gap-2 select-none",AO(z.align)),children:[U.jsx("span",{children:z.header}),U.jsx("span",{className:qs("flex-none rounded-sm text-gray-400 dark:text-gray-500",ee?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:U.jsx(_O,{"aria-hidden":"true",className:qs("size-5 transition-transform",ee&&ie==="asc"&&"rotate-180")})})]}):z.header},z.key)})})}),U.jsx("tbody",{className:qs("divide-y divide-gray-200 dark:divide-white/10",u?"bg-white dark:bg-gray-800/50":"bg-white dark:bg-gray-900"),children:g?U.jsx("tr",{children:U.jsx("td",{colSpan:s.length,className:qs(I,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):P.length===0?U.jsx("tr",{children:U.jsx("td",{colSpan:s.length,className:qs(I,"px-3 text-sm text-gray-500 dark:text-gray-400"),children:m})}):P.map((z,ee)=>{const ie=t?t(z,ee):String(ee);return U.jsx("tr",{className:qs(c&&"even:bg-gray-50 dark:even:bg-gray-800/50",_&&"cursor-pointer"),onClick:()=>_?.(z),onContextMenu:b?Q=>{Q.preventDefault(),b(z,Q)}:void 0,children:s.map(Q=>{const oe=Q.cell?.(z,ee)??Q.accessor?.(z)??z?.[Q.key];return U.jsx("td",{className:qs(I,"px-3 text-sm whitespace-nowrap",Ox(Q.align),Q.className,Q.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:oe},Q.key)})},ie)})})]})})})})})})]})}function pA({children:s,content:e}){const t=Y.useRef(null),i=Y.useRef(null),[n,r]=Y.useState(!1),[o,u]=Y.useState(null),c=Y.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)},g=()=>{d(),r(!0)},m=()=>{f()},v=()=>{const b=t.current,E=i.current;if(!b||!E)return;const w=8,L=8,I=b.getBoundingClientRect(),F=E.getBoundingClientRect();let B=I.bottom+w;if(B+F.height>window.innerHeight-L){const q=I.top-F.height-w;q>=L?B=q:B=Math.max(L,window.innerHeight-F.height-L)}let N=I.left;N+F.width>window.innerWidth-L&&(N=window.innerWidth-F.width-L),N=Math.max(L,N),u({left:N,top:B})};Y.useLayoutEffect(()=>{if(!n)return;const b=requestAnimationFrame(()=>v());return()=>cancelAnimationFrame(b)},[n]),Y.useEffect(()=>{if(!n)return;const b=()=>requestAnimationFrame(()=>v());return window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[n]),Y.useEffect(()=>()=>d(),[]);const _=()=>typeof e=="function"?e(n):e;return U.jsxs(U.Fragment,{children:[U.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:g,onMouseLeave:m,children:s}),n&&tg.createPortal(U.jsx("div",{ref:i,className:"fixed z-50",style:{left:o?.left??-9999,top:o?.top??-9999,visibility:o?"visible":"hidden"},onMouseEnter:g,onMouseLeave:m,children:U.jsx(In,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 w-[360px]",noBodyPadding:!0,children:_()})}),document.body)]})}function Mx({job:s,getFileName:e,durationSeconds:t,onDuration:i,thumbTick:n}){const r=e(s.output||""),[o,u]=Y.useState(!0),[c,d]=Y.useState(!1),f=Y.useMemo(()=>{if(!r)return"";const w=r.lastIndexOf(".");return w>0?r.slice(0,w):r},[r]),g=Y.useMemo(()=>r?`/api/record/video?file=${encodeURIComponent(r)}`:"",[r]),m=typeof t=="number"&&Number.isFinite(t)&&t>0,v=n??0,_=Y.useMemo(()=>{if(!t||!Number.isFinite(t)||t<=0)return 0;const w=3,L=Math.max(0,Math.floor(v)),I=Math.max(t-.1,w);return L*w%I},[t,v]),b=Y.useMemo(()=>{if(!f)return"";const w=[];w.push(`t=${encodeURIComponent(_.toFixed(2))}`),typeof n=="number"&&w.push(`v=${encodeURIComponent(String(n))}`);const L=w.length?`&${w.join("&")}`:"";return`/api/record/preview?id=${encodeURIComponent(f)}${L}`},[f,_,n]),E=w=>{if(d(!0),!i)return;const L=w.currentTarget.duration;Number.isFinite(L)&&L>0&&i(s,L)};return g?U.jsx(pA,{content:w=>w&&U.jsx("div",{className:"w-[420px]",children:U.jsx("div",{className:"aspect-video",children:U.jsx("video",{src:g,className:"w-full h-full bg-black",muted:!0,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation()})})}),children:U.jsxs("div",{className:"w-20 h-16 rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative",children:[b&&o?U.jsx("img",{src:b,loading:"lazy",alt:r,className:"w-full h-full object-cover",onError:()=>u(!1)}):U.jsx("div",{className:"w-full h-full bg-black"}),i&&!m&&!c&&U.jsx("video",{src:g,preload:"metadata",muted:!0,playsInline:!0,className:"hidden",onLoadedMetadata:E})]})}):U.jsx("div",{className:"w-20 h-16 rounded bg-gray-100 dark:bg-white/5"})}function CO({open:s,x:e,y:t,items:i,onClose:n,className:r}){const o=Y.useRef(null),[u,c]=Y.useState({left:e,top:t});return Y.useLayoutEffect(()=>{if(!s)return;const d=o.current;if(!d)return;const f=8,{innerWidth:g,innerHeight:m}=window,v=d.getBoundingClientRect(),_=Math.min(Math.max(e,f),g-v.width-f),b=Math.min(Math.max(t,f),m-v.height-f);c({left:_,top:b})},[s,e,t,i.length]),Y.useEffect(()=>{if(!s)return;const d=g=>g.key==="Escape"&&n(),f=()=>n();return window.addEventListener("keydown",d),window.addEventListener("scroll",f,!0),window.addEventListener("resize",f),()=>{window.removeEventListener("keydown",d),window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",f)}},[s,n]),s?tg.createPortal(U.jsxs(U.Fragment,{children:[U.jsx("div",{className:"fixed inset-0 z-50",onMouseDown:n,onContextMenu:d=>{d.preventDefault(),n()}}),U.jsx("div",{ref:o,className:kt("fixed z-50 min-w-[220px] overflow-hidden rounded-lg","bg-white dark:bg-gray-800","ring-1 ring-black/10 dark:ring-white/10 shadow-lg",r),style:{left:u.left,top:u.top},role:"menu",onMouseDown:d=>d.stopPropagation(),onContextMenu:d=>d.preventDefault(),children:U.jsx("div",{className:"py-1",children:i.map((d,f)=>U.jsx("button",{type:"button",disabled:d.disabled,onClick:()=>{d.disabled||(d.onClick(),n())},className:kt("w-full text-left px-3 py-2 text-sm","hover:bg-black/5 dark:hover:bg-white/10","disabled:opacity-50 disabled:cursor-not-allowed",d.danger?"text-red-700 dark:text-red-300":"text-gray-900 dark:text-gray-100"),role:"menuitem",children:d.label},f))})})]}),document.body):null}function DO({job:s,modelName:e,state:t,actions:i}){const c=t.liked;return[{label:"Abspielen",onClick:()=>i.onPlay(s)},{label:"Beobachten",onClick:()=>i.onToggleWatch(s)},{label:c===!0?"Gefällt mir entfernen":"Gefällt mir",onClick:()=>i.onSetLike(s,!0)},{label:c===!1?"Gefällt mir nicht entfernen":"Gefällt mir nicht",onClick:()=>i.onSetLike(s,!1)},{label:"Als Favorit markieren",onClick:()=>i.onToggleFavorite(s)},{label:`Mehr von ${e} anzeigen`,onClick:()=>i.onMoreFromModel(e,s),disabled:!e||e==="—"},{label:"Dateipfad im Explorer öffnen",onClick:()=>i.onRevealInExplorer(s),disabled:!s.output},{label:"Zur Downloadliste hinzufügen",onClick:()=>i.onAddToDownloadList(s)},{label:"Als HOT markieren",onClick:()=>i.onToggleHot(s)},{label:"Behalten",onClick:()=>i.onToggleKeep(s)},{label:"Löschen",onClick:()=>i.onDelete(s),danger:!0,disabled:!1}]}const rv=s=>(s||"").replaceAll("\\","/").trim(),uo=s=>{const t=rv(s).split("/");return t[t.length-1]||""},wn=s=>uo(s.output||"")||s.id;function gA(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 wO(s){const e=Date.parse(String(s.startedAt||"")),t=Date.parse(String(s.endedAt||""));return!Number.isFinite(e)||!Number.isFinite(t)?"—":gA(t-e)}const V0=s=>{const e=(s??"").match(/\bHTTP\s+(\d{3})\b/i);return e?`HTTP ${e[1]}`:null},Mf=s=>{const e=uo(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};function LO({jobs:s,doneJobs:e,onOpenPlayer:t}){const[n,r]=Y.useState(50),[o,u]=Y.useState(null),[c,d]=Y.useState(()=>new Set),[f,g]=Y.useState(()=>new Set),[m,v]=Y.useState(null),[_,b]=Y.useState(0);Y.useEffect(()=>{const Q=window.setInterval(()=>{b(oe=>oe+1)},3e3);return()=>window.clearInterval(Q)},[]);const[E,w]=Y.useState({}),L=(Q,oe)=>{oe.preventDefault(),oe.stopPropagation(),u({x:oe.clientX,y:oe.clientY,job:Q})},I=(Q,oe,H)=>{u({x:oe,y:H,job:Q})},F=Y.useCallback((Q,oe)=>{g(H=>{const X=new Set(H);return oe?X.add(Q):X.delete(Q),X})},[]),B=Y.useCallback(Q=>{d(oe=>{const H=new Set(oe);return H.add(Q),H})},[]),V=Y.useCallback(async Q=>{const oe=uo(Q.output||""),H=wn(Q);if(!oe){window.alert("Kein Dateiname gefunden – kann nicht löschen.");return}if(!f.has(H)){F(H,!0);try{const X=await fetch(`/api/record/delete?file=${encodeURIComponent(oe)}`,{method:"POST"});if(!X.ok){const te=await X.text().catch(()=>"");throw new Error(te||`HTTP ${X.status}`)}B(H)}catch(X){window.alert(`Löschen fehlgeschlagen: ${String(X?.message||X)}`)}finally{F(H,!1)}}},[f,B,F]),N=Y.useMemo(()=>{if(!o)return[];const Q=o.job,oe=Mf(Q.output);return DO({job:Q,modelName:oe,state:{liked:null},actions:{onPlay:t,onToggleWatch:H=>console.log("toggle watch",H.id),onSetLike:(H,X)=>console.log("set like",H.id,X),onToggleFavorite:H=>console.log("toggle favorite",H.id),onMoreFromModel:H=>console.log("more from",H),onRevealInExplorer:H=>console.log("reveal in explorer",H.output),onAddToDownloadList:H=>console.log("add to download list",H.id),onToggleHot:H=>console.log("toggle hot",H.id),onToggleKeep:H=>console.log("toggle keep",H.id),onDelete:H=>{u(null),V(H)}}})},[o,V,t]),q=Y.useCallback(Q=>{const oe=wn(Q),H=E[oe];if(typeof H=="number"&&Number.isFinite(H)&&H>0)return H;const X=Date.parse(String(Q.startedAt||"")),te=Date.parse(String(Q.endedAt||""));return!Number.isFinite(X)||!Number.isFinite(te)||te<=X?Number.POSITIVE_INFINITY:(te-X)/1e3},[E]),R=Y.useMemo(()=>{const Q=new Map;for(const H of e)Q.set(wn(H),H);for(const H of s){const X=wn(H);Q.has(X)&&Q.set(X,{...Q.get(X),...H})}const oe=Array.from(Q.values()).filter(H=>c.has(wn(H))?!1:H.status==="finished"||H.status==="failed"||H.status==="stopped");return oe.sort((H,X)=>rv(X.endedAt||"").localeCompare(rv(H.endedAt||""))),oe},[s,e,c]);Y.useEffect(()=>{r(50)},[R.length]);const P=Y.useMemo(()=>R.slice(0,n),[R,n]),z=Q=>{const oe=wn(Q),H=E[oe];return typeof H=="number"&&Number.isFinite(H)&&H>0?gA(H*1e3):wO(Q)},ee=Y.useCallback((Q,oe)=>{if(!Number.isFinite(oe)||oe<=0)return;const H=wn(Q);w(X=>{const te=X[H];return typeof te=="number"&&Math.abs(te-oe)<.5?X:{...X,[H]:oe}})},[]),ie=[{key:"preview",header:"Vorschau",cell:Q=>U.jsx(Mx,{job:Q,getFileName:uo,durationSeconds:E[wn(Q)],onDuration:ee,thumbTick:_})},{key:"model",header:"Modelname",sortable:!0,sortValue:Q=>Mf(Q.output),cell:Q=>{const oe=Mf(Q.output);return U.jsx("span",{className:"truncate",title:oe,children:oe})}},{key:"output",header:"Datei",sortable:!0,sortValue:Q=>uo(Q.output||""),cell:Q=>uo(Q.output||"")},{key:"status",header:"Status",sortable:!0,sortValue:Q=>Q.status==="finished"?0:Q.status==="stopped"?1:Q.status==="failed"?2:9,cell:Q=>{if(Q.status!=="failed")return Q.status;const oe=V0(Q.error),H=oe?`failed (${oe})`:"failed";return U.jsx("span",{className:"text-red-700 dark:text-red-300",title:Q.error||"",children:H})}},{key:"runtime",header:"Dauer",sortable:!0,sortValue:Q=>q(Q),cell:Q=>z(Q)},{key:"actions",header:"Aktion",align:"right",srOnlyHeader:!0,cell:Q=>{const oe=wn(Q),H=f.has(oe);return U.jsx(ci,{disabled:H,variant:"soft",color:"red",onClick:X=>{X.preventDefault(),X.stopPropagation(),V(Q)},"aria-label":"Video löschen",title:"Video löschen",children:H?"…":"Löschen"})}}];return R.length===0?U.jsx(In,{grayBody:!0,children:U.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads im Zielordner vorhanden."})}):U.jsxs(U.Fragment,{children:[U.jsx("div",{className:"sm:hidden space-y-3",children:P.map(Q=>{const oe=Mf(Q.output),H=uo(Q.output||""),X=z(Q),te=Q.status==="failed"?U.jsxs("span",{className:"text-red-700 dark:text-red-300",title:Q.error||"",children:["failed",V0(Q.error)?` (${V0(Q.error)})`:""]}):U.jsx("span",{className:"font-medium",children:Q.status});return U.jsx("div",{role:"button",tabIndex:0,className:"cursor-pointer",onClick:()=>t(Q),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&t(Q)},onContextMenu:ae=>L(Q,ae),children:U.jsx(In,{header:U.jsxs("div",{className:"flex items-start justify-between gap-3",children:[U.jsxs("div",{className:"min-w-0",children:[U.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:oe}),U.jsx("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:H||"—"})]}),U.jsxs("div",{className:"shrink-0 flex items-center gap-1",children:[U.jsx(ci,{"aria-label":"Video löschen",title:"Video löschen",onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),V(Q)},children:"🗑"}),U.jsx("button",{type:"button",className:"rounded px-2 py-1 text-lg leading-none hover:bg-black/5 dark:hover:bg-white/10","aria-label":"Aktionen",onClick:ae=>{ae.preventDefault(),ae.stopPropagation();const ce=ae.currentTarget.getBoundingClientRect();I(Q,ce.left,ce.bottom+6)},children:"⋯"})]})]}),children:U.jsxs("div",{className:"flex gap-3",children:[U.jsx("div",{className:"shrink-0",onClick:ae=>ae.stopPropagation(),onMouseDown:ae=>ae.stopPropagation(),onContextMenu:ae=>{ae.preventDefault(),ae.stopPropagation(),L(Q,ae)},children:U.jsx(Mx,{job:Q,getFileName:uo,durationSeconds:E[wn(Q)],onDuration:ee})}),U.jsxs("div",{className:"min-w-0 flex-1",children:[U.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Status: ",te,U.jsx("span",{className:"mx-2 opacity-60",children:"•"}),"Dauer: ",U.jsx("span",{className:"font-medium",children:X})]}),Q.output?U.jsx("div",{className:"mt-1 truncate text-xs text-gray-500 dark:text-gray-400",children:Q.output}):null]})]})})},wn(Q))})}),U.jsx("div",{className:"hidden sm:block",children:U.jsx(dg,{rows:P,columns:ie,getRowKey:Q=>wn(Q),striped:!0,fullWidth:!0,sort:m,onSortChange:v,onRowClick:t,onRowContextMenu:(Q,oe)=>L(Q,oe)})}),U.jsx(CO,{open:!!o,x:o?.x??0,y:o?.y??0,items:N,onClose:()=>u(null)}),R.length>n?U.jsx("div",{className:"mt-3 flex justify-center",children:U.jsxs("button",{type:"button",className:"rounded-md bg-black/5 px-3 py-2 text-sm font-medium hover:bg-black/10 dark:bg-white/10 dark:hover:bg-white/15",onClick:()=>r(Q=>Math.min(R.length,Q+50)),children:["Mehr laden (",Math.min(50,R.length-n)," von ",R.length-n,")"]})}):null]})}var q0,Nx;function hg(){if(Nx)return q0;Nx=1;var s;return typeof window<"u"?s=window:typeof Tp<"u"?s=Tp:typeof self<"u"?s=self:s={},q0=s,q0}var IO=hg();const ne=sc(IO),RO={},kO=Object.freeze(Object.defineProperty({__proto__:null,default:RO},Symbol.toStringTag,{value:"Module"})),OO=zI(kO);var z0,Bx;function mA(){if(Bx)return z0;Bx=1;var s=typeof Tp<"u"?Tp:typeof window<"u"?window:{},e=OO,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),z0=t,z0}var PO=mA();const Ne=sc(PO);var Nf={exports:{}},K0={exports:{}},Fx;function MO(){return Fx||(Fx=1,(function(s){function e(){return s.exports=e=Object.assign?Object.assign.bind():function(t){for(var i=1;i=n.length?{done:!0}:{done:!1,value:n[u++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function e(n,r){if(n){if(typeof n=="string")return t(n,r);var o=Object.prototype.toString.call(n).slice(8,-1);if(o==="Object"&&n.constructor&&(o=n.constructor.name),o==="Map"||o==="Set")return Array.from(n);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var o=0,u=new Array(r);o=400&&u.statusCode<=599){var d=c;if(r)if(s.TextDecoder){var f=t(u.headers&&u.headers["content-type"]);try{d=new TextDecoder(f).decode(c)}catch{}}else d=String.fromCharCode.apply(null,new Uint8Array(c));n({cause:d});return}n(null,c)}};function t(i){return i===void 0&&(i=""),i.toLowerCase().split(";").reduce(function(n,r){var o=r.split("="),u=o[0],c=o[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Q0=e,Q0}var Gx;function $O(){if(Gx)return Nf.exports;Gx=1;var s=hg(),e=MO(),t=NO(),i=BO(),n=FO();d.httpHandler=UO(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(_){var b={};return _&&_.trim().split(` +`).forEach(function(E){var w=E.indexOf(":"),L=E.slice(0,w).trim().toLowerCase(),I=E.slice(w+1).trim();typeof b[L]>"u"?b[L]=I:Array.isArray(b[L])?b[L].push(I):b[L]=[b[L],I]}),b};Nf.exports=d,Nf.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||m,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,o(["get","put","post","patch","head","delete"],function(v){d[v==="delete"?"del":v]=function(_,b,E){return b=c(_,b,E),b.method=v.toUpperCase(),f(b)}});function o(v,_){for(var b=0;b"u")throw new Error("callback argument missing");if(v.requestType&&d.requestInterceptorsStorage.getIsEnabled()){var _={uri:v.uri||v.url,headers:v.headers||{},body:v.body,metadata:v.metadata||{},retry:v.retry,timeout:v.timeout},b=d.requestInterceptorsStorage.execute(v.requestType,_);v.uri=b.uri,v.headers=b.headers,v.body=b.body,v.metadata=b.metadata,v.retry=b.retry,v.timeout=b.timeout}var E=!1,w=function(te,ae,ce){E||(E=!0,v.callback(te,ae,ce))};function L(){V.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(B,0)}function I(){var X=void 0;if(V.response?X=V.response:X=V.responseText||g(V),Q)try{X=JSON.parse(X)}catch{}return X}function F(X){if(clearTimeout(oe),clearTimeout(v.retryTimeout),X instanceof Error||(X=new Error(""+(X||"Unknown XMLHttpRequest Error"))),X.statusCode=0,!q&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=V,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var te={headers:H.headers||{},body:H.body,responseUrl:V.responseURL,responseType:V.responseType},ae=d.responseInterceptorsStorage.execute(v.requestType,te);H.body=ae.body,H.headers=ae.headers}return w(X,H)}function B(){if(!q){var X;clearTimeout(oe),clearTimeout(v.retryTimeout),v.useXDR&&V.status===void 0?X=200:X=V.status===1223?204:V.status;var te=H,ae=null;if(X!==0?(te={body:I(),statusCode:X,method:P,headers:{},url:R,rawRequest:V},V.getAllResponseHeaders&&(te.headers=r(V.getAllResponseHeaders()))):ae=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var ce={headers:te.headers||{},body:te.body,responseUrl:V.responseURL,responseType:V.responseType},$=d.responseInterceptorsStorage.execute(v.requestType,ce);te.body=$.body,te.headers=$.headers}return w(ae,te,te.body)}}var V=v.xhr||null;V||(v.cors||v.useXDR?V=new d.XDomainRequest:V=new d.XMLHttpRequest);var N,q,R=V.url=v.uri||v.url,P=V.method=v.method||"GET",z=v.body||v.data,ee=V.headers=v.headers||{},ie=!!v.sync,Q=!1,oe,H={body:void 0,headers:{},statusCode:0,method:P,url:R,rawRequest:V};if("json"in v&&v.json!==!1&&(Q=!0,ee.accept||ee.Accept||(ee.Accept="application/json"),P!=="GET"&&P!=="HEAD"&&(ee["content-type"]||ee["Content-Type"]||(ee["Content-Type"]="application/json"),z=JSON.stringify(v.json===!0?z:v.json))),V.onreadystatechange=L,V.onload=B,V.onerror=F,V.onprogress=function(){},V.onabort=function(){q=!0,clearTimeout(v.retryTimeout)},V.ontimeout=F,V.open(P,R,!ie,v.username,v.password),ie||(V.withCredentials=!!v.withCredentials),!ie&&v.timeout>0&&(oe=setTimeout(function(){if(!q){q=!0,V.abort("timeout");var X=new Error("XMLHttpRequest timeout");X.code="ETIMEDOUT",F(X)}},v.timeout)),V.setRequestHeader)for(N in ee)ee.hasOwnProperty(N)&&V.setRequestHeader(N,ee[N]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&(V.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend(V),V.send(z||null),V}function g(v){try{if(v.responseType==="document")return v.responseXML;var _=v.responseXML&&v.responseXML.documentElement.nodeName==="parsererror";if(v.responseType===""&&!_)return v.responseXML}catch{}return null}function m(){}return Nf.exports}var jO=$O();const yA=sc(jO);var Z0={exports:{}},J0,Vx;function HO(){if(Vx)return J0;Vx=1;var s=mA(),e=Object.create||(function(){function R(){}return function(P){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return R.prototype=P,new R}})();function t(R,P){this.name="ParsingError",this.code=R.code,this.message=P||R.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(R){function P(ee,ie,Q,oe){return(ee|0)*3600+(ie|0)*60+(Q|0)+(oe|0)/1e3}var z=R.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return z?z[3]?P(z[1],z[2],z[3].replace(":",""),z[4]):z[1]>59?P(z[1],z[2],0,z[4]):P(0,z[1],z[2],z[4]):null}function n(){this.values=e(null)}n.prototype={set:function(R,P){!this.get(R)&&P!==""&&(this.values[R]=P)},get:function(R,P,z){return z?this.has(R)?this.values[R]:P[z]:this.has(R)?this.values[R]:P},has:function(R){return R in this.values},alt:function(R,P,z){for(var ee=0;ee=0&&P<=100)?(this.set(R,P),!0):!1}};function r(R,P,z,ee){var ie=ee?R.split(ee):[R];for(var Q in ie)if(typeof ie[Q]=="string"){var oe=ie[Q].split(z);if(oe.length===2){var H=oe[0].trim(),X=oe[1].trim();P(H,X)}}}function o(R,P,z){var ee=R;function ie(){var H=i(R);if(H===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+ee);return R=R.replace(/^[^\sa-zA-Z-]+/,""),H}function Q(H,X){var te=new n;r(H,function(ae,ce){switch(ae){case"region":for(var $=z.length-1;$>=0;$--)if(z[$].id===ce){te.set(ae,z[$].region);break}break;case"vertical":te.alt(ae,ce,["rl","lr"]);break;case"line":var se=ce.split(","),he=se[0];te.integer(ae,he),te.percent(ae,he)&&te.set("snapToLines",!1),te.alt(ae,he,["auto"]),se.length===2&&te.alt("lineAlign",se[1],["start","center","end"]);break;case"position":se=ce.split(","),te.percent(ae,se[0]),se.length===2&&te.alt("positionAlign",se[1],["start","center","end"]);break;case"size":te.percent(ae,ce);break;case"align":te.alt(ae,ce,["start","center","end","left","right"]);break}},/:/,/\s/),X.region=te.get("region",null),X.vertical=te.get("vertical","");try{X.line=te.get("line","auto")}catch{}X.lineAlign=te.get("lineAlign","start"),X.snapToLines=te.get("snapToLines",!0),X.size=te.get("size",100);try{X.align=te.get("align","center")}catch{X.align=te.get("align","middle")}try{X.position=te.get("position","auto")}catch{X.position=te.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},X.align)}X.positionAlign=te.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},X.align)}function oe(){R=R.replace(/^\s+/,"")}if(oe(),P.startTime=ie(),oe(),R.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+ee);R=R.substr(3),oe(),P.endTime=ie(),oe(),Q(R,P)}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"},g={rt:"ruby"};function m(R,P){function z(){if(!P)return null;function he(be){return P=P.substr(be.length),be}var Se=P.match(/^([^<]*)(<[^>]*>?)?/);return he(Se[1]?Se[1]:Se[2])}function ee(he){return u.innerHTML=he,he=u.textContent,u.textContent="",he}function ie(he,Se){return!g[Se.localName]||g[Se.localName]===he.localName}function Q(he,Se){var be=c[he];if(!be)return null;var Pe=R.document.createElement(be),Ae=f[he];return Ae&&Se&&(Pe[Ae]=Se.trim()),Pe}for(var oe=R.document.createElement("div"),H=oe,X,te=[];(X=z())!==null;){if(X[0]==="<"){if(X[1]==="/"){te.length&&te[te.length-1]===X.substr(2).replace(">","")&&(te.pop(),H=H.parentNode);continue}var ae=i(X.substr(1,X.length-2)),ce;if(ae){ce=R.document.createProcessingInstruction("timestamp",ae),H.appendChild(ce);continue}var $=X.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!$||(ce=Q($[1],$[3]),!ce)||!ie(H,ce))continue;if($[2]){var se=$[2].split(".");se.forEach(function(he){var Se=/^bg_/.test(he),be=Se?he.slice(3):he;if(d.hasOwnProperty(be)){var Pe=Se?"background-color":"color",Ae=d[be];ce.style[Pe]=Ae}}),ce.className=se.join(" ")}te.push($[1]),H.appendChild(ce),H=ce;continue}H.appendChild(R.document.createTextNode(ee(X)))}return oe}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 _(R){for(var P=0;P=z[0]&&R<=z[1])return!0}return!1}function b(R){var P=[],z="",ee;if(!R||!R.childNodes)return"ltr";function ie(H,X){for(var te=X.childNodes.length-1;te>=0;te--)H.push(X.childNodes[te])}function Q(H){if(!H||!H.length)return null;var X=H.pop(),te=X.textContent||X.innerText;if(te){var ae=te.match(/^.*(\n|\r)/);return ae?(H.length=0,ae[0]):te}if(X.tagName==="ruby")return Q(H);if(X.childNodes)return ie(H,X),Q(H)}for(ie(P,R);z=Q(P);)for(var oe=0;oe=0&&R.line<=100))return R.line;if(!R.track||!R.track.textTrackList||!R.track.textTrackList.mediaElement)return-1;for(var P=R.track,z=P.textTrackList,ee=0,ie=0;ieR.left&&this.topR.top},I.prototype.overlapsAny=function(R){for(var P=0;P=R.top&&this.bottom<=R.bottom&&this.left>=R.left&&this.right<=R.right},I.prototype.overlapsOppositeAxis=function(R,P){switch(P){case"+x":return this.leftR.right;case"+y":return this.topR.bottom}},I.prototype.intersectPercentage=function(R){var P=Math.max(0,Math.min(this.right,R.right)-Math.max(this.left,R.left)),z=Math.max(0,Math.min(this.bottom,R.bottom)-Math.max(this.top,R.top)),ee=P*z;return ee/(this.height*this.width)},I.prototype.toCSSCompatValues=function(R){return{top:this.top-R.top,bottom:R.bottom-this.bottom,left:this.left-R.left,right:R.right-this.right,height:this.height,width:this.width}},I.getSimpleBoxPosition=function(R){var P=R.div?R.div.offsetHeight:R.tagName?R.offsetHeight:0,z=R.div?R.div.offsetWidth:R.tagName?R.offsetWidth:0,ee=R.div?R.div.offsetTop:R.tagName?R.offsetTop:0;R=R.div?R.div.getBoundingClientRect():R.tagName?R.getBoundingClientRect():R;var ie={left:R.left,right:R.right,top:R.top||ee,height:R.height||P,bottom:R.bottom||ee+(R.height||P),width:R.width||z};return ie};function F(R,P,z,ee){function ie(be,Pe){for(var Ae,Be=new I(be),$e=1,Je=0;Jeht&&(Ae=new I(be),$e=ht),be=new I(Be)}return Ae||Be}var Q=new I(P),oe=P.cue,H=E(oe),X=[];if(oe.snapToLines){var te;switch(oe.vertical){case"":X=["+y","-y"],te="height";break;case"rl":X=["+x","-x"],te="width";break;case"lr":X=["-x","+x"],te="width";break}var ae=Q.lineHeight,ce=ae*Math.round(H),$=z[te]+ae,se=X[0];Math.abs(ce)>$&&(ce=ce<0?-1:1,ce*=Math.ceil($/ae)*ae),H<0&&(ce+=oe.vertical===""?z.height:z.width,X=X.reverse()),Q.move(se,ce)}else{var he=Q.lineHeight/z.height*100;switch(oe.lineAlign){case"center":H-=he/2;break;case"end":H-=he;break}switch(oe.vertical){case"":P.applyStyles({top:P.formatStyle(H,"%")});break;case"rl":P.applyStyles({left:P.formatStyle(H,"%")});break;case"lr":P.applyStyles({right:P.formatStyle(H,"%")});break}X=["+y","-x","+x","-y"],Q=new I(P)}var Se=ie(Q,X);P.move(Se.toCSSCompatValues(z))}function B(){}B.StringDecoder=function(){return{decode:function(R){if(!R)return"";if(typeof R!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(R))}}},B.convertCueToDOMTree=function(R,P){return!R||!P?null:m(R,P)};var V=.05,N="sans-serif",q="1.5%";return B.processCues=function(R,P,z){if(!R||!P||!z)return null;for(;z.firstChild;)z.removeChild(z.firstChild);var ee=R.document.createElement("div");ee.style.position="absolute",ee.style.left="0",ee.style.right="0",ee.style.top="0",ee.style.bottom="0",ee.style.margin=q,z.appendChild(ee);function ie(ae){for(var ce=0;ce")===-1){P.cue.id=oe;continue}case"CUE":try{o(oe,P.cue,P.regionList)}catch(ae){P.reportOrThrowError(ae),P.cue=null,P.state="BADCUE";continue}P.state="CUETEXT";continue;case"CUETEXT":var te=oe.indexOf("-->")!==-1;if(!oe||te&&(X=!0)){P.oncue&&P.oncue(P.cue),P.cue=null,P.state="ID";continue}P.cue.text&&(P.cue.text+=` +`),P.cue.text+=oe.replace(/\u2028/g,` +`).replace(/u2029/g,` +`);continue;case"BADCUE":oe||(P.state="ID");continue}}}catch(ae){P.reportOrThrowError(ae),P.state==="CUETEXT"&&P.cue&&P.oncue&&P.oncue(P.cue),P.cue=null,P.state=P.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var R=this;try{if(R.buffer+=R.decoder.decode(),(R.cue||R.state==="HEADER")&&(R.buffer+=` + +`,R.parse()),R.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(P){R.reportOrThrowError(P)}return R.onflush&&R.onflush(),this}},J0=B,J0}var ey,qx;function GO(){if(qx)return ey;qx=1;var s="auto",e={"":1,lr:1,rl:1},t={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function i(o){if(typeof o!="string")return!1;var u=e[o.toLowerCase()];return u?o.toLowerCase():!1}function n(o){if(typeof o!="string")return!1;var u=t[o.toLowerCase()];return u?o.toLowerCase():!1}function r(o,u,c){this.hasBeenReset=!1;var d="",f=!1,g=o,m=u,v=c,_=null,b="",E=!0,w="auto",L="start",I="auto",F="auto",B=100,V="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return d},set:function(N){d=""+N}},pauseOnExit:{enumerable:!0,get:function(){return f},set:function(N){f=!!N}},startTime:{enumerable:!0,get:function(){return g},set:function(N){if(typeof N!="number")throw new TypeError("Start time must be set to a number.");g=N,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return m},set:function(N){if(typeof N!="number")throw new TypeError("End time must be set to a number.");m=N,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return v},set:function(N){v=""+N,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return _},set:function(N){_=N,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return b},set:function(N){var q=i(N);if(q===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");b=q,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return E},set:function(N){E=!!N,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return w},set:function(N){if(typeof N!="number"&&N!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");w=N,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return L},set:function(N){var q=n(N);q?(L=q,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return I},set:function(N){if(N<0||N>100)throw new Error("Position must be between 0 and 100.");I=N,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return F},set:function(N){var q=n(N);q?(F=q,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return B},set:function(N){if(N<0||N>100)throw new Error("Size must be between 0 and 100.");B=N,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return V},set:function(N){var q=n(N);if(!q)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");V=q,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},ey=r,ey}var ty,zx;function VO(){if(zx)return ty;zx=1;var s={"":!0,up:!0};function e(n){if(typeof n!="string")return!1;var r=s[n.toLowerCase()];return r?n.toLowerCase():!1}function t(n){return typeof n=="number"&&n>=0&&n<=100}function i(){var n=100,r=3,o=0,u=100,c=0,d=100,f="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return n},set:function(g){if(!t(g))throw new Error("Width must be between 0 and 100.");n=g}},lines:{enumerable:!0,get:function(){return r},set:function(g){if(typeof g!="number")throw new TypeError("Lines must be set to a number.");r=g}},regionAnchorY:{enumerable:!0,get:function(){return u},set:function(g){if(!t(g))throw new Error("RegionAnchorX must be between 0 and 100.");u=g}},regionAnchorX:{enumerable:!0,get:function(){return o},set:function(g){if(!t(g))throw new Error("RegionAnchorY must be between 0 and 100.");o=g}},viewportAnchorY:{enumerable:!0,get:function(){return d},set:function(g){if(!t(g))throw new Error("ViewportAnchorY must be between 0 and 100.");d=g}},viewportAnchorX:{enumerable:!0,get:function(){return c},set:function(g){if(!t(g))throw new Error("ViewportAnchorX must be between 0 and 100.");c=g}},scroll:{enumerable:!0,get:function(){return f},set:function(g){var m=e(g);m===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=m}}})}return ty=i,ty}var Kx;function qO(){if(Kx)return Z0.exports;Kx=1;var s=hg(),e=Z0.exports={WebVTT:HO(),VTTCue:GO(),VTTRegion:VO()};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(),Z0.exports}var zO=qO();const Yx=sc(zO);function Mi(){return Mi=Object.assign?Object.assign.bind():function(s){for(var e=1;e-1},e.trigger=function(i){var n=this.listeners[i];if(n)if(arguments.length===2)for(var r=n.length,o=0;o-1;t=this.buffer.indexOf(` +`))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const WO=" ",iy=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},XO=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},ws=function(s){const e={};if(!s)return e;const t=s.split(XO());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},Xx=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 QO extends rT{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;if(e=e.trim(),e.length===0)return;if(e[0]!=="#"){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((r,o)=>{const u=o(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let o=0;or),this.customParsers.push(r=>{if(e.exec(r))return this.trigger("data",{type:"custom",data:i(r),customType:t,segment:n}),!0})}addTagMapper({expression:e,map:t}){const i=n=>e.test(n)?t(n):n;this.tagMappers.push(i)}}const ZO=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),io=function(s){const e={};return Object.keys(s).forEach(function(t){e[ZO(t)]=s[t]}),e},sy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",o="partHoldBack",u=t&&t*3,c=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=u,this.trigger("info",{message:`${n} defaulting HOLD-BACK to targetDuration * 3 (${u}).`})),u&&e[r]{n.uri||!n.parts&&!n.preloadHints||(!n.map&&r&&(n.map=r),!n.key&&o&&(n.key=o),!n.timeline&&typeof g=="number"&&(n.timeline=g),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(b){let E,w;if(t.manifest.definitions){for(const L in t.manifest.definitions)if(b.uri&&(b.uri=b.uri.replace(`{$${L}}`,t.manifest.definitions[L])),b.attributes)for(const I in b.attributes)typeof b.attributes[I]=="string"&&(b.attributes[I]=b.attributes[I].replace(`{$${L}}`,t.manifest.definitions[L]))}({tag(){({version(){b.version&&(this.manifest.version=b.version)},"allow-cache"(){this.manifest.allowCache=b.allowed,"allowed"in b||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const L={};"length"in b&&(n.byterange=L,L.length=b.length,"offset"in b||(b.offset=m)),"offset"in b&&(n.byterange=L,L.offset=b.offset),m=L.offset+L.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"})),b.title&&(n.title=b.title),b.duration>0&&(n.duration=b.duration),b.duration===0&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!b.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(b.attributes.METHOD==="NONE"){o=null;return}if(!b.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(b.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:b.attributes};return}if(b.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:b.attributes.URI};return}if(b.attributes.KEYFORMAT===f){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(b.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(b.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),b.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(b.attributes.KEYID&&b.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:b.attributes.KEYFORMAT,keyId:b.attributes.KEYID.substring(2)},pssh:vA(b.attributes.URI.split(",")[1])};return}b.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),o={method:b.attributes.METHOD||"AES-128",uri:b.attributes.URI},typeof b.attributes.IV<"u"&&(o.iv=b.attributes.IV)},"media-sequence"(){if(!isFinite(b.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+b.number});return}this.manifest.mediaSequence=b.number},"discontinuity-sequence"(){if(!isFinite(b.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+b.number});return}this.manifest.discontinuitySequence=b.number,g=b.number},"playlist-type"(){if(!/VOD|EVENT/.test(b.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+b.playlist});return}this.manifest.playlistType=b.playlistType},map(){r={},b.uri&&(r.uri=b.uri),b.byterange&&(r.byterange=b.byterange),o&&(r.key=o)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!b.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}n.attributes||(n.attributes={}),Mi(n.attributes,b.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(b.attributes&&b.attributes.TYPE&&b.attributes["GROUP-ID"]&&b.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const L=this.manifest.mediaGroups[b.attributes.TYPE];L[b.attributes["GROUP-ID"]]=L[b.attributes["GROUP-ID"]]||{},E=L[b.attributes["GROUP-ID"]],w={default:/yes/i.test(b.attributes.DEFAULT)},w.default?w.autoselect=!0:w.autoselect=/yes/i.test(b.attributes.AUTOSELECT),b.attributes.LANGUAGE&&(w.language=b.attributes.LANGUAGE),b.attributes.URI&&(w.uri=b.attributes.URI),b.attributes["INSTREAM-ID"]&&(w.instreamId=b.attributes["INSTREAM-ID"]),b.attributes.CHARACTERISTICS&&(w.characteristics=b.attributes.CHARACTERISTICS),b.attributes.FORCED&&(w.forced=/yes/i.test(b.attributes.FORCED)),E[b.attributes.NAME]=w},discontinuity(){g+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=b.dateTimeString,this.manifest.dateTimeObject=b.dateTimeObject),n.dateTimeString=b.dateTimeString,n.dateTimeObject=b.dateTimeObject;const{lastProgramDateTime:L}=this;this.lastProgramDateTime=new Date(b.dateTimeString).getTime(),L===null&&this.manifest.segments.reduceRight((I,F)=>(F.programDateTime=I-F.duration*1e3,F.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(b.duration)||b.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+b.duration});return}this.manifest.targetDuration=b.duration,sy.call(this,this.manifest)},start(){if(!b.attributes||isNaN(b.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:b.attributes["TIME-OFFSET"],precise:b.attributes.PRECISE}},"cue-out"(){n.cueOut=b.data},"cue-out-cont"(){n.cueOutCont=b.data},"cue-in"(){n.cueIn=b.data},skip(){this.manifest.skip=io(b.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",b.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const L=this.manifest.segments.length,I=io(b.attributes);n.parts=n.parts||[],n.parts.push(I),I.byterange&&(I.byterange.hasOwnProperty("offset")||(I.byterange.offset=v),v=I.byterange.offset+I.byterange.length);const F=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${F} for segment #${L}`,b.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((B,V)=>{B.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${V} lacks required attribute(s): LAST-PART`})})},"server-control"(){const L=this.manifest.serverControl=io(b.attributes);L.hasOwnProperty("canBlockReload")||(L.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),sy.call(this,this.manifest),L.canSkipDateranges&&!L.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 L=this.manifest.segments.length,I=io(b.attributes),F=I.type&&I.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(I),I.byterange&&(I.byterange.hasOwnProperty("offset")||(I.byterange.offset=F?v:0,F&&(v=I.byterange.offset+I.byterange.length)));const B=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${B} for segment #${L}`,b.attributes,["TYPE","URI"]),!!I.type)for(let V=0;VV.id===I.id);this.manifest.dateRanges[B]=Mi(this.manifest.dateRanges[B],I),_[I.id]=Mi(_[I.id],I),this.manifest.dateRanges.pop()}},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=io(b.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",b.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const L=(I,F)=>{if(I in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${I}`});return}this.manifest.definitions[I]=F};if("QUERYPARAM"in b.attributes){if("NAME"in b.attributes||"IMPORT"in b.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const I=this.params.get(b.attributes.QUERYPARAM);if(!I){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${b.attributes.QUERYPARAM}`});return}L(b.attributes.QUERYPARAM,decodeURIComponent(I));return}if("NAME"in b.attributes){if("IMPORT"in b.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in b.attributes)||typeof b.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${b.attributes.NAME}`});return}L(b.attributes.NAME,b.attributes.VALUE);return}if("IMPORT"in b.attributes){if(!this.mainDefinitions[b.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${b.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}L(b.attributes.IMPORT,this.mainDefinitions[b.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:b.attributes,uri:b.uri,timeline:g}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",b.attributes,["BANDWIDTH","URI"])}}[b.tagType]||c).call(t)},uri(){n.uri=b.uri,i.push(n),this.manifest.targetDuration&&!("duration"in n)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),n.duration=this.manifest.targetDuration),o&&(n.key=o),n.timeline=g,r&&(n.map=r),v=0,this.lastProgramDateTime!==null&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=n.duration*1e3),n={}},comment(){},custom(){b.segment?(n.custom=n.custom||{},n.custom[b.customType]=b.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[b.customType]=b.data)}})[b.type].call(t)})}requiredCompatibilityversion(e,t){(eg&&(f-=g,f-=g,f-=cs(2))}return Number(f)},cP=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=cs(e);for(var o=oP(e),u=new Uint8Array(new ArrayBuffer(o)),c=0;c=t.length&&d.call(t,function(f,g){var m=c[g]?c[g]&e[o+g]:e[o+g];return f===m})},hP=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var o in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][o];i(u,n,r,o)}})},fd={},aa={},sl={},Jx;function pg(){if(Jx)return sl;Jx=1;function s(r,o,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,o);for(var c=0;c=0&&j=0){for(var Me=K.length-1;xe0},lookupPrefix:function(j){for(var K=this;K;){var le=K._nsMap;if(le){for(var xe in le)if(Object.prototype.hasOwnProperty.call(le,xe)&&le[xe]===j)return xe}K=K.nodeType==m?K.ownerDocument:K.parentNode}return null},lookupNamespaceURI:function(j){for(var K=this;K;){var le=K._nsMap;if(le&&Object.prototype.hasOwnProperty.call(le,j))return le[j];K=K.nodeType==m?K.ownerDocument:K.parentNode}return null},isDefaultNamespace:function(j){var K=this.lookupPrefix(j);return K==null}};function se(j){return j=="<"&&"<"||j==">"&&">"||j=="&"&&"&"||j=='"'&&"""||"&#"+j.charCodeAt()+";"}c(f,$),c(f,$.prototype);function he(j,K){if(K(j))return!0;if(j=j.firstChild)do if(he(j,K))return!0;while(j=j.nextSibling)}function Se(){this.ownerDocument=this}function be(j,K,le){j&&j._inc++;var xe=le.namespaceURI;xe===t.XMLNS&&(K._nsMap[le.prefix?le.localName:""]=le.value)}function Pe(j,K,le,xe){j&&j._inc++;var Me=le.namespaceURI;Me===t.XMLNS&&delete K._nsMap[le.prefix?le.localName:""]}function Ae(j,K,le){if(j&&j._inc){j._inc++;var xe=K.childNodes;if(le)xe[xe.length++]=le;else{for(var Me=K.firstChild,tt=0;Me;)xe[tt++]=Me,Me=Me.nextSibling;xe.length=tt,delete xe[xe.length]}}}function Be(j,K){var le=K.previousSibling,xe=K.nextSibling;return le?le.nextSibling=xe:j.firstChild=xe,xe?xe.previousSibling=le:j.lastChild=le,K.parentNode=null,K.previousSibling=null,K.nextSibling=null,Ae(j.ownerDocument,j),K}function $e(j){return j&&(j.nodeType===$.DOCUMENT_NODE||j.nodeType===$.DOCUMENT_FRAGMENT_NODE||j.nodeType===$.ELEMENT_NODE)}function Je(j){return j&&(Tt(j)||Ni(j)||ht(j)||j.nodeType===$.DOCUMENT_FRAGMENT_NODE||j.nodeType===$.COMMENT_NODE||j.nodeType===$.PROCESSING_INSTRUCTION_NODE)}function ht(j){return j&&j.nodeType===$.DOCUMENT_TYPE_NODE}function Tt(j){return j&&j.nodeType===$.ELEMENT_NODE}function Ni(j){return j&&j.nodeType===$.TEXT_NODE}function It(j,K){var le=j.childNodes||[];if(e(le,Tt)||ht(K))return!1;var xe=e(le,ht);return!(K&&xe&&le.indexOf(xe)>le.indexOf(K))}function Li(j,K){var le=j.childNodes||[];function xe(tt){return Tt(tt)&&tt!==K}if(e(le,xe))return!1;var Me=e(le,ht);return!(K&&Me&&le.indexOf(Me)>le.indexOf(K))}function We(j,K,le){if(!$e(j))throw new ee(R,"Unexpected parent node type "+j.nodeType);if(le&&le.parentNode!==j)throw new ee(P,"child not in parent");if(!Je(K)||ht(K)&&j.nodeType!==$.DOCUMENT_NODE)throw new ee(R,"Unexpected node type "+K.nodeType+" for parent node type "+j.nodeType)}function Jt(j,K,le){var xe=j.childNodes||[],Me=K.childNodes||[];if(K.nodeType===$.DOCUMENT_FRAGMENT_NODE){var tt=Me.filter(Tt);if(tt.length>1||e(Me,Ni))throw new ee(R,"More than one element or text in fragment");if(tt.length===1&&!It(j,le))throw new ee(R,"Element in fragment can not be inserted before doctype")}if(Tt(K)&&!It(j,le))throw new ee(R,"Only one element can be added and only after doctype");if(ht(K)){if(e(xe,ht))throw new ee(R,"Only one doctype is allowed");var Ot=e(xe,Tt);if(le&&xe.indexOf(Ot)1||e(Me,Ni))throw new ee(R,"More than one element or text in fragment");if(tt.length===1&&!Li(j,le))throw new ee(R,"Element in fragment can not be inserted before doctype")}if(Tt(K)&&!Li(j,le))throw new ee(R,"Only one element can be added and only after doctype");if(ht(K)){let fs=function(ns){return ht(ns)&&ns!==le};var Yi=fs;if(e(xe,fs))throw new ee(R,"Only one doctype is allowed");var Ot=e(xe,Tt);if(le&&xe.indexOf(Ot)0&&he(le.documentElement,function(Me){if(Me!==le&&Me.nodeType===g){var tt=Me.getAttribute("class");if(tt){var Ot=j===tt;if(!Ot){var Yi=o(tt);Ot=K.every(u(Yi))}Ot&&xe.push(Me)}}}),xe})},createElement:function(j){var K=new Ct;K.ownerDocument=this,K.nodeName=j,K.tagName=j,K.localName=j,K.childNodes=new ie;var le=K.attributes=new H;return le._ownerElement=K,K},createDocumentFragment:function(){var j=new et;return j.ownerDocument=this,j.childNodes=new ie,j},createTextNode:function(j){var K=new xs;return K.ownerDocument=this,K.appendData(j),K},createComment:function(j){var K=new Oe;return K.ownerDocument=this,K.appendData(j),K},createCDATASection:function(j){var K=new Fe;return K.ownerDocument=this,K.appendData(j),K},createProcessingInstruction:function(j,K){var le=new ei;return le.ownerDocument=this,le.tagName=le.nodeName=le.target=j,le.nodeValue=le.data=K,le},createAttribute:function(j){var K=new Gi;return K.ownerDocument=this,K.name=j,K.nodeName=j,K.localName=j,K.specified=!0,K},createEntityReference:function(j){var K=new pt;return K.ownerDocument=this,K.nodeName=j,K},createElementNS:function(j,K){var le=new Ct,xe=K.split(":"),Me=le.attributes=new H;return le.childNodes=new ie,le.ownerDocument=this,le.nodeName=K,le.tagName=K,le.namespaceURI=j,xe.length==2?(le.prefix=xe[0],le.localName=xe[1]):le.localName=K,Me._ownerElement=le,le},createAttributeNS:function(j,K){var le=new Gi,xe=K.split(":");return le.ownerDocument=this,le.nodeName=K,le.name=K,le.namespaceURI=j,le.specified=!0,xe.length==2?(le.prefix=xe[0],le.localName=xe[1]):le.localName=K,le}},d(Se,$);function Ct(){this._nsMap={}}Ct.prototype={nodeType:g,hasAttribute:function(j){return this.getAttributeNode(j)!=null},getAttribute:function(j){var K=this.getAttributeNode(j);return K&&K.value||""},getAttributeNode:function(j){return this.attributes.getNamedItem(j)},setAttribute:function(j,K){var le=this.ownerDocument.createAttribute(j);le.value=le.nodeValue=""+K,this.setAttributeNode(le)},removeAttribute:function(j){var K=this.getAttributeNode(j);K&&this.removeAttributeNode(K)},appendChild:function(j){return j.nodeType===B?this.insertBefore(j,null):_t(this,j)},setAttributeNode:function(j){return this.attributes.setNamedItem(j)},setAttributeNodeNS:function(j){return this.attributes.setNamedItemNS(j)},removeAttributeNode:function(j){return this.attributes.removeNamedItem(j.nodeName)},removeAttributeNS:function(j,K){var le=this.getAttributeNodeNS(j,K);le&&this.removeAttributeNode(le)},hasAttributeNS:function(j,K){return this.getAttributeNodeNS(j,K)!=null},getAttributeNS:function(j,K){var le=this.getAttributeNodeNS(j,K);return le&&le.value||""},setAttributeNS:function(j,K,le){var xe=this.ownerDocument.createAttributeNS(j,K);xe.value=xe.nodeValue=""+le,this.setAttributeNode(xe)},getAttributeNodeNS:function(j,K){return this.attributes.getNamedItemNS(j,K)},getElementsByTagName:function(j){return new Q(this,function(K){var le=[];return he(K,function(xe){xe!==K&&xe.nodeType==g&&(j==="*"||xe.tagName==j)&&le.push(xe)}),le})},getElementsByTagNameNS:function(j,K){return new Q(this,function(le){var xe=[];return he(le,function(Me){Me!==le&&Me.nodeType===g&&(j==="*"||Me.namespaceURI===j)&&(K==="*"||Me.localName==K)&&xe.push(Me)}),xe})}},Se.prototype.getElementsByTagName=Ct.prototype.getElementsByTagName,Se.prototype.getElementsByTagNameNS=Ct.prototype.getElementsByTagNameNS,d(Ct,$);function Gi(){}Gi.prototype.nodeType=m,d(Gi,$);function $t(){}$t.prototype={data:"",substringData:function(j,K){return this.data.substring(j,j+K)},appendData:function(j){j=this.data+j,this.nodeValue=this.data=j,this.length=j.length},insertData:function(j,K){this.replaceData(j,0,K)},appendChild:function(j){throw new Error(q[R])},deleteData:function(j,K){this.replaceData(j,K,"")},replaceData:function(j,K,le){var xe=this.data.substring(0,j),Me=this.data.substring(j+K);le=xe+le+Me,this.nodeValue=this.data=le,this.length=le.length}},d($t,$);function xs(){}xs.prototype={nodeName:"#text",nodeType:v,splitText:function(j){var K=this.data,le=K.substring(j);K=K.substring(0,j),this.data=this.nodeValue=K,this.length=K.length;var xe=this.ownerDocument.createTextNode(le);return this.parentNode&&this.parentNode.insertBefore(xe,this.nextSibling),xe}},d(xs,$t);function Oe(){}Oe.prototype={nodeName:"#comment",nodeType:L},d(Oe,$t);function Fe(){}Fe.prototype={nodeName:"#cdata-section",nodeType:_},d(Fe,$t);function je(){}je.prototype.nodeType=F,d(je,$);function Qe(){}Qe.prototype.nodeType=V,d(Qe,$);function rt(){}rt.prototype.nodeType=E,d(rt,$);function pt(){}pt.prototype.nodeType=b,d(pt,$);function et(){}et.prototype.nodeName="#document-fragment",et.prototype.nodeType=B,d(et,$);function ei(){}ei.prototype.nodeType=w,d(ei,$);function Ft(){}Ft.prototype.serializeToString=function(j,K,le){return ti.call(j,K,le)},$.prototype.toString=ti;function ti(j,K){var le=[],xe=this.nodeType==9&&this.documentElement||this,Me=xe.prefix,tt=xe.namespaceURI;if(tt&&Me==null){var Me=xe.lookupPrefix(tt);if(Me==null)var Ot=[{namespace:tt,prefix:null}]}return Rt(this,le,j,K,Ot),le.join("")}function vi(j,K,le){var xe=j.prefix||"",Me=j.namespaceURI;if(!Me||xe==="xml"&&Me===t.XML||Me===t.XMLNS)return!1;for(var tt=le.length;tt--;){var Ot=le[tt];if(Ot.prefix===xe)return Ot.namespace!==Me}return!0}function Fn(j,K,le){j.push(" ",K,'="',le.replace(/[<>&"\t\n\r]/g,se),'"')}function Rt(j,K,le,xe,Me){if(Me||(Me=[]),xe)if(j=xe(j),j){if(typeof j=="string"){K.push(j);return}}else return;switch(j.nodeType){case g:var tt=j.attributes,Ot=tt.length,Dt=j.firstChild,Yi=j.tagName;le=t.isHTML(j.namespaceURI)||le;var fs=Yi;if(!le&&!j.prefix&&j.namespaceURI){for(var ns,ps=0;ps=0;gs--){var li=Me[gs];if(li.prefix===""&&li.namespace===j.namespaceURI){ns=li.namespace;break}}if(ns!==j.namespaceURI)for(var gs=Me.length-1;gs>=0;gs--){var li=Me[gs];if(li.namespace===j.namespaceURI){li.prefix&&(fs=li.prefix+":"+Yi);break}}}K.push("<",fs);for(var _n=0;_n"),le&&/^script$/i.test(Yi))for(;Dt;)Dt.data?K.push(Dt.data):Rt(Dt,K,le,xe,Me.slice()),Dt=Dt.nextSibling;else for(;Dt;)Rt(Dt,K,le,xe,Me.slice()),Dt=Dt.nextSibling;K.push("")}else K.push("/>");return;case I:case B:for(var Dt=j.firstChild;Dt;)Rt(Dt,K,le,xe,Me.slice()),Dt=Dt.nextSibling;return;case m:return Fn(K,j.name,j.value);case v:return K.push(j.data.replace(/[<&>]/g,se));case _:return K.push("");case L:return K.push("");case F:var St=j.publicId,bn=j.systemId;if(K.push("");else if(bn&&bn!=".")K.push(" SYSTEM ",bn,">");else{var Fr=j.internalSubset;Fr&&K.push(" [",Fr,"]"),K.push(">")}return;case w:return K.push("");case b:return K.push("&",j.nodeName,";");default:K.push("??",j.nodeName)}}function xi(j,K,le){var xe;switch(K.nodeType){case g:xe=K.cloneNode(!1),xe.ownerDocument=j;case B:break;case m:le=!0;break}if(xe||(xe=K.cloneNode(!1)),xe.ownerDocument=j,xe.parentNode=null,le)for(var Me=K.firstChild;Me;)xe.appendChild(xi(j,Me,le)),Me=Me.nextSibling;return xe}function Os(j,K,le){var xe=new K.constructor;for(var Me in K)if(Object.prototype.hasOwnProperty.call(K,Me)){var tt=K[Me];typeof tt!="object"&&tt!=xe[Me]&&(xe[Me]=tt)}switch(K.childNodes&&(xe.childNodes=new ie),xe.ownerDocument=j,xe.nodeType){case g:var Ot=K.attributes,Yi=xe.attributes=new H,fs=Ot.length;Yi._ownerElement=xe;for(var ns=0;ns",lt:"<",quot:'"'}),s.HTML_ENTITIES=e({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:` +`,nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}),s.entityMap=s.HTML_ENTITIES})(ry)),ry}var Bf={},iE;function pP(){if(iE)return Bf;iE=1;var s=pg().NAMESPACE,e=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,t=new RegExp("[\\-\\.0-9"+e.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),i=new RegExp("^"+e.source+t.source+"*(?::"+e.source+t.source+"*)?$"),n=0,r=1,o=2,u=3,c=4,d=5,f=6,g=7;function m(R,P){this.message=R,this.locator=P,Error.captureStackTrace&&Error.captureStackTrace(this,m)}m.prototype=new Error,m.prototype.name=m.name;function v(){}v.prototype={parse:function(R,P,z){var ee=this.domBuilder;ee.startDocument(),F(P,P={}),_(R,P,z,ee,this.errorHandler),ee.endDocument()}};function _(R,P,z,ee,ie){function Q(_t){if(_t>65535){_t-=65536;var Ct=55296+(_t>>10),Gi=56320+(_t&1023);return String.fromCharCode(Ct,Gi)}else return String.fromCharCode(_t)}function oe(_t){var Ct=_t.slice(1,-1);return Object.hasOwnProperty.call(z,Ct)?z[Ct]:Ct.charAt(0)==="#"?Q(parseInt(Ct.substr(1).replace("x","0x"))):(ie.error("entity not found:"+_t),_t)}function H(_t){if(_t>Se){var Ct=R.substring(Se,_t).replace(/&#?\w+;/g,oe);$&&X(Se),ee.characters(Ct,0,_t-Se),Se=_t}}function X(_t,Ct){for(;_t>=ae&&(Ct=ce.exec(R));)te=Ct.index,ae=te+Ct[0].length,$.lineNumber++;$.columnNumber=_t-te+1}for(var te=0,ae=0,ce=/.*(?:\r\n?|\n)|.*$/g,$=ee.locator,se=[{currentNSMap:P}],he={},Se=0;;){try{var be=R.indexOf("<",Se);if(be<0){if(!R.substr(Se).match(/^\s*$/)){var Pe=ee.doc,Ae=Pe.createTextNode(R.substr(Se));Pe.appendChild(Ae),ee.currentElement=Ae}return}switch(be>Se&&H(be),R.charAt(be+1)){case"/":var We=R.indexOf(">",be+3),Be=R.substring(be+2,We).replace(/[ \t\n\r]+$/g,""),$e=se.pop();We<0?(Be=R.substring(be+2).replace(/[\s<].*/,""),ie.error("end tag name: "+Be+" is not complete:"+$e.tagName),We=be+1+Be.length):Be.match(/\sSe?Se=We:H(Math.max(be,Se)+1)}}function b(R,P){return P.lineNumber=R.lineNumber,P.columnNumber=R.columnNumber,P}function E(R,P,z,ee,ie,Q){function oe($,se,he){z.attributeNames.hasOwnProperty($)&&Q.fatalError("Attribute "+$+" redefined"),z.addValue($,se.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,ie),he)}for(var H,X,te=++P,ae=n;;){var ce=R.charAt(te);switch(ce){case"=":if(ae===r)H=R.slice(P,te),ae=u;else if(ae===o)ae=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(ae===u||ae===r)if(ae===r&&(Q.warning('attribute value must after "="'),H=R.slice(P,te)),P=te+1,te=R.indexOf(ce,P),te>0)X=R.slice(P,te),oe(H,X,P-1),ae=d;else throw new Error("attribute value no end '"+ce+"' match");else if(ae==c)X=R.slice(P,te),oe(H,X,P),Q.warning('attribute "'+H+'" missed start quot('+ce+")!!"),P=te+1,ae=d;else throw new Error('attribute value must after "="');break;case"/":switch(ae){case n:z.setTagName(R.slice(P,te));case d:case f:case g:ae=g,z.closed=!0;case c:case r:break;case o:z.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return Q.error("unexpected end of input"),ae==n&&z.setTagName(R.slice(P,te)),te;case">":switch(ae){case n:z.setTagName(R.slice(P,te));case d:case f:case g:break;case c:case r:X=R.slice(P,te),X.slice(-1)==="/"&&(z.closed=!0,X=X.slice(0,-1));case o:ae===o&&(X=H),ae==c?(Q.warning('attribute "'+X+'" missed quot(")!'),oe(H,X,P)):((!s.isHTML(ee[""])||!X.match(/^(?:disabled|checked|selected)$/i))&&Q.warning('attribute "'+X+'" missed value!! "'+X+'" instead!!'),oe(X,X,P));break;case u:throw new Error("attribute value missed!!")}return te;case"€":ce=" ";default:if(ce<=" ")switch(ae){case n:z.setTagName(R.slice(P,te)),ae=f;break;case r:H=R.slice(P,te),ae=o;break;case c:var X=R.slice(P,te);Q.warning('attribute "'+X+'" missed quot(")!!'),oe(H,X,P);case d:ae=f;break}else switch(ae){case o:z.tagName,(!s.isHTML(ee[""])||!H.match(/^(?:disabled|checked|selected)$/i))&&Q.warning('attribute "'+H+'" missed value!! "'+H+'" instead2!!'),oe(H,H,P),P=te,ae=r;break;case d:Q.warning('attribute space is required"'+H+'"!!');case f:ae=r,P=te;break;case u:ae=c,P=te;break;case g:throw new Error("elements closed character '/' and '>' must be connected to")}}te++}}function w(R,P,z){for(var ee=R.tagName,ie=null,ce=R.length;ce--;){var Q=R[ce],oe=Q.qName,H=Q.value,$=oe.indexOf(":");if($>0)var X=Q.prefix=oe.slice(0,$),te=oe.slice($+1),ae=X==="xmlns"&&te;else te=oe,X=null,ae=oe==="xmlns"&&"";Q.localName=te,ae!==!1&&(ie==null&&(ie={},F(z,z={})),z[ae]=ie[ae]=H,Q.uri=s.XMLNS,P.startPrefixMapping(ae,H))}for(var ce=R.length;ce--;){Q=R[ce];var X=Q.prefix;X&&(X==="xml"&&(Q.uri=s.XML),X!=="xmlns"&&(Q.uri=z[X||""]))}var $=ee.indexOf(":");$>0?(X=R.prefix=ee.slice(0,$),te=R.localName=ee.slice($+1)):(X=null,te=R.localName=ee);var se=R.uri=z[X||""];if(P.startElement(se,te,ee,R),R.closed){if(P.endElement(se,te,ee),ie)for(X in ie)Object.prototype.hasOwnProperty.call(ie,X)&&P.endPrefixMapping(X)}else return R.currentNSMap=z,R.localNSMap=ie,!0}function L(R,P,z,ee,ie){if(/^(?:script|textarea)$/i.test(z)){var Q=R.indexOf("",P),oe=R.substring(P+1,Q);if(/[&<]/.test(oe))return/^script$/i.test(z)?(ie.characters(oe,0,oe.length),Q):(oe=oe.replace(/&#?\w+;/g,ee),ie.characters(oe,0,oe.length),Q)}return P+1}function I(R,P,z,ee){var ie=ee[z];return ie==null&&(ie=R.lastIndexOf(""),ie",P+4);return Q>P?(z.comment(R,P+4,Q-P-4),Q+3):(ee.error("Unclosed comment"),-1)}else return-1;default:if(R.substr(P+3,6)=="CDATA["){var Q=R.indexOf("]]>",P+9);return z.startCDATA(),z.characters(R,P+9,Q-P-9),z.endCDATA(),Q+3}var oe=q(R,P),H=oe.length;if(H>1&&/!doctype/i.test(oe[0][0])){var X=oe[1][0],te=!1,ae=!1;H>3&&(/^public$/i.test(oe[2][0])?(te=oe[3][0],ae=H>4&&oe[4][0]):/^system$/i.test(oe[2][0])&&(ae=oe[3][0]));var ce=oe[H-1];return z.startDTD(X,te,ae),z.endDTD(),ce.index+ce[0].length}}return-1}function V(R,P,z){var ee=R.indexOf("?>",P);if(ee){var ie=R.substring(P,ee).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return ie?(ie[0].length,z.processingInstruction(ie[1],ie[2]),ee+2):-1}return-1}function N(){this.attributeNames={}}N.prototype={setTagName:function(R){if(!i.test(R))throw new Error("invalid tagName:"+R);this.tagName=R},addValue:function(R,P,z){if(!i.test(R))throw new Error("invalid attribute:"+R);this.attributeNames[R]=this.length,this[this.length++]={qName:R,value:P,offset:z}},length:0,getLocalName:function(R){return this[R].localName},getLocator:function(R){return this[R].locator},getQName:function(R){return this[R].qName},getURI:function(R){return this[R].uri},getValue:function(R){return this[R].value}};function q(R,P){var z,ee=[],ie=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(ie.lastIndex=P,ie.exec(R);z=ie.exec(R);)if(ee.push(z),z[1])return ee}return Bf.XMLReader=v,Bf.ParseError=m,Bf}var sE;function gP(){if(sE)return pd;sE=1;var s=pg(),e=EA(),t=fP(),i=pP(),n=e.DOMImplementation,r=s.NAMESPACE,o=i.ParseError,u=i.XMLReader;function c(E){return E.replace(/\r[\n\u0085]/g,` +`).replace(/[\r\u0085\u2028]/g,` +`)}function d(E){this.options=E||{locator:{}}}d.prototype.parseFromString=function(E,w){var L=this.options,I=new u,F=L.domBuilder||new g,B=L.errorHandler,V=L.locator,N=L.xmlns||{},q=/\/x?html?$/.test(w),R=q?t.HTML_ENTITIES:t.XML_ENTITIES;V&&F.setDocumentLocator(V),I.errorHandler=f(B,F,V),I.domBuilder=L.domBuilder||F,q&&(N[""]=r.HTML),N.xml=N.xml||r.XML;var P=L.normalizeLineEndings||c;return E&&typeof E=="string"?I.parse(P(E),N,R):I.errorHandler.error("invalid doc source"),F.doc};function f(E,w,L){if(!E){if(w instanceof g)return w;E=w}var I={},F=E instanceof Function;L=L||{};function B(V){var N=E[V];!N&&F&&(N=E.length==2?function(q){E(V,q)}:E),I[V]=N&&function(q){N("[xmldom "+V+"] "+q+v(L))}||function(){}}return B("warning"),B("error"),B("fatalError"),I}function g(){this.cdata=!1}function m(E,w){w.lineNumber=E.lineNumber,w.columnNumber=E.columnNumber}g.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(E,w,L,I){var F=this.doc,B=F.createElementNS(E,L||w),V=I.length;b(this,B),this.currentElement=B,this.locator&&m(this.locator,B);for(var N=0;N=w+L||w?new java.lang.String(E,w,L)+"":E}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(E){g.prototype[E]=function(){return null}});function b(E,w){E.currentElement?E.currentElement.appendChild(w):E.doc.appendChild(w)}return pd.__DOMHandler=g,pd.normalizeLineEndings=c,pd.DOMParser=d,pd}var nE;function mP(){if(nE)return fd;nE=1;var s=EA();return fd.DOMImplementation=s.DOMImplementation,fd.XMLSerializer=s.XMLSerializer,fd.DOMParser=gP().DOMParser,fd}var yP=mP();const rE=s=>!!s&&typeof s=="object",is=(...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]):rE(e[i])&&rE(t[i])?e[i]=is(e[i],t[i]):e[i]=t[i]}),e),{}),AA=s=>Object.keys(s).map(e=>s[e]),vP=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),CA=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),_P=(s,e)=>AA(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var Yu={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 Ud=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:fg(s||"",e)};if(t||i){const o=(t||i).split("-");let u=ne.BigInt?ne.BigInt(o[0]):parseInt(o[0],10),c=ne.BigInt?ne.BigInt(o[1]):parseInt(o[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=ne.BigInt(s.offset)+ne.BigInt(s.length)-ne.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},aE=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),SP={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=aE(s.endNumber),o=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/o}:{start:0,end:i/o}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:o=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=aE(s.endNumber),f=(e+t)/1e3,g=i+o,v=f+u-g,_=Math.ceil(v*n/r),b=Math.floor((f-g-c)*n/r),E=Math.floor((f-g)*n/r);return{start:Math.max(0,b),end:typeof d=="number"?d:Math.min(_,E)}}},xP=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}},aT=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:o,end:u}=SP[e](s),c=vP(o,u).map(xP(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},DA=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:o,number:u=0,duration:c}=s;if(!e)throw new Error(Yu.NO_BASE_URL);const d=Ud({baseUrl:e,source:t.sourceURL,range:t.range}),f=Ud({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const g=aT(s);g.length&&(f.duration=g[0].duration,f.timeline=g[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=o||r,f.number=u,[f]},oT=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,o=s.sidx.byterange,u=o.offset+o.length,c=e.timescale,d=e.references.filter(E=>E.referenceType!==1),f=[],g=s.endList?"static":"dynamic",m=s.sidx.timeline;let v=m,_=s.mediaSequence||0,b;typeof e.firstOffset=="bigint"?b=ne.BigInt(u)+e.firstOffset:b=u+e.firstOffset;for(let E=0;E_P(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),CP=(s,e)=>{for(let t=0;t{let e=[];return hP(s,EP,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},lE=({playlist:s,mediaSequence:e})=>{s.mediaSequence=e,s.segments.forEach((t,i)=>{t.number=s.mediaSequence+i})},DP=({oldPlaylists:s,newPlaylists:e,timelineStarts:t})=>{e.forEach(i=>{i.discontinuitySequence=t.findIndex(function({timeline:c}){return c===i.timeline});const n=CP(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],o=n.segments.findIndex(function(c){return Math.abs(c.presentationTime-r.presentationTime)n.timeline||n.segments.length&&i.timeline>n.segments[n.segments.length-1].timeline)&&i.discontinuitySequence--;return}n.segments[o].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),lE({playlist:i,mediaSequence:n.segments[o].number})})},wP=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(oE(s)),i=e.playlists.concat(oE(e));return e.timelineStarts=wA([s.timelineStarts,e.timelineStarts]),DP({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},gg=s=>s&&s.uri+"-"+bP(s.byterange),ay=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=AA(i.reduce((r,o)=>{const u=o.attributes.id+(o.attributes.lang||"");return r[u]?(o.segments&&(o.segments[0]&&(o.segments[0].discontinuity=!0),r[u].segments.push(...o.segments)),o.attributes.contentProtection&&(r[u].attributes.contentProtection=o.attributes.contentProtection)):(r[u]=o,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:o.attributes.periodStart,timeline:o.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=TP(i.segments||[],"discontinuity"),i))},lT=(s,e)=>{const t=gg(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&oT(s,i,s.sidx.resolvedUri),s},LP=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=lT(s[t],e);return s},IP=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},o)=>{const u={attributes:{NAME:s.id,BANDWIDTH:s.bandwidth,CODECS:s.codecs,"PROGRAM-ID":1},uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,discontinuitySequence:n,discontinuityStarts:r,timelineStarts:s.timelineStarts,mediaSequence:i,segments:e};return s.contentProtection&&(u.contentProtection=s.contentProtection),s.serviceLocation&&(u.attributes.serviceLocation=s.serviceLocation),t&&(u.sidx=t),o&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},RP=({attributes:s,segments:e,mediaSequence:t,discontinuityStarts:i,discontinuitySequence:n})=>{typeof e>"u"&&(e=[{uri:s.baseUrl,timeline:s.periodStart,resolvedUri:s.baseUrl||"",duration:s.sourceDuration,number:0}],s.duration=s.sourceDuration);const r={NAME:s.id,BANDWIDTH:s.bandwidth,"PROGRAM-ID":1};s.codecs&&(r.CODECS=s.codecs);const o={attributes:r,uri:"",endList:s.type==="static",timeline:s.periodStart,resolvedUri:s.baseUrl||"",targetDuration:s.duration,timelineStarts:s.timelineStarts,discontinuityStarts:i,discontinuitySequence:n,mediaSequence:t,segments:e};return s.serviceLocation&&(o.attributes.serviceLocation=s.serviceLocation),o},kP=(s,e={},t=!1)=>{let i;const n=s.reduce((r,o)=>{const u=o.attributes.role&&o.attributes.role.value||"",c=o.attributes.lang||"";let d=o.attributes.label||"main";if(c&&!o.attributes.label){const g=u?` (${u})`:"";d=`${o.attributes.lang}${g}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=lT(IP(o,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=o,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},OP=(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(lT(RP(i),e)),t},{}),PP=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),{}),MP=({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},NP=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",BP=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",FP=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",UP=(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})})},uE=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],$P=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:o,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=ay(s.filter(NP)).map(MP),g=ay(s.filter(BP)),m=ay(s.filter(FP)),v=s.map(F=>F.attributes.captionServices).filter(Boolean),_={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:o,playlists:LP(f,i)};d>=0&&(_.minimumUpdatePeriod=d*1e3),e&&(_.locations=e),t&&(_.contentSteering=t),u==="dynamic"&&(_.suggestedPresentationDelay=c),r&&r.length>0&&(_.eventStream=r);const b=_.playlists.length===0,E=g.length?kP(g,i,b):null,w=m.length?OP(m,i):null,L=f.concat(uE(E),uE(w)),I=L.map(({timelineStarts:F})=>F);return _.timelineStarts=wA(I),UP(L,_.timelineStarts),E&&(_.mediaGroups.AUDIO.audio=E),w&&(_.mediaGroups.SUBTITLES.subs=w),v.length&&(_.mediaGroups["CLOSED-CAPTIONS"].cc=PP(v)),n?wP({oldManifest:n,newManifest:_}):_},jP=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:o=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,m=d+c-f;return Math.ceil((m*o-e)/t)},LA=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:o=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let g=0;gf&&(f=b);let E;if(_<0){const I=g+1;I===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?E=jP(s,f,v):E=(r*o-f)/v:E=(e[I].t-f)/v}else E=_+1;const w=u+d.length+E;let L=u+d.length;for(;L(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}`},cE=(s,e)=>s.replace(HP,GP(e)),VP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?aT(s):LA(s,e),qP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=Ud({baseUrl:s.baseUrl,source:cE(i.sourceURL,t),range:i.range});return VP(s,e).map(o=>{t.Number=o.number,t.Time=o.time;const u=cE(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(o.time-d)/c;return{uri:u,timeline:o.timeline,duration:o.duration,resolvedUri:fg(s.baseUrl||"",u),map:n,number:o.number,presentationTime:f}})},zP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=Ud({baseUrl:t,source:i.sourceURL,range:i.range}),r=Ud({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},KP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(Yu.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>zP(s,c));let o;return t&&(o=aT(s)),e&&(o=LA(s,e)),o.map((c,d)=>{if(r[d]){const f=r[d],g=s.timescale||1,m=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-m)/g,f}}).filter(c=>c)},YP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=qP,t=is(s,e.template)):e.base?(i=DA,t=is(s,e.base)):e.list&&(i=KP,t=is(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:o,timescale:u=1}=t;t.duration=o/u}else r.length?t.duration=r.reduce((o,u)=>Math.max(o,Math.ceil(u.duration)),0):t.duration=0;return n.attributes=t,n.segments=r,e.base&&t.indexRange&&(n.sidx=r[0],n.segments=[]),n},WP=s=>s.map(YP),mi=(s,e)=>CA(s.childNodes).filter(({tagName:t})=>t===e),eh=s=>s.textContent.trim(),XP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),vu=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,g,m,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(g||0)*3600+parseFloat(m||0)*60+parseFloat(v||0)},QP=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),dE={mediaPresentationDuration(s){return vu(s)},availabilityStartTime(s){return QP(s)/1e3},minimumUpdatePeriod(s){return vu(s)},suggestedPresentationDelay(s){return vu(s)},type(s){return s},timeShiftBufferDepth(s){return vu(s)},start(s){return vu(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return XP(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)?vu(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}},Hi=s=>s&&s.attributes?CA(s.attributes).reduce((e,t)=>{const i=dE[t.name]||dE.DEFAULT;return e[t.name]=i(t.value),e},{}):{},ZP={"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"},mg=(s,e)=>e.length?Ku(s.map(function(t){return e.map(function(i){const n=eh(i),r=fg(t.baseUrl,n),o=is(Hi(i),{baseUrl:r});return r!==n&&!o.serviceLocation&&t.serviceLocation&&(o.serviceLocation=t.serviceLocation),o})})):s,uT=s=>{const e=mi(s,"SegmentTemplate")[0],t=mi(s,"SegmentList")[0],i=t&&mi(t,"SegmentURL").map(g=>is({tag:"SegmentURL"},Hi(g))),n=mi(s,"SegmentBase")[0],r=t||e,o=r&&mi(r,"SegmentTimeline")[0],u=t||n||e,c=u&&mi(u,"Initialization")[0],d=e&&Hi(e);d&&c?d.initialization=c&&Hi(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:o&&mi(o,"S").map(g=>Hi(g)),list:t&&is(Hi(t),{segmentUrls:i,initialization:Hi(c)}),base:n&&is(Hi(n),{initialization:Hi(c)})};return Object.keys(f).forEach(g=>{f[g]||delete f[g]}),f},JP=(s,e,t)=>i=>{const n=mi(i,"BaseURL"),r=mg(e,n),o=is(s,Hi(i)),u=uT(i);return r.map(c=>({segmentInfo:is(t,u),attributes:is(o,c)}))},eM=s=>s.reduce((e,t)=>{const i=Hi(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=ZP[i.schemeIdUri];if(n){e[n]={attributes:i};const r=mi(t,"cenc:pssh")[0];if(r){const o=eh(r);e[n].pssh=o&&vA(o)}}return e},{}),tM=s=>{if(s.schemeIdUri==="urn:scte:dash:cc:cea-608:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{let i,n;return n=t,/^CC\d=/.test(t)?[i,n]=t.split("="):/^CC\d$/.test(t)&&(i=t),{channel:i,language:n}});if(s.schemeIdUri==="urn:scte:dash:cc:cea-708:2015")return(typeof s.value!="string"?[]:s.value.split(";")).map(t=>{const i={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(t)){const[n,r=""]=t.split("=");i.channel=n,i.language=t,r.split(",").forEach(o=>{const[u,c]=o.split(":");u==="lang"?i.language=c:u==="er"?i.easyReader=Number(c):u==="war"?i.aspectRatio=Number(c):u==="3D"&&(i["3D"]=Number(c))})}else i.language=t;return i.channel&&(i.channel="SERVICE"+i.channel),i})},iM=s=>Ku(mi(s.node,"EventStream").map(e=>{const t=Hi(e),i=t.schemeIdUri;return mi(e,"Event").map(n=>{const r=Hi(n),o=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=o/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:eh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),sM=(s,e,t)=>i=>{const n=Hi(i),r=mg(e,mi(i,"BaseURL")),o=mi(i,"Role")[0],u={role:Hi(o)};let c=is(s,n,u);const d=mi(i,"Accessibility")[0],f=tM(Hi(d));f&&(c=is(c,{captionServices:f}));const g=mi(i,"Label")[0];if(g&&g.childNodes.length){const E=g.childNodes[0].nodeValue.trim();c=is(c,{label:E})}const m=eM(mi(i,"ContentProtection"));Object.keys(m).length&&(c=is(c,{contentProtection:m}));const v=uT(i),_=mi(i,"Representation"),b=is(t,v);return Ku(_.map(JP(c,r,b)))},nM=(s,e)=>(t,i)=>{const n=mg(e,mi(t.node,"BaseURL")),r=is(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const o=mi(t.node,"AdaptationSet"),u=uT(t.node);return Ku(o.map(sM(r,n,u)))},rM=(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=is({serverURL:eh(s[0])},Hi(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},aM=({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,oM=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,o=mi(s,"Period");if(!o.length)throw new Error(Yu.INVALID_NUMBER_OF_PERIOD);const u=mi(s,"Location"),c=Hi(s),d=mg([{baseUrl:t}],mi(s,"BaseURL")),f=mi(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(eh));const g=[];return o.forEach((m,v)=>{const _=Hi(m),b=g[v-1];_.start=aM({attributes:_,priorPeriodAttributes:b?b.attributes:null,mpdType:c.type}),g.push({node:m,attributes:_})}),{locations:c.locations,contentSteeringInfo:rM(f,r),representationInfo:Ku(g.map(nM(c,d))),eventStream:Ku(g.map(iM))}},IA=s=>{if(s==="")throw new Error(Yu.DASH_EMPTY_MANIFEST);const e=new yP.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(Yu.DASH_INVALID_XML);return i},lM=s=>{const e=mi(s,"UTCTiming")[0];if(!e)return null;const t=Hi(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(Yu.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},uM=(s,e={})=>{const t=oM(IA(s),e),i=WP(t.representationInfo);return $P({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},cM=s=>lM(IA(s));var oy,hE;function dM(){if(hE)return oy;hE=1;var s=Math.pow(2,32),e=function(t){var i=new DataView(t.buffer,t.byteOffset,t.byteLength),n;return i.getBigUint64?(n=i.getBigUint64(0),n0;r+=12,o--)n.references.push({referenceType:(t[r]&128)>>>7,referencedSize:i.getUint32(r)&2147483647,subsegmentDuration:i.getUint32(r+4),startsWithSap:!!(t[r+8]&128),sapType:(t[r+8]&112)>>>4,sapDeltaTime:i.getUint32(r+8)&268435455});return n};return ly=e,ly}var fM=hM();const pM=sc(fM);var gM=it([73,68,51]),mM=function(e,t){t===void 0&&(t=0),e=it(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},xd=function s(e,t){return t===void 0&&(t=0),e=it(e),e.length-t<10||!gi(e,gM,{offset:t})?t:(t+=mM(e,t),s(e,t))},pE=function(e){return typeof e=="string"?xA(e):e},yM=function(e){return Array.isArray(e)?e.map(function(t){return pE(t)}):[pE(e)]},vM=function s(e,t,i){i===void 0&&(i=!1),t=yM(t),e=it(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(o===0)break;var c=r+o;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);gi(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},Ff={EBML:it([26,69,223,163]),DocType:it([66,130]),Segment:it([24,83,128,103]),SegmentInfo:it([21,73,169,102]),Tracks:it([22,84,174,107]),Track:it([174]),TrackNumber:it([215]),DefaultDuration:it([35,227,131]),TrackEntry:it([174]),TrackType:it([131]),FlagDefault:it([136]),CodecID:it([134]),CodecPrivate:it([99,162]),VideoTrack:it([224]),AudioTrack:it([225]),Cluster:it([31,67,182,117]),Timestamp:it([231]),TimestampScale:it([42,215,177]),BlockGroup:it([160]),BlockDuration:it([155]),Block:it([161]),SimpleBlock:it([163])},ov=[128,64,32,16,8,4,2,1],TM=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=xp(t,i,!1);if(gi(e.bytes,n.bytes))return i;var r=xp(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},mE=function s(e,t){t=_M(t),e=it(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+o.value,d=e.subarray(u,c);gi(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+o.length+d.length;n+=f}return i},SM=it([0,0,0,1]),xM=it([0,0,1]),EM=it([0,0,3]),AM=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(o=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},CM=function(e,t,i){return RA(e,"h264",t,i)},DM=function(e,t,i){return RA(e,"h265",t,i)},Ls={webm:it([119,101,98,109]),matroska:it([109,97,116,114,111,115,107,97]),flac:it([102,76,97,67]),ogg:it([79,103,103,83]),ac3:it([11,119]),riff:it([82,73,70,70]),avi:it([65,86,73]),wav:it([87,65,86,69]),"3gp":it([102,116,121,112,51,103]),mp4:it([102,116,121,112]),fmp4:it([115,116,121,112]),mov:it([102,116,121,112,113,116]),moov:it([109,111,111,118]),moof:it([109,111,111,102])},Wu={aac:function(e){var t=xd(e);return gi(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=xd(e);return gi(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=mE(e,[Ff.EBML,Ff.DocType])[0];return gi(t,Ls.webm)},mkv:function(e){var t=mE(e,[Ff.EBML,Ff.DocType])[0];return gi(t,Ls.matroska)},mp4:function(e){if(Wu["3gp"](e)||Wu.mov(e))return!1;if(gi(e,Ls.mp4,{offset:4})||gi(e,Ls.fmp4,{offset:4})||gi(e,Ls.moof,{offset:4})||gi(e,Ls.moov,{offset:4}))return!0},mov:function(e){return gi(e,Ls.mov,{offset:4})},"3gp":function(e){return gi(e,Ls["3gp"],{offset:4})},ac3:function(e){var t=xd(e);return gi(e,Ls.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},uy,yE;function IM(){if(yE)return uy;yE=1;var s=9e4,e,t,i,n,r,o,u;return e=function(c){return c*s},t=function(c,d){return c*d},i=function(c){return c/s},n=function(c,d){return c/d},r=function(c,d){return e(n(c,d))},o=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},uy={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:o,metadataTsToSeconds:u},uy}var fl=IM();var uv="8.23.4";const ha={},_o=function(s,e){return ha[s]=ha[s]||[],e&&(ha[s]=ha[s].concat(e)),ha[s]},RM=function(s,e){_o(s,e)},kA=function(s,e){const t=_o(s).indexOf(e);return t<=-1?!1:(ha[s]=ha[s].slice(),ha[s].splice(t,1),!0)},kM=function(s,e){_o(s,[].concat(e).map(t=>{const i=(...n)=>(kA(s,i),t(...n));return i}))},Ep={prefixed:!0},lp=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],vE=lp[0];let Ed;for(let s=0;s(i,n,r)=>{const o=e.levels[n],u=new RegExp(`^(${o})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),Ks){Ks.push([].concat(r));const f=Ks.length-1e3;Ks.splice(0,f>0?f:0)}if(!ne.console)return;let d=ne.console[i];!d&&i==="debug"&&(d=ne.console.info||ne.console.log),!(!d||!o||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](ne.console,r)};function cv(s,e=":",t=""){let i="info",n;function r(...o){n("log",i,o)}return n=OM(s,r,t),r.createLogger=(o,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,g=`${s} ${d} ${o}`;return cv(g,d,f)},r.createNewLogger=(o,u,c)=>cv(o,u,c),r.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:i},r.level=o=>{if(typeof o=="string"){if(!r.levels.hasOwnProperty(o))throw new Error(`"${o}" in not a valid log level`);i=o}return i},r.history=()=>Ks?[].concat(Ks):[],r.history.filter=o=>(Ks||[]).filter(u=>new RegExp(`.*${o}.*`).test(u[0])),r.history.clear=()=>{Ks&&(Ks.length=0)},r.history.disable=()=>{Ks!==null&&(Ks.length=0,Ks=null)},r.history.enable=()=>{Ks===null&&(Ks=[])},r.error=(...o)=>n("error",i,o),r.warn=(...o)=>n("warn",i,o),r.debug=(...o)=>n("debug",i,o),r}const yt=cv("VIDEOJS"),OA=yt.createLogger,PM=Object.prototype.toString,PA=function(s){return kr(s)?Object.keys(s):[]};function Ou(s,e){PA(s).forEach(t=>e(s[t],t))}function MA(s,e,t=0){return PA(s).reduce((i,n)=>e(i,s[n],n),t)}function kr(s){return!!s&&typeof s=="object"}function Xu(s){return kr(s)&&PM.call(s)==="[object Object]"&&s.constructor===Object}function Qt(...s){const e={};return s.forEach(t=>{t&&Ou(t,(i,n)=>{if(!Xu(i)){e[n]=i;return}Xu(e[n])||(e[n]={}),e[n]=Qt(e[n],i)})}),e}function NA(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function yg(s,e,t,i=!0){const n=o=>Object.defineProperty(s,e,{value:o,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const o=t();return n(o),o}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var MM=Object.freeze({__proto__:null,each:Ou,reduce:MA,isObject:kr,isPlain:Xu,merge:Qt,values:NA,defineLazyProperty:yg});let dT=!1,BA=null,Jn=!1,FA,UA=!1,Pu=!1,Mu=!1,Or=!1,hT=null,vg=null;const NM=!!(ne.cast&&ne.cast.framework&&ne.cast.framework.CastReceiverContext);let $A=null,Ap=!1,Tg=!1,Cp=!1,_g=!1,Dp=!1,wp=!1,Lp=!1;const $d=!!(nc()&&("ontouchstart"in ne||ne.navigator.maxTouchPoints||ne.DocumentTouch&&ne.document instanceof ne.DocumentTouch)),so=ne.navigator&&ne.navigator.userAgentData;so&&so.platform&&so.brands&&(Jn=so.platform==="Android",Pu=!!so.brands.find(s=>s.brand==="Microsoft Edge"),Mu=!!so.brands.find(s=>s.brand==="Chromium"),Or=!Pu&&Mu,hT=vg=(so.brands.find(s=>s.brand==="Chromium")||{}).version||null,Tg=so.platform==="Windows");if(!Mu){const s=ne.navigator&&ne.navigator.userAgent||"";dT=/iPod/i.test(s),BA=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),Jn=/Android/i.test(s),FA=(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})(),UA=/Firefox/i.test(s),Pu=/Edg/i.test(s),Mu=/Chrome/i.test(s)||/CriOS/i.test(s),Or=!Pu&&Mu,hT=vg=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),$A=(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),wp=/Web0S/i.test(s),Lp=Dp||wp,Ap=/Safari/i.test(s)&&!Or&&!Jn&&!Pu&&!Lp,Tg=/Windows/i.test(s),Cp=/iPad/i.test(s)||Ap&&$d&&!/iPhone/i.test(s),_g=/iPhone/i.test(s)&&!Cp}const _s=_g||Cp||dT,bg=(Ap||_s)&&!Or;var jA=Object.freeze({__proto__:null,get IS_IPOD(){return dT},get IOS_VERSION(){return BA},get IS_ANDROID(){return Jn},get ANDROID_VERSION(){return FA},get IS_FIREFOX(){return UA},get IS_EDGE(){return Pu},get IS_CHROMIUM(){return Mu},get IS_CHROME(){return Or},get CHROMIUM_VERSION(){return hT},get CHROME_VERSION(){return vg},IS_CHROMECAST_RECEIVER:NM,get IE_VERSION(){return $A},get IS_SAFARI(){return Ap},get IS_WINDOWS(){return Tg},get IS_IPAD(){return Cp},get IS_IPHONE(){return _g},get IS_TIZEN(){return Dp},get IS_WEBOS(){return wp},get IS_SMART_TV(){return Lp},TOUCH_ENABLED:$d,IS_IOS:_s,IS_ANY_SAFARI:bg});function TE(s){return typeof s=="string"&&!!s.trim()}function BM(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function nc(){return Ne===ne.document}function rc(s){return kr(s)&&s.nodeType===1}function HA(){try{return ne.parent!==ne.self}catch{return!0}}function GA(s){return function(e,t){if(!TE(e))return Ne[s](null);TE(t)&&(t=Ne.querySelector(t));const i=rc(t)?t:Ne;return i[s]&&i[s](e)}}function nt(s="div",e={},t={},i){const n=Ne.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const o=e[r];r==="textContent"?Eo(n,o):(n[r]!==o||r==="tabIndex")&&(n[r]=o)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&fT(n,i),n}function Eo(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function dv(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function Rd(s,e){return BM(e),s.classList.contains(e)}function ml(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function Sg(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(yt.warn("removeClass was called with an element that doesn't exist"),null)}function VA(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 qA(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 co(s){const e={},t=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(s&&s.attributes&&s.attributes.length>0){const i=s.attributes;for(let n=i.length-1;n>=0;n--){const r=i[n].name;let o=i[n].value;t.includes(r)&&(o=o!==null),e[r]=o}}return e}function zA(s,e){return s.getAttribute(e)}function Qu(s,e,t){s.setAttribute(e,t)}function xg(s,e){s.removeAttribute(e)}function KA(){Ne.body.focus(),Ne.onselectstart=function(){return!1}}function YA(){Ne.onselectstart=function(){return!0}}function Zu(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(Ju(s,"height"))),t.width||(t.width=parseFloat(Ju(s,"width"))),t}}function jd(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!==Ne[Ep.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function Eg(s,e){const t={x:0,y:0};if(_s){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const g=Ju(f,"transform");if(/^matrix/.test(g)){const m=g.slice(7,-1).split(/,\s/).map(Number);t.x+=m[4],t.y+=m[5]}else if(/^matrix3d/.test(g)){const m=g.slice(9,-1).split(/,\s/).map(Number);t.x+=m[12],t.y+=m[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&ne.WebKitCSSMatrix){const m=ne.getComputedStyle(f.assignedSlot.parentElement).transform,v=new ne.WebKitCSSMatrix(m);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=jd(e.target),r=jd(s),o=r.width,u=r.height;let c=e.offsetY-(r.top-n.top),d=e.offsetX-(r.left-n.left);return e.changedTouches&&(d=e.changedTouches[0].pageX-r.left,c=e.changedTouches[0].pageY+r.top,_s&&(d-=t.x,c-=t.y)),i.y=1-Math.max(0,Math.min(1,c/u)),i.x=Math.max(0,Math.min(1,d/o)),i}function WA(s){return kr(s)&&s.nodeType===3}function Ag(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function XA(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),rc(e)||WA(e))return e;if(typeof e=="string"&&/\S/.test(e))return Ne.createTextNode(e)}).filter(e=>e)}function fT(s,e){return XA(e).forEach(t=>s.appendChild(t)),s}function QA(s,e){return fT(Ag(s),e)}function Hd(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 bo=GA("querySelector"),ZA=GA("querySelectorAll");function Ju(s,e){if(!s||!e)return"";if(typeof ne.getComputedStyle=="function"){let t;try{t=ne.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function JA(s){[...Ne.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=Ne.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=Ne.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:nc,isEl:rc,isInFrame:HA,createEl:nt,textContent:Eo,prependTo:dv,hasClass:Rd,addClass:ml,removeClass:Sg,toggleClass:VA,setAttributes:qA,getAttributes:co,getAttribute:zA,setAttribute:Qu,removeAttribute:xg,blockTextSelection:KA,unblockTextSelection:YA,getBoundingClientRect:Zu,findPosition:jd,getPointerPosition:Eg,isTextNode:WA,emptyEl:Ag,normalizeContent:XA,appendContent:fT,insertContent:QA,isSingleLeftClick:Hd,$:bo,$$:ZA,computedStyle:Ju,copyStyleSheetsToWindow:JA});let tC=!1,hv;const FM=function(){if(hv.options.autoSetup===!1)return;const s=Array.prototype.slice.call(Ne.getElementsByTagName("video")),e=Array.prototype.slice.call(Ne.getElementsByTagName("audio")),t=Array.prototype.slice.call(Ne.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 bs(s,e,t){if(!Rs.has(s))return;const i=Rs.get(s);if(!i.handlers)return;if(Array.isArray(e))return pT(bs,s,e,t);const n=function(o,u){i.handlers[u]=[],_E(o,u)};if(e===void 0){for(const o in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},o)&&n(s,o);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let o=0;o=e&&(s(...n),t=r)}},nC=function(s,e,t,i=ne){let n;const r=()=>{i.clearTimeout(n),n=null},o=function(){const u=this,c=arguments;let d=function(){n=null,d=null,t||s.apply(u,c)};!n&&t&&s.apply(u,c),i.clearTimeout(n),n=i.setTimeout(d,e)};return o.cancel=r,o};var VM=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:On,bind_:di,throttle:Pr,debounce:nC});let gd;class vn{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},yn(this,e,t),this.addEventListener=i}off(e,t){bs(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Dg(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},gT(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=Cg(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),ac(this,e)}queueTrigger(e){gd||(gd=new Map);const t=e.type||e;let i=gd.get(this);i||(i=new Map,gd.set(this,i));const n=i.get(t);i.delete(t),ne.clearTimeout(n);const r=ne.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,gd.delete(this)),this.trigger(e)},0);i.set(t,r)}}vn.prototype.allowedEvents_={};vn.prototype.addEventListener=vn.prototype.on;vn.prototype.removeEventListener=vn.prototype.off;vn.prototype.dispatchEvent=vn.prototype.trigger;const wg=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,ga=s=>s instanceof vn||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),qM=(s,e)=>{ga(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},gv=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,Ip=(s,e,t)=>{if(!s||!s.nodeName&&!ga(s))throw new Error(`Invalid target for ${wg(e)}#${t}; must be a DOM node or evented object.`)},rC=(s,e,t)=>{if(!gv(s))throw new Error(`Invalid event type for ${wg(e)}#${t}; must be a non-empty string or array.`)},aC=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${wg(e)}#${t}; must be a function.`)},cy=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,o;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,o]=e):(n=e[0],r=e[1],o=e[2]),Ip(n,s,t),rC(r,s,t),aC(o,s,t),o=di(s,o),{isTargetingSelf:i,target:n,type:r,listener:o}},nl=(s,e,t,i)=>{Ip(s,s,e),s.nodeName?GM[e](s,t,i):s[e](t,i)},zM={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=cy(this,s,"on");if(nl(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const o=()=>this.off("dispose",r);o.guid=n.guid,nl(this,"on","dispose",r),nl(t,"on","dispose",o)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=cy(this,s,"one");if(e)nl(t,"one",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,nl(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=cy(this,s,"any");if(e)nl(t,"any",i,n);else{const r=(...o)=>{this.off(t,i,r),n.apply(null,o)};r.guid=n.guid,nl(t,"any",i,r)}},off(s,e,t){if(!s||gv(s))bs(this.eventBusEl_,s,e);else{const i=s,n=e;Ip(i,this,"off"),rC(n,this,"off"),aC(t,this,"off"),t=di(this,t),this.off("dispose",t),i.nodeName?(bs(i,n,t),bs(i,"dispose",t)):ga(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){Ip(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!gv(t))throw new Error(`Invalid event type for ${wg(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return ac(this.eventBusEl_,s,e)}};function mT(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_=nt("span",{className:"vjs-event-bus"});return Object.assign(s,zM),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&Rs.has(i)&&Rs.delete(i)}),ne.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const KM={state:{},setState(s){typeof s=="function"&&(s=s());let e;return Ou(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&ga(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function oC(s,e){return Object.assign(s,KM),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&ga(s)&&s.on("statechanged",s.handleStateChanged),s}const kd=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},wi=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},lC=function(s,e){return wi(s)===wi(e)};var YM=Object.freeze({__proto__:null,toLowerCase:kd,toTitleCase:wi,titleCaseEquals:lC});class De{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=Qt({},this.options_),t=this.options_=Qt(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_${kn()}`}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&&(mT(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),oC(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_=Qt(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return nt(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),o=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return o&&o[e]?d=o[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,g){const m=t[g-1];let v=m;return typeof m>"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_[wi(e.name())]=null,this.childNameIndex_[kd(e.name())]=null;const i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){const e=this.options_.children;if(e){const t=this.options_,i=o=>{const u=o.name;let c=o.opts;if(t[u]!==void 0&&(c=t[u]),c===!1)return;c===!0&&(c={}),c.playerOptions=this.options_.playerOptions;const d=this.addChild(u,c);d&&(this[u]=d)};let n;const r=De.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(o){return!n.some(function(u){return typeof u=="string"?o===u:o===u.name})})).map(o=>{let u,c;return typeof o=="string"?(u=o,c=e[u]||this.options_[u]||{}):(u=o.name,c=o),{name:u,opts:c}}).filter(o=>{const u=De.getComponent(o.opts.componentClass||wi(o.name));return u&&!r.isTech(u)}).forEach(i)}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){const e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(t){t.call(this)},this),this.trigger("ready")},1)}$(e,t){return bo(e,t||this.contentEl())}$$(e,t){return ZA(e,t||this.contentEl())}hasClass(e){return Rd(this.el_,e)}addClass(...e){ml(this.el_,...e)}removeClass(...e){Sg(this.el_,...e)}toggleClass(e,t){VA(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 zA(this.el_,e)}setAttribute(e,t){Qu(this.el_,e,t)}removeAttribute(e){xg(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"+wi(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Ju(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${wi(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=ne.performance.now(),r=!0)}),this.on("touchmove",function(u){if(u.touches.length>1)r=!1;else if(t){const c=u.touches[0].pageX-t.pageX,d=u.touches[0].pageY-t.pageY;Math.sqrt(c*c+d*d)>i&&(r=!1)}});const o=function(){r=!1};this.on("touchleave",o),this.on("touchcancel",o),this.on("touchend",function(u){t=null,r===!0&&ne.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),ne.clearTimeout(e)),e}setInterval(e,t){e=di(this,e),this.clearTimersOnDispose_();const i=ne.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),ne.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=di(this,e),t=ne.requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=di(this,t);const i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),ne.cancelAnimationFrame(e)),e}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((i,n)=>this[t](n))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){function t(r){const o=ne.getComputedStyle(r,null),u=o.getPropertyValue("visibility");return o.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||ne.getComputedStyle(r).height==="0px"||ne.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const o={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(o.x<0||o.x>(Ne.documentElement.clientWidth||ne.innerWidth)||o.y<0||o.y>(Ne.documentElement.clientHeight||ne.innerHeight))return!1;let u=Ne.elementFromPoint(o.x,o.y);for(;u;){if(u===r)return!0;if(u.parentNode)u=u.parentNode;else return!1}}return e||(e=this.el()),!!(n(e)&&i(e)&&(!e.parentElement||e.tabIndex>=0))}static registerComponent(e,t){if(typeof e!="string"||!e)throw new Error(`Illegal component name, "${e}"; must be a non-empty string.`);const i=De.getComponent("Tech"),n=i&&i.isTech(t),r=De===t||De.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=wi(e),De.components_||(De.components_={});const o=De.getComponent("Player");if(e==="Player"&&o&&o.players){const u=o.players,c=Object.keys(u);if(u&&c.length>0){for(let d=0;dt)throw new Error(`Failed to execute '${s}' on 'TimeRanges': The index provided (${e}) is non-numeric or out of bounds (0-${t}).`)}function bE(s,e,t,i){return WM(s,i,t.length-1),t[i][e]}function dy(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:bE.bind(null,"start",0,s),end:bE.bind(null,"end",1,s)},ne.Symbol&&ne.Symbol.iterator&&(e[ne.Symbol.iterator]=()=>(s||[]).values()),e}function Zn(s,e){return Array.isArray(s)?dy(s):s===void 0||e===void 0?dy():dy([[s,e]])}const uC=function(s,e){s=s<0?0:s;let t=Math.floor(s%60),i=Math.floor(s/60%60),n=Math.floor(s/3600);const r=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||o>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let yT=uC;function cC(s){yT=s}function dC(){yT=uC}function Sl(s,e=s){return yT(s,e)}var XM=Object.freeze({__proto__:null,createTimeRanges:Zn,createTimeRange:Zn,setFormatTime:cC,resetFormatTime:dC,formatTime:Sl});function hC(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=Zn(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function Si(s){if(s instanceof Si)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:kr(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=Si.defaultMessages[this.code]||"")}Si.prototype.code=0;Si.prototype.message="";Si.prototype.status=null;Si.prototype.metadata=null;Si.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];Si.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."};Si.MEDIA_ERR_CUSTOM=0;Si.prototype.MEDIA_ERR_CUSTOM=0;Si.MEDIA_ERR_ABORTED=1;Si.prototype.MEDIA_ERR_ABORTED=1;Si.MEDIA_ERR_NETWORK=2;Si.prototype.MEDIA_ERR_NETWORK=2;Si.MEDIA_ERR_DECODE=3;Si.prototype.MEDIA_ERR_DECODE=3;Si.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Si.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;Si.MEDIA_ERR_ENCRYPTED=5;Si.prototype.MEDIA_ERR_ENCRYPTED=5;function Od(s){return s!=null&&typeof s.then=="function"}function Ar(s){Od(s)&&s.then(null,e=>{})}const mv=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}})})},QM=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=mv(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(mv))},ZM=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 yv={textTracksToJson:QM,jsonToTextTracks:ZM,trackToJson:mv};const hy="vjs-modal-dialog";class oc extends De{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_=nt("div",{className:`${hy}-content`},{role:"document"}),this.descEl_=nt("p",{className:`${hy}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),Eo(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`${hy} 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(),QA(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"),Ag(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=Ne.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 ne.HTMLAnchorElement||t instanceof ne.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof ne.HTMLInputElement||t instanceof ne.HTMLSelectElement||t instanceof ne.HTMLTextAreaElement||t instanceof ne.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof ne.HTMLIFrameElement||t instanceof ne.HTMLObjectElement||t instanceof ne.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}oc.prototype.options_={pauseOnOpen:!0,temporary:!0};De.registerComponent("ModalDialog",oc);class xl extends vn{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})},ga(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){fy(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&fy(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,fy(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 py=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){py(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,py(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 vT extends xl{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 JM{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(ne.console&&ne.console.groupCollapsed&&ne.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>yt.error(n)),ne.console&&ne.console.groupEnd&&ne.console.groupEnd()),t.flush()},EE=function(s,e){const t={uri:s},i=Lg(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),yA(t,di(this,function(r,o,u){if(r)return yt.error(r,o);e.loaded_=!0,typeof ne.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){yt.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return xE(u,e)}):xE(u,e)}))};class th extends TT{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=Qt(e,{kind:iN[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=SE[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 Rp(this.cues_),o=new Rp(this.activeCues_);let u=!1;this.timeupdateHandler=di(this,function(d={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,u&&(this.trigger("cuechange"),u=!1),d.type!=="timeupdate"&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}});const c=()=>{this.stopTracking()};this.tech_.one("dispose",c),i!=="disabled"&&this.startTracking(),Object.defineProperties(this,{default:{get(){return n},set(){}},mode:{get(){return i},set(d){SE[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&EE(this.src,this),this.stopTracking(),i!=="disabled"&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(this.cues.length===0)return o;const d=this.tech_.currentTime(),f=[];for(let g=0,m=this.cues.length;g=d&&f.push(v)}if(u=!1,f.length!==this.activeCues_.length)u=!0;else for(let g=0;g{t=ya.LOADED,this.trigger({type:"load",target:this})})}}ya.prototype.allowedEvents_={load:"load"};ya.NONE=0;ya.LOADING=1;ya.LOADED=2;ya.ERROR=3;const Rn={audio:{ListClass:fC,TrackClass:mC,capitalName:"Audio"},video:{ListClass:pC,TrackClass:yC,capitalName:"Video"},text:{ListClass:vT,TrackClass:th,capitalName:"Text"}};Object.keys(Rn).forEach(function(s){Rn[s].getterName=`${s}Tracks`,Rn[s].privateName=`${s}Tracks_`});const ec={remoteText:{ListClass:vT,TrackClass:th,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:JM,TrackClass:ya,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Is=Object.assign({},Rn,ec);ec.names=Object.keys(ec);Rn.names=Object.keys(Rn);Is.names=[].concat(ec.names).concat(Rn.names);function nN(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const o=new Is.text.TrackClass(n);return r.addTrack(o),o}class dt extends De{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}),Is.names.forEach(i=>{const n=Is[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 Is.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(di(this,function(){const t=this.bufferedPercent();this.bufferedPercent_!==t&&this.trigger("progress"),this.bufferedPercent_=t,t===1&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return Zn(0,0)}bufferedPercent(){return hC(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(Rn.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 Si(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?Zn(0,0):Zn()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){Rn.names.forEach(e=>{const t=Rn[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(!ne.WebVTT)if(Ne.body.contains(this.el())){if(!this.options_["vtt.js"]&&Xu(Yx)&&Object.keys(Yx).length>0){this.trigger("vttjsloaded");return}const e=Ne.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}),ne.WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const e=this.textTracks(),t=this.remoteTextTracks(),i=u=>e.addTrack(u.track),n=u=>e.removeTrack(u.track);t.on("addtrack",i),t.on("removetrack",n),this.addWebVttScript_();const r=()=>this.trigger("texttrackchange"),o=()=>{r();for(let u=0;uthis.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){const t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){const t=kn();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 dt.canPlayType(e.type)}static isTech(e){return e.prototype instanceof dt||e instanceof dt||e===dt}static registerTech(e,t){if(dt.techs_||(dt.techs_={}),!dt.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!dt.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!dt.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=wi(e),dt.techs_[e]=t,dt.techs_[kd(e)]=t,e!=="Tech"&&dt.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(dt.techs_&&dt.techs_[e])return dt.techs_[e];if(e=wi(e),ne&&ne.videojs&&ne.videojs[e])return yt.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),ne.videojs[e]}}}Is.names.forEach(function(s){const e=Is[s];dt.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});dt.prototype.featuresVolumeControl=!0;dt.prototype.featuresMuteControl=!0;dt.prototype.featuresFullscreenResize=!1;dt.prototype.featuresPlaybackRate=!1;dt.prototype.featuresProgressEvents=!1;dt.prototype.featuresSourceset=!1;dt.prototype.featuresTimeupdateEvents=!1;dt.prototype.featuresNativeTextTracks=!1;dt.prototype.featuresVideoFrameCallback=!1;dt.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;rll(e,yl[e.type],t,s),1)}function oN(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function lN(s,e,t){return s.reduceRight(ST(t),e[t]())}function uN(s,e,t,i){return e[t](s.reduce(ST(t),i))}function AE(s,e,t,i=null){const n="call"+wi(t),r=s.reduce(ST(n),i),o=r===Op,u=o?null:e[t](r);return hN(s,t,u,o),u}const cN={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},dN={setCurrentTime:1,setMuted:1,setVolume:1},CE={play:1,pause:1};function ST(s){return(e,t)=>e===Op?Op:t[s]?t[s](e):e}function hN(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function fN(s){kp.hasOwnProperty(s.id())&&delete kp[s.id()]}function pN(s,e){const t=kp[s.id()];let i=null;if(t==null)return i=e(s),kp[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 wE=Dp?10009:wp?461:8,Tu={codes:{play:415,pause:19,ff:417,rw:412,back:wE},names:{415:"play",19:"pause",417:"ff",412:"rw",[wE]:"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}},LE=5;class vN extends vn{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(Tu.isEventKey(t,"play")||Tu.isEventKey(t,"pause")||Tu.isEventKey(t,"ff")||Tu.isEventKey(t,"rw")){t.preventDefault();const i=Tu.getEventName(t);this.performMediaAction_(i)}else Tu.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()+LE);break;case"rw":this.userSeek_(this.player_.currentTime()-LE);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},g={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:g}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:d=>!0,focus:()=>u.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let n=0;n0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){const t=this.getCurrentComponent();if(!t)return;const i=t.getPositions(),n=this.focusableComponents.filter(o=>o!==t&&this.isInDirection_(i.boundingClientRect,o.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,n,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let n=1/0,r=null;for(const o of t){const u=o.getPositions().center,c=this.calculateDistance_(e,u,i);c=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(i),this.handleMouseOut_=i=>this.handleMouseOut(i),this.handleClick_=i=>this.handleClick(i),this.handleKeyDown_=i=>this.handleKeyDown(i),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),e==="button"&&yt.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=nt(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(nt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=nt("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,Eo(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)}}De.registerComponent("ClickableComponent",Ig);class vv extends Ig{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 nt("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(nt("picture",{className:"vjs-poster",tabIndex:-1},{},nt("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()?Ar(this.player_.play()):this.player_.pause())}}vv.prototype.crossorigin=vv.prototype.crossOrigin;De.registerComponent("PosterImage",vv);const Ln="#222",IE="#ccc",_N={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 gy(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 yr(s,e,t){try{s.style[e]=t}catch{return}}function RE(s){return s?`${s}px`:""}class bN extends De{constructor(e,t,i){super(e,t,i);const n=o=>this.updateDisplay(o),r=o=>{this.updateDisplayOverlay(),this.updateDisplay(o)};e.on("loadstart",o=>this.toggleDisplay(o)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",o=>{this.updateDisplayOverlay(),this.preselectTrack(o)}),e.ready(di(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const o=ne.screen.orientation||ne,u=ne.screen.orientation?"change":"orientationchange";o.addEventListener(u,r),e.on("dispose",()=>o.removeEventListener(u,r));const c=this.options_.playerOptions.tracks||[];for(let d=0;d0&&u.forEach(f=>{if(f.style.inset){const g=f.style.inset.split(" ");g.length===3&&Object.assign(f.style,{top:g[0],right:g[1],bottom:g[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!ne.CSS.supports("inset-inline: 10px"))return;const e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,n=this.player_.videoWidth()/this.player_.videoHeight();let r=0,o=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):o=Math.round((t-e/n)/2)),yr(this.el_,"insetInline",RE(r)),yr(this.el_,"insetBlock",RE(o))}updateDisplayState(e){const t=this.player_.textTrackSettings.getValues(),i=e.activeCues;let n=i.length;for(;n--;){const r=i[n];if(!r)continue;const o=r.displayState;if(t.color&&(o.firstChild.style.color=t.color),t.textOpacity&&yr(o.firstChild,"color",gy(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(o.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&yr(o.firstChild,"backgroundColor",gy(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?yr(o,"backgroundColor",gy(t.windowColor,t.windowOpacity)):o.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?o.firstChild.style.textShadow=`2px 2px 3px ${Ln}, 2px 2px 4px ${Ln}, 2px 2px 5px ${Ln}`:t.edgeStyle==="raised"?o.firstChild.style.textShadow=`1px 1px ${Ln}, 2px 2px ${Ln}, 3px 3px ${Ln}`:t.edgeStyle==="depressed"?o.firstChild.style.textShadow=`1px 1px ${IE}, 0 1px ${IE}, -1px -1px ${Ln}, 0 -1px ${Ln}`:t.edgeStyle==="uniform"&&(o.firstChild.style.textShadow=`0 0 4px ${Ln}, 0 0 4px ${Ln}, 0 0 4px ${Ln}, 0 0 4px ${Ln}`)),t.fontPercent&&t.fontPercent!==1){const u=ne.parseFloat(o.style.fontSize);o.style.fontSize=u*t.fontPercent+"px",o.style.height="auto",o.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?o.firstChild.style.fontVariant="small-caps":o.firstChild.style.fontFamily=_N[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof ne.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){Ar(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();Od(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}TC.prototype.controlText_="Play Video";De.registerComponent("BigPlayButton",TC);class xN extends Ss{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)}}De.registerComponent("CloseButton",xN);class _C extends Ss{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()?Ar(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))}}_C.prototype.controlText_="Play";De.registerComponent("PlayToggle",_C);class lc extends De{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=nt("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=nt("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=Sl(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,yt.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_=Ne.createTextNode(this.formattedTime_),this.textNode_&&(t?this.contentEl_.replaceChild(this.textNode_,t):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}lc.prototype.labelText_="Time";lc.prototype.controlText_="Time";De.registerComponent("TimeDisplay",lc);class xT extends lc{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)}}xT.prototype.labelText_="Current Time";xT.prototype.controlText_="Current Time";De.registerComponent("CurrentTimeDisplay",xT);class ET extends lc{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)}}ET.prototype.labelText_="Duration";ET.prototype.controlText_="Duration";De.registerComponent("DurationDisplay",ET);class EN extends De{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}}De.registerComponent("TimeDivider",EN);class AT extends lc{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(nt("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)}}AT.prototype.labelText_="Remaining Time";AT.prototype.controlText_="Remaining Time";De.registerComponent("RemainingTimeDisplay",AT);class AN extends De{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_=nt("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(nt("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(Ne.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()}}De.registerComponent("LiveDisplay",AN);class bC extends Ss{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_=nt("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}bC.prototype.controlText_="Seek to live, currently playing live";De.registerComponent("SeekToLive",bC);function ih(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var CN=Object.freeze({__proto__:null,clamp:ih});class CT extends De{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"&&!Or&&e.preventDefault(),KA(),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;YA(),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(ih(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=Eg(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")}}De.registerComponent("Slider",CT);const my=(s,e)=>ih(s/e*100,0,100).toFixed(2)+"%";class DN extends De{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=nt("span",{className:"vjs-control-text"}),i=nt("span",{textContent:this.localize("Loaded")}),n=Ne.createTextNode(": ");return this.percentageEl_=nt("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(n),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{const t=this.player_.liveTracker,i=this.player_.buffered(),n=t&&t.isLive()?t.seekableEnd():this.player_.duration(),r=this.player_.bufferedEnd(),o=this.partEls_,u=my(r,n);this.percent_!==u&&(this.el_.style.width=u,Eo(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(o[c-1]);o.length=i.length})}}De.registerComponent("LoadProgressBar",DN);class wN extends De{constructor(e,t){super(e,t),this.update=Pr(di(this,this.update),On)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=jd(this.el_),r=Zu(this.player_.el()),o=e.width*t;if(!r||!n)return;let u=e.left-r.left+o,c=e.width-o+(r.right-e.right);c||(c=e.width-o,u=o);let d=n.width/2;un.width&&(d=n.width),d=Math.round(d),this.el_.style.right=`-${d}px`,this.write(i)}write(e){Eo(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const o=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+Sl(c,u)}else r=Sl(i,o);this.update(e,t,r),n&&n()})}}De.registerComponent("TimeTooltip",wN);class DT extends De{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=Pr(di(this,this.update),On)}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)}}DT.prototype.options_={children:[]};!_s&&!Jn&&DT.prototype.options_.children.push("timeTooltip");De.registerComponent("PlayProgressBar",DT);class SC extends De{constructor(e,t){super(e,t),this.update=Pr(di(this,this.update),On)}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`})}}SC.prototype.options_={children:["timeTooltip"]};De.registerComponent("MouseTimeDisplay",SC);class Rg extends CT{constructor(e,t){t=Qt(Rg.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(_s||Jn)||e.options_.disableSeekWhileScrubbingOnSTV;(!_s&&!Jn||i)&&t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbing_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=di(this,this.update),this.update=Pr(this.update_,On),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 Ne&&"visibilityState"in Ne&&this.on(Ne,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){Ne.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,On))}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(Ne.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}",[Sl(i,r),Sl(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(Zu(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){Hd(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Hd(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const n=this.calculateDistance(e),r=this.player_.liveTracker;if(!r||!r.isLive())i=n*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(n>=.99){r.seekToLiveEdge();return}const o=r.seekableStart(),u=r.liveCurrentTime();if(i=o+n*r.liveWindow(),i>=u&&(i=u),i<=o&&(i=o+.1),i===1/0)return}this.shouldDisableSeekWhileScrubbing_?this.pendingSeekTime(i):this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime()!==null&&(this.userSeek_(this.pendingSeekTime()),this.pendingSeekTime(null)),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?Ar(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 Ne&&"visibilityState"in Ne&&this.off(Ne,"visibilitychange",this.toggleVisibility_),super.dispose()}}Rg.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};De.registerComponent("SeekBar",Rg);class xC extends De{constructor(e,t){super(e,t),this.handleMouseMove=Pr(di(this,this.handleMouseMove),On),this.throttledHandleMouseSeek=Pr(di(this,this.handleMouseSeek),On),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),n=t.getChild("mouseTimeDisplay");if(!i&&!n)return;const r=t.el(),o=jd(r);let u=Eg(r,e).x;u=ih(u,0,1),n&&n.update(o,u),i&&i.update(o,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&Ar(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()}}xC.prototype.options_={children:["seekBar"]};De.registerComponent("ProgressControl",xC);class EC extends Ss{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(){Ne.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in ne?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 Ne.exitPictureInPicture=="function"&&super.show()}}EC.prototype.controlText_="Picture-in-Picture";De.registerComponent("PictureInPictureToggle",EC);class AC extends Ss{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),Ne[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()}}AC.prototype.controlText_="Fullscreen";De.registerComponent("FullscreenToggle",AC);const LN=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 IN extends De{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}}De.registerComponent("VolumeLevel",IN);class RN extends De{constructor(e,t){super(e,t),this.update=Pr(di(this,this.update),On)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=Zu(this.el_),o=Zu(this.player_.el()),u=e.width*t;if(!o||!r)return;const c=e.left-o.left+u,d=e.width-u+(o.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){Eo(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}De.registerComponent("VolumeLevelTooltip",RN);class CC extends De{constructor(e,t){super(e,t),this.update=Pr(di(this,this.update),On)}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`})}}CC.prototype.options_={children:["volumeLevelTooltip"]};De.registerComponent("MouseVolumeLevelDisplay",CC);class kg extends CT{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){Hd(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=Zu(i),r=this.vertical();let o=Eg(i,e);o=r?o.y:o.x,o=ih(o,0,1),t.update(n,o,r)}Hd(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)})}}kg.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!_s&&!Jn&&kg.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");kg.prototype.playerEvent="volumechange";De.registerComponent("VolumeBar",kg);class DC extends De{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Xu(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),LN(this,e),this.throttledHandleMouseMove=Pr(di(this,this.handleMouseMove),On),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)}}DC.prototype.options_={children:["volumeBar"]};De.registerComponent("VolumeControl",DC);const kN=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 wC extends Ss{constructor(e,t){super(e,t),kN(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"),_s&&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),Sg(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),ml(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}wC.prototype.controlText_="Mute";De.registerComponent("MuteToggle",wC);class LC extends De{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Xu(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"),yn(Ne,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),bs(Ne,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}LC.prototype.options_={children:["muteToggle","volumeControl"]};De.registerComponent("VolumePanel",LC);class IC extends Ss{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]))}}IC.prototype.controlText_="Skip Forward";De.registerComponent("SkipForward",IC);class RC extends Ss{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]))}}RC.prototype.controlText_="Skip Backward";De.registerComponent("SkipBackward",RC);class kC extends De{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 De&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof De&&(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_=nt(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_),yn(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||Ne.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())}}De.registerComponent("Menu",kC);class wT extends De{constructor(e,t={}){super(e,t),this.menuButton_=new Ss(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=Ss.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(),yn(Ne,"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 kC(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=nt("li",{className:"vjs-menu-title",textContent:wi(this.options_.title),tabIndex:-1}),i=new De(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},o=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",o),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",o)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof ne.Event!="object")try{u=new ne.Event("change")}catch{}u||(u=Ne.createEvent("Event"),u.initEvent("change",!0,!0)),n.dispatchEvent(u)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let n=0;n-1&&o.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let n=0,r=t.length;n-1&&o.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}De.registerComponent("OffTextTrackMenuItem",OC);class uc extends LT{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=nh){let i;this.label_&&(i=`${this.label_} off`),e.push(new OC(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const n=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let r=0;r-1){const u=new t(this.player_,{track:o,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${o.kind}-menu-item`),e.push(u)}}return e}}De.registerComponent("TextTrackButton",uc);class PC extends sh{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(wi(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(wi(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 OT(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,MC),e}}MT.prototype.kinds_=["captions","subtitles"];MT.prototype.controlText_="Subtitles";De.registerComponent("SubsCapsButton",MT);class NC extends sh{constructor(e,t){const i=t.track,n=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const r=(...o)=>{this.handleTracksChange.apply(this,o)};n.addEventListener("change",r),this.on("dispose",()=>{n.removeEventListener("change",r)})}createEl(e,t,i){const n=super.createEl(e,t,i),r=n.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(r.appendChild(nt("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(nt("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)}}NT.prototype.contentElType="button";De.registerComponent("PlaybackRateMenuItem",NT);class FC extends wT{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_=nt("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 NT(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")}}FC.prototype.controlText_="Playback Rate";De.registerComponent("PlaybackRateMenuButton",FC);class UC extends De{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}De.registerComponent("Spacer",UC);class ON extends UC{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}De.registerComponent("CustomControlSpacer",ON);class $C extends De{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}$C.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};De.registerComponent("ControlBar",$C);class jC extends oc{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):""}}jC.prototype.options_=Object.assign({},oc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});De.registerComponent("ErrorDisplay",jC);class HC extends De{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(),nt("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${kn()}`)+"-"+t[1].replace(/\W+/g,""),n=nt("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}De.registerComponent("TextTrackSelect",HC);class vl extends De{constructor(e,t={}){super(e,t);const i=nt("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const n=this.options_.selects;for(const r of n){const o=this.options_.selectConfigs[r],u=o.className,c=o.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${kn()}`;if(this.options_.type==="colors"){d=nt("span",{className:u});const m=nt("label",{id:c,className:"vjs-label",textContent:this.localize(o.label)});m.setAttribute("for",f),d.appendChild(m)}const g=new HC(e,{SelectOptions:o.options,legendId:this.options_.legendId,id:f,labelId:c});this.addChild(g),this.options_.type==="colors"&&(d.appendChild(g.el()),this.el().appendChild(d))}}createEl(){return nt("fieldset",{className:this.options_.className})}}De.registerComponent("TextTrackFieldset",vl);class GC extends De{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new vl(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 vl(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const o=new vl(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(o)}createEl(){return nt("div",{className:"vjs-track-settings-colors"})}}De.registerComponent("TextTrackSettingsColors",GC);class VC extends De{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new vl(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 vl(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const o=new vl(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(o)}createEl(){return nt("div",{className:"vjs-track-settings-font"})}}De.registerComponent("TextTrackSettingsFont",VC);class qC extends De{constructor(e,t={}){super(e,t);const i=new Ss(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 Ss(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return nt("div",{className:"vjs-track-settings-controls"})}}De.registerComponent("TrackSettingsControls",qC);const yy="vjs-text-track-settings",kE=["#000","Black"],OE=["#00F","Blue"],PE=["#0FF","Cyan"],ME=["#0F0","Green"],NE=["#F0F","Magenta"],BE=["#F00","Red"],FE=["#FFF","White"],UE=["#FF0","Yellow"],vy=["1","Opaque"],Ty=["0.5","Semi-Transparent"],$E=["0","Transparent"],ho={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[kE,FE,BE,ME,OE,UE,NE,PE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[vy,Ty,$E],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[FE,kE,BE,ME,OE,UE,NE,PE],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:[vy,Ty],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:[$E,Ty,vy],className:"vjs-window-opacity vjs-opacity"}};ho.windowColor.options=ho.backgroundColor.options;function zC(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function PN(s,e){const t=s.options[s.options.selectedIndex].value;return zC(t,e)}function MN(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()}),Ou(ho,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 MA(ho,(e,t,i)=>{const n=PN(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){Ou(ho,(t,i)=>{MN(this.$(t.selector),e[i],t.parser)})}setDefaults(){Ou(ho,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(ne.localStorage.getItem(yy))}catch(t){yt.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?ne.localStorage.setItem(yy,JSON.stringify(e)):ne.localStorage.removeItem(yy)}catch(t){yt.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}De.registerComponent("TextTrackSettings",NN);class BN extends De{constructor(e,t){let i=t.ResizeObserver||ne.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=Qt({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||ne.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=nC(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const r=this.debouncedHandler_;let o=this.unloadListener_=function(){bs(this,"resize",r),bs(this,"unload",o),o=null};yn(this.el_.contentWindow,"unload",o),yn(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()}}De.registerComponent("ResizeManager",BN);const FN={trackingThreshold:20,liveTolerance:15};class UN extends De{constructor(e,t){const i=Qt(FN,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(ne.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const n=this.liveCurrentTime(),r=this.player_.currentTime();let o=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(o=!1),o!==this.behindLiveEdge_&&(this.behindLiveEdge_=o,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,On),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()}}De.registerComponent("LiveTracker",UN);class $N extends De{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:nt("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${kn()}`}),description:nt("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${kn()}`})},nt("div",{className:"vjs-title-bar"},{},NA(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(n=>{const r=this.state[n],o=this.els[n],u=i[n];Ag(o),r&&Eo(o,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,o.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}De.registerComponent("TitleBar",$N);const jN={initialDisplay:4e3,position:[],takeFocus:!1};class HN extends Ss{constructor(e,t){t=Qt(jN,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=nt("button",{},{type:"button",class:this.buildCSSClass()},nt("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()}}De.registerComponent("TransientButton",HN);const Tv=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;iKC([s.el(),ne.HTMLMediaElement.prototype,ne.Element.prototype,GN],"innerHTML"),jE=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=VN(s),n=r=>(...o)=>{const u=r.apply(e,o);return Tv(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",Qt(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_)},qN=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?gC(ne.Element.prototype.getAttribute.call(this,"src")):""},set(s){return ne.Element.prototype.setAttribute.call(this,"src",s),s}}),zN=s=>KC([s.el(),ne.HTMLMediaElement.prototype,qN],"src"),KN=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=zN(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",Qt(t,{set:r=>{const o=t.set.call(e,r);return s.triggerSourceset(e.src),o}})),e.setAttribute=(r,o)=>{const u=i.call(e,r,o);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return Tv(s)||(s.triggerSourceset(""),jE(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):Tv(s)||jE(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class Ve extends dt{constructor(e,t){super(e,t);const i=e.source;let n=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const r=this.el_.childNodes;let o=r.length;const u=[];for(;o--;){const c=r[o];c.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(c),this.remoteTextTracks().addTrack(c.track),this.textTracks().addTrack(c.track),!n&&!this.el_.hasAttribute("crossorigin")&&Lg(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=Rn[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[ec.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},o=function(){const u=[];for(let c=0;c{const c=r[u];i.addEventListener(u,c),this.on("dispose",d=>i.removeEventListener(u,c))}),this.on("loadstart",o),this.on("dispose",u=>this.off("loadstart",o))}proxyNativeTracks_(){Rn.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),Ve.disposeMediaElement(e),e=i}else{e=Ne.createElement("video");const i=this.options_.tag&&co(this.options_.tag),n=Qt({},i);(!$d||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,qA(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&Qu(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&&bg?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){yt(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Jn&&Or&&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)Ar(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 yt.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=nt("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return yt.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 yt.warn(`No matching source element found with src: ${e}`),!1}reset(){Ve.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=Ne.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),ne.performance&&(e.creationTime=ne.performance.now()),e}}yg(Ve,"TEST_VID",function(){if(!nc())return;const s=Ne.createElement("video"),e=Ne.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});Ve.isSupported=function(){try{Ve.TEST_VID.volume=.5}catch{return!1}return!!(Ve.TEST_VID&&Ve.TEST_VID.canPlayType)};Ve.canPlayType=function(s){return Ve.TEST_VID.canPlayType(s)};Ve.canPlaySource=function(s,e){return Ve.canPlayType(s.type)};Ve.canControlVolume=function(){try{const s=Ve.TEST_VID.volume;Ve.TEST_VID.volume=s/2+.1;const e=s!==Ve.TEST_VID.volume;return e&&_s?(ne.setTimeout(()=>{Ve&&Ve.prototype&&(Ve.prototype.featuresVolumeControl=s!==Ve.TEST_VID.volume)}),!1):e}catch{return!1}};Ve.canMuteVolume=function(){try{const s=Ve.TEST_VID.muted;return Ve.TEST_VID.muted=!s,Ve.TEST_VID.muted?Qu(Ve.TEST_VID,"muted","muted"):xg(Ve.TEST_VID,"muted","muted"),s!==Ve.TEST_VID.muted}catch{return!1}};Ve.canControlPlaybackRate=function(){if(Jn&&Or&&vg<58)return!1;try{const s=Ve.TEST_VID.playbackRate;return Ve.TEST_VID.playbackRate=s/2+.1,s!==Ve.TEST_VID.playbackRate}catch{return!1}};Ve.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(Ne.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(Ne.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(Ne.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(Ne.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};Ve.supportsNativeTextTracks=function(){return bg||_s&&Or};Ve.supportsNativeVideoTracks=function(){return!!(Ve.TEST_VID&&Ve.TEST_VID.videoTracks)};Ve.supportsNativeAudioTracks=function(){return!!(Ve.TEST_VID&&Ve.TEST_VID.audioTracks)};Ve.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]){yg(Ve.prototype,s,()=>Ve[e](),!0)});Ve.prototype.featuresVolumeControl=Ve.canControlVolume();Ve.prototype.movingMediaElementInDOM=!_s;Ve.prototype.featuresFullscreenResize=!0;Ve.prototype.featuresProgressEvents=!0;Ve.prototype.featuresTimeupdateEvents=!0;Ve.prototype.featuresVideoFrameCallback=!!(Ve.TEST_VID&&Ve.TEST_VID.requestVideoFrameCallback);Ve.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{}})()}};Ve.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){Ve.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){Ve.prototype["set"+wi(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){Ve.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){Ve.prototype["set"+wi(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){Ve.prototype[s]=function(){return this.el_[s]()}});dt.withSourceHandlers(Ve);Ve.nativeSourceHandler={};Ve.nativeSourceHandler.canPlayType=function(s){try{return Ve.TEST_VID.canPlayType(s)}catch{return""}};Ve.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return Ve.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=bT(s.src);return Ve.nativeSourceHandler.canPlayType(`video/${t}`)}return""};Ve.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};Ve.nativeSourceHandler.dispose=function(){};Ve.registerSourceHandler(Ve.nativeSourceHandler);dt.registerTech("Html5",Ve);const YC=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],_y={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},_v=["tiny","xsmall","small","medium","large","xlarge","huge"],up={};_v.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;up[s]=`vjs-layout-${e}`});const YN={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let yi=class Cu extends De{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${kn()}`,t=Object.assign(Cu.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const o=e.closest("[lang]");o&&(t.language=o.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=o=>this.documentFullscreenChange_(o),this.boundFullWindowOnEscKey_=o=>this.fullWindowOnEscKey(o),this.boundUpdateStyleEl_=o=>this.updateStyleEl_(o),this.boundApplyInitTime_=o=>this.applyInitTime_(o),this.boundUpdateCurrentBreakpoint_=o=>this.updateCurrentBreakpoint_(o),this.boundHandleTechClick_=o=>this.handleTechClick_(o),this.boundHandleTechDoubleClick_=o=>this.handleTechDoubleClick_(o),this.boundHandleTechTouchStart_=o=>this.handleTechTouchStart_(o),this.boundHandleTechTouchMove_=o=>this.handleTechTouchMove_(o),this.boundHandleTechTouchEnd_=o=>this.handleTechTouchEnd_(o),this.boundHandleTechTap_=o=>this.handleTechTap_(o),this.boundUpdatePlayerHeightOnAudioOnlyMode_=o=>this.updatePlayerHeightOnAudioOnlyMode_(o),this.isFullscreen_=!1,this.log=OA(this.id_),this.fsApi_=Ep,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&&co(e),this.language(this.options_.language),t.languages){const o={};Object.getOwnPropertyNames(t.languages).forEach(function(u){o[u.toLowerCase()]=t.languages[u]}),this.languages_=o}else this.languages_=Cu.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(o=>{if(typeof this[o]!="function")throw new Error(`plugin "${o}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),mT(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(yn(Ne,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=Qt(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(o=>{this[o](t.plugins[o])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new ne.DOMParser().parseFromString(yN,"image/svg+xml");if(u.querySelector("parsererror"))yt.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 vN(this),this.addClass("vjs-spatial-navigation-enabled")),$d&&this.addClass("vjs-touch-enabled"),_s||this.addClass("vjs-workinghover"),Cu.players[this.id_]=this;const r=uv.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",o=>this.listenForUserActivity_(o)),this.on("keydown",o=>this.handleKeyDown(o)),this.on("languagechange",o=>this.handleLanguagechange(o)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),bs(Ne,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),bs(Ne,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),Cu.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),fN(this),Is.names.forEach(e=>{const t=Is[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=co(e);if(n){for(t=this.el_=e,e=this.tag=Ne.createElement("video");t.children.length;)e.appendChild(t.firstChild);Rd(t,"video-js")||ml(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",Or&&Tg&&(e.setAttribute("role","application"),r.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(c){n&&c==="class"||t.setAttribute(c,r[c]),n&&e.setAttribute(c,r[c])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const o=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>jA[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...o),ne.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=iC("vjs-styles-dimensions");const c=bo(".vjs-styles-defaults"),d=bo("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"){yt.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)){yt.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,ga(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),qM(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(ne.VIDEOJS_NO_DYNAMIC_STYLE===!0){const u=typeof this.width_=="number"?this.width_:this.options_.width,c=typeof this.height_=="number"?this.height_:this.options_.height,d=this.tech_&&this.tech_.el();d&&(u>=0&&(d.width=u),c>=0&&(d.height=c));return}let e,t,i,n;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const r=i.split(":"),o=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/o:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*o,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),sC(this.styleEl_,` + .${n} { + width: ${e}px; + height: ${t}px; + } + + .${n}.vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: ${o*100}%; + } + `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=wi(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(dt.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(r=!1);const o={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${n}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};Is.names.forEach(c=>{const d=Is[c];o[d.getterName]=this[d.privateName]}),Object.assign(o,this.options_[i]),Object.assign(o,this.options_[n]),Object.assign(o,this.options_[e.toLowerCase()]),this.tag&&(o.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(o.startTime=this.cache_.currentTime);const u=dt.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(o),this.tech_.ready(di(this,this.handleTechReady_),!0),yv.jsonToTextTracks(this.textTracksJson_||[],this.tech_),YC.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${wi(c)}_`](d))}),Object.keys(_y).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${_y[c]}_`].bind(this),event:d});return}this[`handleTech${_y[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)&&dv(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Is.names.forEach(e=>{const t=Is[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=yv.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&&yt.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":uv}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const n=this.muted();this.muted(!0);const r=()=>{this.muted(n)};this.playTerminatedQueue_.push(r);const o=this.play();if(Od(o))return o.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),Od(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Od(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=mN(this,t)),this.cache_.source=Qt({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],o=this.$$("source"),u=[];for(let c=0;cthis.updateSourceCaches_(r);const i=this.currentSource().src,n=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(n)&&(!this.lastSource_||this.lastSource_.tech!==n&&this.lastSource_.player!==i)&&(t=()=>{}),t(n),e.src||this.tech_.any(["sourceset","loadstart"],r=>{if(r.type==="sourceset")return;const o=this.techGet_("currentSrc");this.lastSource_.tech=o,this.updateSourceCaches_(o)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?Ar(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()&&!Ne.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=Ne[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 dN)return uN(this.middleware_,this.tech_,e,t);if(e in CE)return AE(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw yt(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in cN)return lN(this.middleware_,this.tech_,e);if(e in CE)return AE(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(yt(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(yt(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(yt(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Ar){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(bg||_s);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=o=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const n=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),n===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(n)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||Zn(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=Zn(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=Zn(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 hC(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,n)=>{function r(){t.off("fullscreenerror",u),t.off("fullscreenchange",o)}function o(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",o),t.one("fullscreenerror",u);const c=t.requestFullscreenHelper_(e);c&&(c.then(r,r),c.then(i,n))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function n(){e.off("fullscreenerror",o),e.off("fullscreenchange",r)}function r(){n(),t()}function o(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",o);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=Ne[this.fsApi_.exitFullscreen]();return e&&Ar(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=Ne.documentElement.style.overflow,yn(Ne,"keydown",this.boundFullWindowOnEscKey_),Ne.documentElement.style.overflow="hidden",ml(Ne.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,bs(Ne,"keydown",this.boundFullWindowOnEscKey_),Ne.documentElement.style.overflow=this.docOrigOverflow,Sg(Ne.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&&ne.documentPictureInPicture){const e=Ne.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(nt("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),ne.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(JA(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 Ne&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(ne.documentPictureInPicture&&ne.documentPictureInPicture.window)return ne.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in Ne)return Ne.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const o=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?o.indexOf(n.type)===-1:["textarea"].indexOf(r)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=o=>e.key.toLowerCase()==="f",muteKey:n=o=>e.key.toLowerCase()==="m",playPauseKey:r=o=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const o=De.getComponent("FullscreenToggle");Ne[this.fsApi_.fullscreenEnabled]!==!1&&o.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),De.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),De.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,dt.getTech(u)]).filter(([u,c])=>c?c.isSupported():(yt.error(`The "${u}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(u,c,d){let f;return u.some(g=>c.some(m=>{if(f=d(g,m),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),o=([u,c],d)=>{if(c.canPlaySource(d,this.options_[u.toLowerCase()]))return{source:d,tech:u}};return this.options_.sourceOrder?n=i(e,t,r(o)):n=i(t,e,o),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=vC(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]),aN(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}oN(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?lC(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();Ar(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}),ga(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(_o("beforeerror").forEach(t=>{const i=t(this,e);if(!(kr(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 Si(e),this.addClass("vjs-error"),yt.error(`(CODE:${this.error_.code} ${Si.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),_o("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const n=di(this,this.reportUserActivity),r=function(g){(g.screenX!==t||g.screenY!==i)&&(t=g.screenX,i=g.screenY,n())},o=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(g){n(),this.clearInterval(e)};this.on("mousedown",o),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!_s&&!Jn&&(c.on("mouseenter",function(g){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),c.on("mouseleave",function(g){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 g=this.options_.inactivityTimeout;g<=0||(d=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},g))};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(),ga(this)&&this.trigger("languagechange"))}languages(){return Qt(Cu.prototype.options_.languages,this.languages_)}toJSON(){const e=Qt(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;i<_v.length;i++){const n=_v[i],r=this.breakpoints_[n];if(t<=r){if(e===n)return;e&&this.removeClass(up[e]),this.addClass(up[n]),this.breakpoint_=n;break}}}removeCurrentBreakpoint_(){const e=this.currentBreakpointClass();this.breakpoint_="",e&&this.removeClass(e)}breakpoints(e){return e===void 0?Object.assign(this.breakpoints_):(this.breakpoint_="",this.breakpoints_=Object.assign({},YN,e),this.updateCurrentBreakpoint_(),Object.assign(this.breakpoints_))}responsive(e){if(e===void 0)return this.responsive_;e=!!e;const t=this.responsive_;if(e!==t)return this.responsive_=e,e?(this.on("playerresize",this.boundUpdateCurrentBreakpoint_),this.updateCurrentBreakpoint_()):(this.off("playerresize",this.boundUpdateCurrentBreakpoint_),this.removeCurrentBreakpoint_()),e}currentBreakpoint(){return this.breakpoint_}currentBreakpointClass(){return up[this.breakpoint_]||""}loadMedia(e,t){if(!e||typeof e!="object")return;const i=this.crossOrigin();this.reset(),this.cache_.media=Qt(e);const{artist:n,artwork:r,description:o,poster:u,src:c,textTracks:d,title:f}=this.cache_.media;!r&&u&&(this.cache_.media.artwork=[{src:u,type:Pp(u)}]),i&&this.crossOrigin(i),c&&this.src(c),u&&this.poster(u),Array.isArray(d)&&d.forEach(g=>this.addRemoteTextTrack(g,!1)),this.titleBar&&this.titleBar.update({title:f,description:o||n||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),r=>({kind:r.kind,label:r.label,language:r.language,src:r.src})),n={src:t,textTracks:i};return e&&(n.poster=e,n.artwork=[{src:n.poster,type:Pp(n.poster)}]),n}return Qt(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=co(e),n=i["data-setup"];if(Rd(e,"vjs-fill")&&(i.fill=!0),Rd(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){yt.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let o=0,u=r.length;otypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};yi.prototype.videoTracks=()=>{};yi.prototype.audioTracks=()=>{};yi.prototype.textTracks=()=>{};yi.prototype.remoteTextTracks=()=>{};yi.prototype.remoteTextTrackEls=()=>{};Is.names.forEach(function(s){const e=Is[s];yi.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});yi.prototype.crossorigin=yi.prototype.crossOrigin;yi.players={};const md=ne.navigator;yi.prototype.options_={techOrder:dt.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:md&&(md.languages&&md.languages[0]||md.userLanguage||md.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};YC.forEach(function(s){yi.prototype[`handleTech${wi(s)}_`]=function(){return this.trigger(s)}});De.registerComponent("Player",yi);const Mp="plugin",Nu="activePlugins_",wu={},Np=s=>wu.hasOwnProperty(s),cp=s=>Np(s)?wu[s]:void 0,WC=(s,e)=>{s[Nu]=s[Nu]||{},s[Nu][e]=!0},Bp=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},WN=function(s,e){const t=function(){Bp(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return WC(this,s),Bp(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},HE=(s,e)=>(e.prototype.name=s,function(...t){Bp(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,Bp(this,i.getEventHash()),i});class Zs{constructor(e){if(this.constructor===Zs)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),mT(this),delete this.trigger,oC(this,this.constructor.defaultState),WC(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 ac(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[Nu][e]=!1,this.player=this.state=null,t[e]=HE(e,wu[e])}static isBasic(e){const t=typeof e=="string"?cp(e):e;return typeof t=="function"&&!Zs.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(Np(e))yt.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(yi.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return wu[e]=t,e!==Mp&&(Zs.isBasic(t)?yi.prototype[e]=WN(e,t):yi.prototype[e]=HE(e,t)),t}static deregisterPlugin(e){if(e===Mp)throw new Error("Cannot de-register base plugin.");Np(e)&&(delete wu[e],delete yi.prototype[e])}static getPlugins(e=Object.keys(wu)){let t;return e.forEach(i=>{const n=cp(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=cp(e);return t&&t.VERSION||""}}Zs.getPlugin=cp;Zs.BASE_PLUGIN_NAME=Mp;Zs.registerPlugin(Mp,Zs);yi.prototype.usingPlugin=function(s){return!!this[Nu]&&this[Nu][s]===!0};yi.prototype.hasPlugin=function(s){return!!Np(s)};function XN(s,e){let t=!1;return function(...i){return t||yt.warn(s),t=!0,e.apply(this,i)}}function er(s,e,t,i){return XN(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var QN={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 XC=s=>s.indexOf("#")===0?s.slice(1):s;function ye(s,e,t){let i=ye.getPlayer(s);if(i)return e&&yt.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?bo("#"+XC(s)):s;if(!rc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const o=("getRootNode"in n?n.getRootNode()instanceof ne.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!o.contains(n))&&yt.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)),_o("beforesetup").forEach(c=>{const d=c(n,Qt(e));if(!kr(d)||Array.isArray(d)){yt.error("please return an object in beforesetup hooks");return}e=Qt(e,d)});const u=De.getComponent("Player");return i=new u(n,e,t),_o("setup").forEach(c=>c(i)),i}ye.hooks_=ha;ye.hooks=_o;ye.hook=RM;ye.hookOnce=kM;ye.removeHook=kA;if(ne.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&nc()){let s=bo(".vjs-styles-defaults");if(!s){s=iC("vjs-styles-defaults");const e=bo("head");e&&e.insertBefore(s,e.firstChild),sC(s,` + .video-js { + width: 300px; + height: 150px; + } + + .vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: 56.25% + } + `)}}fv(1,ye);ye.VERSION=uv;ye.options=yi.prototype.options_;ye.getPlayers=()=>yi.players;ye.getPlayer=s=>{const e=yi.players;let t;if(typeof s=="string"){const i=XC(s),n=e[i];if(n)return n;t=bo("#"+i)}else t=s;if(rc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};ye.getAllPlayers=()=>Object.keys(yi.players).map(s=>yi.players[s]).filter(Boolean);ye.players=yi.players;ye.getComponent=De.getComponent;ye.registerComponent=(s,e)=>(dt.isTech(e)&&yt.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),De.registerComponent.call(De,s,e));ye.getTech=dt.getTech;ye.registerTech=dt.registerTech;ye.use=rN;Object.defineProperty(ye,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(ye.middleware,"TERMINATOR",{value:Op,writeable:!1,enumerable:!0});ye.browser=jA;ye.obj=MM;ye.mergeOptions=er(9,"videojs.mergeOptions","videojs.obj.merge",Qt);ye.defineLazyProperty=er(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",yg);ye.bind=er(9,"videojs.bind","native Function.prototype.bind",di);ye.registerPlugin=Zs.registerPlugin;ye.deregisterPlugin=Zs.deregisterPlugin;ye.plugin=(s,e)=>(yt.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),Zs.registerPlugin(s,e));ye.getPlugins=Zs.getPlugins;ye.getPlugin=Zs.getPlugin;ye.getPluginVersion=Zs.getPluginVersion;ye.addLanguage=function(s,e){return s=(""+s).toLowerCase(),ye.options.languages=Qt(ye.options.languages,{[s]:e}),ye.options.languages[s]};ye.log=yt;ye.createLogger=OA;ye.time=XM;ye.createTimeRange=er(9,"videojs.createTimeRange","videojs.time.createTimeRanges",Zn);ye.createTimeRanges=er(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",Zn);ye.formatTime=er(9,"videojs.formatTime","videojs.time.formatTime",Sl);ye.setFormatTime=er(9,"videojs.setFormatTime","videojs.time.setFormatTime",cC);ye.resetFormatTime=er(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",dC);ye.parseUrl=er(9,"videojs.parseUrl","videojs.url.parseUrl",_T);ye.isCrossOrigin=er(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",Lg);ye.EventTarget=vn;ye.any=gT;ye.on=yn;ye.one=Dg;ye.off=bs;ye.trigger=ac;ye.xhr=yA;ye.TrackList=xl;ye.TextTrack=th;ye.TextTrackList=vT;ye.AudioTrack=mC;ye.AudioTrackList=fC;ye.VideoTrack=yC;ye.VideoTrackList=pC;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{ye[s]=function(){return yt.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),eC[s].apply(null,arguments)}});ye.computedStyle=er(9,"videojs.computedStyle","videojs.dom.computedStyle",Ju);ye.dom=eC;ye.fn=VM;ye.num=CN;ye.str=YM;ye.url=sN;ye.Error=QN;class ZN{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 Fp extends ye.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 ZN(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=QC,i},ZC=function(s){return JN(this,ye.obj.merge({},s))};ye.registerPlugin("qualityLevels",ZC);ZC.VERSION=QC;const Ys=fg,Up=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,Nn=s=>ye.log.debug?ye.log.debug.bind(ye,"VHS:",`${s} >`):function(){};function jt(...s){const e=ye.obj||ye;return(e.merge||e.mergeOptions).apply(e,s)}function ss(...s){const e=ye.time||ye;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function e3(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 Cr=1/30,Dr=Cr*3,JC=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},$f=function(s,e){return JC(s,function(t){return t-Cr>=e})},t3=function(s){if(s.length<2)return ss();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(", ")},s3=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},pl=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},FT=(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},bv=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),[]),tD=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},iD=({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},sD=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=tD(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},r3=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+=FT(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},a3=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 ne.Infinity}return nD(s,e,t)},Pd=function({defaultDuration:s,durationList:e,startIndex:t,endIndex:i}){let n=0;if(t>i&&([t,i]=[i,t]),t<0){for(let r=t;r0)for(let d=c-1;d>=0;d--){const f=u[d];if(o+=f.duration,r){if(o<0)continue}else if(o+Cr<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-Pd({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e}}if(c<0){for(let d=c;d<0;d++)if(o-=s.targetDuration,o<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dCr,m=o===0,v=g&&o+Cr>=0;if(!((m||v)&&d!==u.length-1)){if(r){if(o>0)continue}else if(o-Cr>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+Pd({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},oD=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},UT=function(s){return s.excludeUntil&&s.excludeUntil===1/0},Og=function(s){const e=oD(s);return!s.disabled&&!e},u3=function(s){return s.disabled},c3=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=>Og(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),GE=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},rh=s=>{if(!s||!s.playlists||!s.playlists.length)return GE(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;e_A(r))||GE(s,r=>$T(t,r))))return!1}return!0};var Ws={liveEdgeDelay:sD,duration:rD,seekable:o3,getMediaInfoForTime:l3,isEnabled:Og,isDisabled:u3,isExcluded:oD,isIncompatible:UT,playlistEnd:aD,isAes:c3,hasAttribute:lD,estimateSegmentRequestTime:d3,isLowestEnabledRendition:Sv,isAudioOnly:rh,playlistMatch:$T,segmentDurationWithParts:FT};const{log:uD}=ye,Bu=(s,e)=>`${s}-${e}`,cD=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,h3=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const o=new JO;s&&o.on("warn",s),e&&o.on("info",e),i.forEach(d=>o.addParser(d)),n.forEach(d=>o.addTagMapper(d)),o.push(t),o.end();const u=o.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(d){u.hasOwnProperty(d)&&delete u[d]}),u.segments&&u.segments.forEach(function(d){["parts","preloadHints"].forEach(function(f){d.hasOwnProperty(f)&&delete d[f]})})),!u.targetDuration){let d=10;u.segments&&u.segments.length&&(d=u.segments.reduce((f,g)=>Math.max(f,g.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${d}`}),u.targetDuration=d}const c=tD(u);if(c.length&&!u.partTargetDuration){const d=c.reduce((f,g)=>Math.max(f,g.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${d}`}),uD.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},cc=(s,e)=>{s.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(s.mediaGroups[t])for(const i in s.mediaGroups[t])for(const n in s.mediaGroups[t][i]){const r=s.mediaGroups[t][i][n];e(r,t,i,n)}})},dD=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},f3=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];dD({playlist:t,id:Bu(e,t.uri)}),t.resolvedUri=Ys(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||uD.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},p3=s=>{cc(s,e=>{e.uri&&(e.resolvedUri=Ys(s.uri,e.uri))})},g3=(s,e)=>{const t=Bu(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:ne.location.href,resolvedUri:ne.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},hD=(s,e,t=cD)=>{s.uri=e;for(let n=0;n{if(!n.playlists||!n.playlists.length){if(i&&r==="AUDIO"&&!n.uri)for(let c=0;c(n.set(r.id,r),n),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,n)=>{if(!this.processedDateRanges_.has(n)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const r=e[i.class].push(i);i.classListIndex=r-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const n=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&n[i.classListIndex+1]?i.endTime=n[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,n)=>{i.startDate.getTime(){const n=e.status<200||e.status>299,r=e.status>=400&&e.status<=499,o={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)o.error=Mi({},t),o.errorType=ye.Error.NetworkRequestFailed;else if(e.aborted)o.errorType=ye.Error.NetworkRequestAborted;else if(e.timedout)o.errorType=ye.Error.NetworkRequestTimeout;else if(u){const c=i?ye.Error.NetworkBodyParserFailed:ye.Error.NetworkBadStatus;o.errorType=c,o.status=e.status,o.headers=e.headers}return o},m3=Nn("CodecUtils"),pD=function(s){const e=s.attributes||{};if(e.CODECS)return Sr(e.CODECS)},gD=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},y3=(s,e)=>{if(!gD(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},Gd=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(TA(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){m3(`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},qE=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},Md=function(s,e){const t=e.attributes||{},i=Gd(pD(e)||[]);if(gD(s,e)&&!i.audio&&!y3(s,e)){const n=Gd(tP(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:v3}=ye,T3=(s,e)=>{if(e.endList||!e.serverControl)return s;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let n=e.mediaSequence+e.segments.length;if(i){const r=i.parts||[],o=iD(e)-1;o>-1&&o!==r.length-1&&(t._HLS_part=o),(o>-1||r.length)&&n--}t._HLS_msn=n}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new ne.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},_3=(s,e)=>{if(!s)return e;const t=jt(s,e);if(s.preloadHints&&!e.preloadHints&&delete t.preloadHints,s.parts&&!e.parts)delete t.parts;else if(s.parts&&e.parts)for(let i=0;i{const i=s.slice(),n=e.slice();t=t||0;const r=[];let o;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=Ys(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=Ys(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=Ys(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=Ys(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=Ys(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=Ys(e,t.uri))})},yD=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,xv=(s,e,t=vD)=>{const i=jt(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=yD(e);const r=jt(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let o=0;o{mD(o,r.resolvedUri)});for(let o=0;o{if(o.playlists)for(let f=0;f{const t=s.segments||[],i=t[t.length-1],n=i&&i.parts&&i.parts[i.parts.length-1],r=n&&n.duration||i&&i.duration;return e&&r?r*1e3:(s.partTargetDuration||s.targetDuration||10)*500},zE=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:o,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:o,codecs:u})}),{type:e,isLive:t,renditions:i}};let Iu=class extends v3{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Nn("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 VE,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=Ys(this.main.uri,e.uri);this.llhls&&(t=T3(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:Tl({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=h3({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:ye.Error.StreamingHlsPlaylistParserError,error:i}}}excludeAudioOnlyVariants(e){const t=i=>{const n=i.attributes||{},{width:r,height:o}=n.RESOLUTION||{};if(r&&o)return!0;const u=pD(i)||[];return!!Gd(u).video};e.some(t)&&e.forEach(i=>{t(i)||(i.excludeUntil=1/0)})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const o=t||this.parseManifest_({url:i,manifestString:e});o.lastRequest=Date.now(),dD({playlist:o,uri:i,id:n});const u=xv(this.main,o);this.targetDuration=o.partTargetDuration||o.targetDuration,this.pendingMedia_=null,u?(this.main=u,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Ev(this.media(),!!u)),r.parsedPlaylist=zE(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),ne.clearTimeout(this.mediaUpdateTimeout),ne.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new VE,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(ne.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=ne.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_(Ev(e,!0)),!n)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const o={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:o}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(u,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=Up(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:o}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(ne.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&&(ne.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=ne.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&&(ne.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=ne.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=ne.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:Tl({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=Up(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=zE(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,hD(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=yD(i),i.segments.forEach(n=>{mD(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||ne.location.href;this.main=g3(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,n=e.ID;let r=i.playlists.length;for(;r--;){const o=i.playlists[r];if(o.attributes["PATHWAY-ID"]===n){const u=o.resolvedUri,c=o.id;if(t){const d=this.createCloneURI_(o.resolvedUri,e),f=Bu(n,d),g=this.createCloneAttributes_(n,o.attributes),m=this.createClonePlaylist_(o,f,e,g);i.playlists[r]=m,i.playlists[f]=m,i.playlists[d]=m}else i.playlists.splice(r,1);delete i.playlists[c],delete i.playlists[u]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,n=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!i.mediaGroups[r]||!i.mediaGroups[r][n])){for(const o in i.mediaGroups[r])if(o===n){for(const u in i.mediaGroups[r][o])i.mediaGroups[r][o][u].playlists.forEach((d,f)=>{const g=i.playlists[d.id],m=g.id,v=g.resolvedUri;delete i.playlists[m],delete i.playlists[v]});delete i.mediaGroups[r][o]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),o=Bu(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,o,e,u);i.playlists[n]=c,i.playlists[o]=c,i.playlists[r]=c,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],n=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(!(!n.mediaGroups[r]||n.mediaGroups[r][t]))for(const o in n.mediaGroups[r]){if(o===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][o]){const c=n.mediaGroups[r][o][u];n.mediaGroups[r][t][u]=Mi({},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((g,m)=>{const v=n.playlists[g.id],_=cD(r,t,u),b=Bu(t,_);if(v&&!n.playlists[b]){const E=this.createClonePlaylist_(v,b,e),w=E.resolvedUri;n.playlists[b]=E,n.playlists[w]=E}d.playlists[m]=this.createClonePlaylist_(g,b,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),o={resolvedUri:r,uri:r,id:t};return e.segments&&(o.segments=[]),n&&(o.attributes=n),jt(e,o)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const n=t["URI-REPLACEMENT"].PARAMS;for(const r of Object.keys(n))i.searchParams.set(r,n[r]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{t[n]&&(i[n]=e)}),i}getKeyIdSet(e){const t=new Set;if(!e||!e.contentProtection)return t;for(const i in e.contentProtection)if(e.contentProtection[i]&&e.contentProtection[i].attributes&&e.contentProtection[i].attributes.keyId){const n=e.contentProtection[i].attributes.keyId;t.add(n.toLowerCase())}return t}};const Av=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)},S3=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},x3=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},TD=function(){const s=function e(t,i){t=jt({timeout:45e3},t);const n=e.beforeRequest||ye.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||ye.Vhs.xhr._requestCallbackSet||new Set,o=e._responseCallbackSet||ye.Vhs.xhr._responseCallbackSet;n&&typeof n=="function"&&(ye.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(n));const u=ye.Vhs.xhr.original===!0?ye.xhr:ye.Vhs.xhr,c=S3(r,t);r.delete(n);const d=u(c||t,function(g,m){return x3(o,d,g,m),Av(d,g,m,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},E3=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=ne.BigInt(s.offset)+ne.BigInt(s.length)-ne.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},Cv=function(s){const e={};return s.byterange&&(e.Range=E3(s.byterange)),e},A3=function(s,e){return s.start(e)+"-"+s.end(e)},C3=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},D3=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},_D=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];SA(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},$p=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},bD=function(s){return s.resolvedUri},SD=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let o=0;oSD(s),L3=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)},k3=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,O3=(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:Ws.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},P3=(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*xD)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},M3=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},N3=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=P3(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=R3(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},ED=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:o})=>{if(!o)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return o({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return o({message:"player must be playing a live stream to start buffering"});if(!N3(e))return o({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=O3(s,e);if(!u)return o({message:`${s} was not found in the stream`});const c=u.segment,d=M3(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return o({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{ED({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:o})});return}const f=c.start+d,g=()=>o(null,r.currentTime());r.one("seeked",g),n&&r.pause(),i(f)},Sy=(s,e)=>{if(s.readyState===4)return e()},F3=(s,e,t,i)=>{let n=[],r,o=!1;const u=function(g,m,v,_){return m.abort(),o=!0,t(g,m,v,_)},c=function(g,m){if(o)return;if(g)return g.metadata=Tl({requestType:i,request:m,error:g}),u(g,m,"",n);const v=m.responseText.substring(n&&n.byteLength||0,m.responseText.length);if(n=dP(n,xA(v,!0)),r=r||xd(n),n.length<10||r&&n.lengthu(g,m,"",n));const _=cT(n);return _==="ts"&&n.length<188?Sy(m,()=>u(g,m,"",n)):!_&&n.length<376?Sy(m,()=>u(g,m,"",n)):u(null,m,_,n)},f=e({uri:s,beforeSend(g){g.overrideMimeType("text/plain; charset=x-user-defined"),g.addEventListener("progress",function({total:m,loaded:v}){return Av(g,null,{statusCode:g.status},c)})}},function(g,m){return Av(f,g,m,c)});return f},{EventTarget:U3}=ye,KE=function(s,e){if(!vD(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}`},j3=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=uM(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return hD(r,e,$3),r},H3=(s,e)=>{cc(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},G3=(s,e,t)=>{let i=!0,n=jt(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=xv(n,r.playlists[0],KE);f&&(n=f,c in n.mediaGroups[o][u]||(n.mediaGroups[o][u][c]=r),n.mediaGroups[o][u][c].playlists[0]=n.playlists[d],i=!1)}}),H3(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},V3=(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,YE=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const o=gg(r);if(!e[o])break;const u=e[o].sidxInfo;V3(u,r)&&(t[o]=e[o])}}return t},q3=(s,e)=>{let i=YE(s.playlists,e);return cc(s,(n,r,o,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=jt(i,YE(c,e))}}),i};class Dv extends U3{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_=Nn("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&&gg(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){ne.clearTimeout(this.mediaRequest_),this.mediaRequest_=ne.setTimeout(()=>i(!1),0);return}const r=Up(e.sidx.resolvedUri),o=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:g}=d;let m;try{m=pM(it(d.response).subarray(8))}catch(v){v.metadata=Tl({requestType:g,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:m},oT(e,m,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=F3(r,this.vhs_.xhr,(c,d,f,g)=>{if(c)return o(c,d);if(!f||f!=="mp4"){const _=f||"unknown";return o({status:d.status,message:`Unsupported ${_} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},d)}const{offset:m,length:v}=e.sidx.byterange;if(g.length>=v+m)return o(c,{response:g.subarray(m,m+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:Cv({byterange:e.sidx.byterange})},o)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},ne.clearTimeout(this.minimumUpdatePeriodTimeout_),ne.clearTimeout(this.mediaRequest_),ne.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,ne.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(),ne.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(ne.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,ne.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=ne.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_){ne.clearTimeout(this.mediaRequest_),this.mediaRequest_=ne.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,n)=>{if(i){const{requestType:o}=n;i.metadata=Tl({requestType:o,request:n,error:i})}if(this.requestErrored_(i,n)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const r=n.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?this.mainLoaded_=Date.parse(n.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=Up(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=cM(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:Ys(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,n)=>{if(!this.request)return;if(i){const{requestType:o}=n;return this.error.metadata=Tl({requestType:o,request:n,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;t.method==="HEAD"?!n.responseHeaders||!n.responseHeaders.date?r=this.mainLoaded_:r=Date.parse(n.responseHeaders.date):r=Date.parse(n.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){ne.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=j3({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:ye.Error.StreamingDashManifestParserError,error:r},this.trigger("error")}e&&(i=G3(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const n=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(n&&n!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=n),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:r,endList:o}=i,u=[];i.playlists.forEach(d=>{u.push({id:d.id,bandwidth:d.attributes.BANDWIDTH,resolution:d.attributes.RESOLUTION,codecs:d.attributes.CODECS})});const c={duration:r,isLive:!o,renditions:u};t.parsedManifest=c,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(ne.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_=ne.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_=q3(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=ne.setTimeout(()=>{this.trigger("mediaupdatetimeout"),n()},Ev(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 ts={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 z3=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(x){var C,A,D,k;if(C=y[x],!!C)if(arguments.length===2)for(D=C.length,A=0;A"u")){for(y in ie)ie.hasOwnProperty(y)&&(ie[y]=[y.charCodeAt(0),y.charCodeAt(1),y.charCodeAt(2),y.charCodeAt(3)]);Q=new Uint8Array([105,115,111,109]),H=new Uint8Array([97,118,99,49]),oe=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]),te=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),ae={video:X,audio:te},se=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),$=new Uint8Array([0,0,0,0,0,0,0,0]),he=new Uint8Array([0,0,0,0,0,0,0,0]),Se=he,be=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Pe=he,ce=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(y){var x=[],C=0,A,D,k;for(A=1;A>>1,y.samplingfrequencyindex<<7|y.channelcount<<3,6,1,2]))},f=function(){return u(ie.ftyp,Q,oe,Q,H)},V=function(y){return u(ie.hdlr,ae[y])},g=function(y){return u(ie.mdat,y)},B=function(y){var x=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,y.duration>>>24&255,y.duration>>>16&255,y.duration>>>8&255,y.duration&255,85,196,0,0]);return y.samplerate&&(x[12]=y.samplerate>>>24&255,x[13]=y.samplerate>>>16&255,x[14]=y.samplerate>>>8&255,x[15]=y.samplerate&255),u(ie.mdhd,x)},F=function(y){return u(ie.mdia,B(y),V(y.type),v(y))},m=function(y){return u(ie.mfhd,new Uint8Array([0,0,0,0,(y&4278190080)>>24,(y&16711680)>>16,(y&65280)>>8,y&255]))},v=function(y){return u(ie.minf,y.type==="video"?u(ie.vmhd,ce):u(ie.smhd,$),c(),q(y))},_=function(y,x){for(var C=[],A=x.length;A--;)C[A]=P(x[A]);return u.apply(null,[ie.moof,m(y)].concat(C))},b=function(y){for(var x=y.length,C=[];x--;)C[x]=L(y[x]);return u.apply(null,[ie.moov,w(4294967295)].concat(C).concat(E(y)))},E=function(y){for(var x=y.length,C=[];x--;)C[x]=z(y[x]);return u.apply(null,[ie.mvex].concat(C))},w=function(y){var x=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(y&4278190080)>>24,(y&16711680)>>16,(y&65280)>>8,y&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return u(ie.mvhd,x)},N=function(y){var x=y.samples||[],C=new Uint8Array(4+x.length),A,D;for(D=0;D>>8),k.push(A[Z].byteLength&255),k=k.concat(Array.prototype.slice.call(A[Z]));for(Z=0;Z>>8),W.push(D[Z].byteLength&255),W=W.concat(Array.prototype.slice.call(D[Z]));if(J=[ie.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(C.width&65280)>>8,C.width&255,(C.height&65280)>>8,C.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u(ie.avcC,new Uint8Array([1,C.profileIdc,C.profileCompatibility,C.levelIdc,255].concat([A.length],k,[D.length],W))),u(ie.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],C.sarRatio){var re=C.sarRatio[0],fe=C.sarRatio[1];J.push(u(ie.pasp,new Uint8Array([(re&4278190080)>>24,(re&16711680)>>16,(re&65280)>>8,re&255,(fe&4278190080)>>24,(fe&16711680)>>16,(fe&65280)>>8,fe&255])))}return u.apply(null,J)},x=function(C){return u(ie.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(C.channelcount&65280)>>8,C.channelcount&255,(C.samplesize&65280)>>8,C.samplesize&255,0,0,0,0,(C.samplerate&65280)>>8,C.samplerate&255,0,0]),d(C))}})(),I=function(y){var x=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,0,(y.duration&4278190080)>>24,(y.duration&16711680)>>16,(y.duration&65280)>>8,y.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(y.width&65280)>>8,y.width&255,0,0,(y.height&65280)>>8,y.height&255,0,0]);return u(ie.tkhd,x)},P=function(y){var x,C,A,D,k,W,Z;return x=u(ie.tfhd,new Uint8Array([0,0,0,58,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),W=Math.floor(y.baseMediaDecodeTime/o),Z=Math.floor(y.baseMediaDecodeTime%o),C=u(ie.tfdt,new Uint8Array([1,0,0,0,W>>>24&255,W>>>16&255,W>>>8&255,W&255,Z>>>24&255,Z>>>16&255,Z>>>8&255,Z&255])),k=92,y.type==="audio"?(A=ee(y,k),u(ie.traf,x,C,A)):(D=N(y),A=ee(y,D.length+k),u(ie.traf,x,C,A,D))},L=function(y){return y.duration=y.duration||4294967295,u(ie.trak,I(y),F(y))},z=function(y){var x=new Uint8Array([0,0,0,0,(y.id&4278190080)>>24,(y.id&16711680)>>16,(y.id&65280)>>8,y.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return y.type!=="video"&&(x[x.length-1]=0),u(ie.trex,x)},(function(){var y,x,C;C=function(A,D){var k=0,W=0,Z=0,J=0;return A.length&&(A[0].duration!==void 0&&(k=1),A[0].size!==void 0&&(W=2),A[0].flags!==void 0&&(Z=4),A[0].compositionTimeOffset!==void 0&&(J=8)),[0,0,k|W|Z|J,1,(A.length&4278190080)>>>24,(A.length&16711680)>>>16,(A.length&65280)>>>8,A.length&255,(D&4278190080)>>>24,(D&16711680)>>>16,(D&65280)>>>8,D&255]},x=function(A,D){var k,W,Z,J,re,fe;for(J=A.samples||[],D+=20+16*J.length,Z=C(J,D),W=new Uint8Array(Z.length+J.length*16),W.set(Z),k=Z.length,fe=0;fe>>24,W[k++]=(re.duration&16711680)>>>16,W[k++]=(re.duration&65280)>>>8,W[k++]=re.duration&255,W[k++]=(re.size&4278190080)>>>24,W[k++]=(re.size&16711680)>>>16,W[k++]=(re.size&65280)>>>8,W[k++]=re.size&255,W[k++]=re.flags.isLeading<<2|re.flags.dependsOn,W[k++]=re.flags.isDependedOn<<6|re.flags.hasRedundancy<<4|re.flags.paddingValue<<1|re.flags.isNonSyncSample,W[k++]=re.flags.degradationPriority&61440,W[k++]=re.flags.degradationPriority&15,W[k++]=(re.compositionTimeOffset&4278190080)>>>24,W[k++]=(re.compositionTimeOffset&16711680)>>>16,W[k++]=(re.compositionTimeOffset&65280)>>>8,W[k++]=re.compositionTimeOffset&255;return u(ie.trun,W)},y=function(A,D){var k,W,Z,J,re,fe;for(J=A.samples||[],D+=20+8*J.length,Z=C(J,D),k=new Uint8Array(Z.length+J.length*8),k.set(Z),W=Z.length,fe=0;fe>>24,k[W++]=(re.duration&16711680)>>>16,k[W++]=(re.duration&65280)>>>8,k[W++]=re.duration&255,k[W++]=(re.size&4278190080)>>>24,k[W++]=(re.size&16711680)>>>16,k[W++]=(re.size&65280)>>>8,k[W++]=re.size&255;return u(ie.trun,k)},ee=function(A,D){return A.type==="audio"?y(A,D):x(A,D)}})();var Ae={ftyp:f,mdat:g,moof:_,moov:b,initSegment:function(y){var x=f(),C=b(y),A;return A=new Uint8Array(x.byteLength+C.byteLength),A.set(x),A.set(C,x.byteLength),A}},Be=function(y){var x,C,A=[],D=[];for(D.byteLength=0,D.nalCount=0,D.duration=0,A.byteLength=0,x=0;x1&&(x=y.shift(),y.byteLength-=x.byteLength,y.nalCount-=x.nalCount,y[0][0].dts=x.dts,y[0][0].pts=x.pts,y[0][0].duration+=x.duration),y},ht=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},Tt=function(y,x){var C=ht();return C.dataOffset=x,C.compositionTimeOffset=y.pts-y.dts,C.duration=y.duration,C.size=4*y.length,C.size+=y.byteLength,y.keyFrame&&(C.flags.dependsOn=2,C.flags.isNonSyncSample=0),C},Ni=function(y,x){var C,A,D,k,W,Z=x||0,J=[];for(C=0;CFt.ONE_SECOND_IN_TS/2))){for(re=ei()[y.samplerate],re||(re=x[0].data),fe=0;fe=C?y:(x.minSegmentDts=1/0,y.filter(function(A){return A.dts>=C?(x.minSegmentDts=Math.min(x.minSegmentDts,A.dts),x.minSegmentPts=x.minSegmentDts,!0):!1}))},Rt=function(y){var x,C,A=[];for(x=0;x=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(y),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Pt.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},Pt.prototype.addText=function(y){this.rows[this.rowIdx]+=y},Pt.prototype.backspace=function(){if(!this.isEmpty()){var y=this.rows[this.rowIdx];this.rows[this.rowIdx]=y.substr(0,y.length-1)}};var Dt=function(y,x,C){this.serviceNum=y,this.text="",this.currentWindow=new Pt(-1),this.windows=[],this.stream=C,typeof x=="string"&&this.createTextDecoder(x)};Dt.prototype.init=function(y,x){this.startPts=y;for(var C=0;C<8;C++)this.windows[C]=new Pt(C),typeof x=="function"&&(this.windows[C].beforeRowOverflow=x)},Dt.prototype.setCurrentWindow=function(y){this.currentWindow=this.windows[y]},Dt.prototype.createTextDecoder=function(y){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(y)}catch(x){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+y+" encoding. "+x})}};var St=function(y){y=y||{},St.prototype.init.call(this);var x=this,C=y.captionServices||{},A={},D;Object.keys(C).forEach(k=>{D=C[k],/^SERVICE/.test(k)&&(A[k]=D.encoding)}),this.serviceEncodings=A,this.current708Packet=null,this.services={},this.push=function(k){k.type===3?(x.new708Packet(),x.add708Bytes(k)):(x.current708Packet===null&&x.new708Packet(),x.add708Bytes(k))}};St.prototype=new ps,St.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},St.prototype.add708Bytes=function(y){var x=y.ccData,C=x>>>8,A=x&255;this.current708Packet.ptsVals.push(y.pts),this.current708Packet.data.push(C),this.current708Packet.data.push(A)},St.prototype.push708Packet=function(){var y=this.current708Packet,x=y.data,C=null,A=null,D=0,k=x[D++];for(y.seq=k>>6,y.sizeCode=k&63;D>5,A=k&31,C===7&&A>0&&(k=x[D++],C=k),this.pushServiceBlock(C,D,A),A>0&&(D+=A-1)},St.prototype.pushServiceBlock=function(y,x,C){var A,D=x,k=this.current708Packet.data,W=this.services[y];for(W||(W=this.initService(y,D));D("0"+(Ge&255).toString(16)).slice(-2)).join("")}if(D?(Ee=[Z,J],y++):Ee=[Z],x.textDecoder_&&!A)fe=x.textDecoder_.decode(new Uint8Array(Ee));else if(D){const we=Ue(Ee);fe=String.fromCharCode(parseInt(we,16))}else fe=Es(W|Z);return re.pendingNewLine&&!re.isEmpty()&&re.newLine(this.getPts(y)),re.pendingNewLine=!1,re.addText(fe),y},St.prototype.multiByteCharacter=function(y,x){var C=this.current708Packet.data,A=C[y+1],D=C[y+2];return Ii(A)&&Ii(D)&&(y=this.handleText(++y,x,{isMultiByte:!0})),y},St.prototype.setCurrentWindow=function(y,x){var C=this.current708Packet.data,A=C[y],D=A&7;return x.setCurrentWindow(D),y},St.prototype.defineWindow=function(y,x){var C=this.current708Packet.data,A=C[y],D=A&7;x.setCurrentWindow(D);var k=x.currentWindow;return A=C[++y],k.visible=(A&32)>>5,k.rowLock=(A&16)>>4,k.columnLock=(A&8)>>3,k.priority=A&7,A=C[++y],k.relativePositioning=(A&128)>>7,k.anchorVertical=A&127,A=C[++y],k.anchorHorizontal=A,A=C[++y],k.anchorPoint=(A&240)>>4,k.rowCount=A&15,A=C[++y],k.columnCount=A&63,A=C[++y],k.windowStyle=(A&56)>>3,k.penStyle=A&7,k.virtualRowCount=k.rowCount+1,y},St.prototype.setWindowAttributes=function(y,x){var C=this.current708Packet.data,A=C[y],D=x.currentWindow.winAttr;return A=C[++y],D.fillOpacity=(A&192)>>6,D.fillRed=(A&48)>>4,D.fillGreen=(A&12)>>2,D.fillBlue=A&3,A=C[++y],D.borderType=(A&192)>>6,D.borderRed=(A&48)>>4,D.borderGreen=(A&12)>>2,D.borderBlue=A&3,A=C[++y],D.borderType+=(A&128)>>5,D.wordWrap=(A&64)>>6,D.printDirection=(A&48)>>4,D.scrollDirection=(A&12)>>2,D.justify=A&3,A=C[++y],D.effectSpeed=(A&240)>>4,D.effectDirection=(A&12)>>2,D.displayEffect=A&3,y},St.prototype.flushDisplayed=function(y,x){for(var C=[],A=0;A<8;A++)x.windows[A].visible&&!x.windows[A].isEmpty()&&C.push(x.windows[A].getText());x.endPts=y,x.text=C.join(` + +`),this.pushCaption(x),x.startPts=y},St.prototype.pushCaption=function(y){y.text!==""&&(this.trigger("data",{startPts:y.startPts,endPts:y.endPts,text:y.text,stream:"cc708_"+y.serviceNum}),y.text="",y.startPts=y.endPts)},St.prototype.displayWindows=function(y,x){var C=this.current708Packet.data,A=C[++y],D=this.getPts(y);this.flushDisplayed(D,x);for(var k=0;k<8;k++)A&1<>4,D.offset=(A&12)>>2,D.penSize=A&3,A=C[++y],D.italics=(A&128)>>7,D.underline=(A&64)>>6,D.edgeType=(A&56)>>3,D.fontStyle=A&7,y},St.prototype.setPenColor=function(y,x){var C=this.current708Packet.data,A=C[y],D=x.currentWindow.penColor;return A=C[++y],D.fgOpacity=(A&192)>>6,D.fgRed=(A&48)>>4,D.fgGreen=(A&12)>>2,D.fgBlue=A&3,A=C[++y],D.bgOpacity=(A&192)>>6,D.bgRed=(A&48)>>4,D.bgGreen=(A&12)>>2,D.bgBlue=A&3,A=C[++y],D.edgeRed=(A&48)>>4,D.edgeGreen=(A&12)>>2,D.edgeBlue=A&3,y},St.prototype.setPenLocation=function(y,x){var C=this.current708Packet.data,A=C[y],D=x.currentWindow.penLoc;return x.currentWindow.pendingNewLine=!0,A=C[++y],D.row=A&15,A=C[++y],D.column=A&63,y},St.prototype.reset=function(y,x){var C=this.getPts(y);return this.flushDisplayed(C,x),this.initService(x.serviceNum,y)};var bn={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},Fr=function(y){return y===null?"":(y=bn[y]||y,String.fromCharCode(y))},Cl=14,ah=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],en=function(){for(var y=[],x=Cl+1;x--;)y.push({text:"",indent:0,offset:0});return y},Kt=function(y,x){Kt.prototype.init.call(this),this.field_=y||0,this.dataChannel_=x||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(C){var A,D,k,W,Z;if(A=C.ccData&32639,A===this.lastControlCode_){this.lastControlCode_=null;return}if((A&61440)===4096?this.lastControlCode_=A:A!==this.PADDING_&&(this.lastControlCode_=null),k=A>>>8,W=A&255,A!==this.PADDING_)if(A===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(A===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(C.pts),this.flushDisplayed(C.pts),D=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=D,this.startPts_=C.pts;else if(A===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(C.pts);else if(A===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(C.pts);else if(A===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(C.pts);else if(A===this.CARRIAGE_RETURN_)this.clearFormatting(C.pts),this.flushDisplayed(C.pts),this.shiftRowsUp_(),this.startPts_=C.pts;else if(A===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(A===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(C.pts),this.displayed_=en();else if(A===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=en();else if(A===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(C.pts),this.displayed_=en()),this.mode_="paintOn",this.startPts_=C.pts;else if(this.isSpecialCharacter(k,W))k=(k&3)<<8,Z=Fr(k|W),this[this.mode_](C.pts,Z),this.column_++;else if(this.isExtCharacter(k,W))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),k=(k&3)<<8,Z=Fr(k|W),this[this.mode_](C.pts,Z),this.column_++;else if(this.isMidRowCode(k,W))this.clearFormatting(C.pts),this[this.mode_](C.pts," "),this.column_++,(W&14)===14&&this.addFormatting(C.pts,["i"]),(W&1)===1&&this.addFormatting(C.pts,["u"]);else if(this.isOffsetControlCode(k,W)){const re=W&3;this.nonDisplayed_[this.row_].offset=re,this.column_+=re}else if(this.isPAC(k,W)){var J=ah.indexOf(A&7968);if(this.mode_==="rollUp"&&(J-this.rollUpRows_+1<0&&(J=this.rollUpRows_-1),this.setRollUp(C.pts,J)),J!==this.row_&&J>=0&&J<=14&&(this.clearFormatting(C.pts),this.row_=J),W&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(C.pts,["u"]),(A&16)===16){const re=(A&14)>>1;this.column_=re*4,this.nonDisplayed_[this.row_].indent+=re}this.isColorPAC(W)&&(W&14)===14&&this.addFormatting(C.pts,["i"])}else this.isNormalChar(k)&&(W===0&&(W=null),Z=Fr(k),Z+=Fr(W),this[this.mode_](C.pts,Z),this.column_+=Z.length)}};Kt.prototype=new ps,Kt.prototype.flushDisplayed=function(y){const x=A=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+A+"."})},C=[];this.displayed_.forEach((A,D)=>{if(A&&A.text&&A.text.length){try{A.text=A.text.trim()}catch{x(D)}A.text.length&&C.push({text:A.text,line:D+1,position:10+Math.min(70,A.indent*10)+A.offset*2.5})}else A==null&&x(D)}),C.length&&this.trigger("data",{startPts:this.startPts_,endPts:y,content:C,stream:this.name_})},Kt.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=en(),this.nonDisplayed_=en(),this.lastControlCode_=null,this.column_=0,this.row_=Cl,this.rollUpRows_=2,this.formatting_=[]},Kt.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},Kt.prototype.isSpecialCharacter=function(y,x){return y===this.EXT_&&x>=48&&x<=63},Kt.prototype.isExtCharacter=function(y,x){return(y===this.EXT_+1||y===this.EXT_+2)&&x>=32&&x<=63},Kt.prototype.isMidRowCode=function(y,x){return y===this.EXT_&&x>=32&&x<=47},Kt.prototype.isOffsetControlCode=function(y,x){return y===this.OFFSET_&&x>=33&&x<=35},Kt.prototype.isPAC=function(y,x){return y>=this.BASE_&&y=64&&x<=127},Kt.prototype.isColorPAC=function(y){return y>=64&&y<=79||y>=96&&y<=127},Kt.prototype.isNormalChar=function(y){return y>=32&&y<=127},Kt.prototype.setRollUp=function(y,x){if(this.mode_!=="rollUp"&&(this.row_=Cl,this.mode_="rollUp",this.flushDisplayed(y),this.nonDisplayed_=en(),this.displayed_=en()),x!==void 0&&x!==this.row_)for(var C=0;C"},"");this[this.mode_](y,C)},Kt.prototype.clearFormatting=function(y){if(this.formatting_.length){var x=this.formatting_.reverse().reduce(function(C,A){return C+""},"");this.formatting_=[],this[this.mode_](y,x)}},Kt.prototype.popOn=function(y,x){var C=this.nonDisplayed_[this.row_].text;C+=x,this.nonDisplayed_[this.row_].text=C},Kt.prototype.rollUp=function(y,x){var C=this.displayed_[this.row_].text;C+=x,this.displayed_[this.row_].text=C},Kt.prototype.shiftRowsUp_=function(){var y;for(y=0;yx&&(C=-1);Math.abs(x-y)>Bi;)y+=C*Ta;return y},$n=function(y){var x,C;$n.prototype.init.call(this),this.type_=y||dc,this.push=function(A){if(A.type==="metadata"){this.trigger("data",A);return}this.type_!==dc&&A.type!==this.type_||(C===void 0&&(C=A.dts),A.dts=Dl(A.dts,C),A.pts=Dl(A.pts,C),x=A.dts,this.trigger("data",A))},this.flush=function(){C=x,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){C=void 0,x=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};$n.prototype=new Co;var $r={TimestampRolloverStream:$n,handleRollover:Dl},Bg=(y,x,C)=>{if(!y)return-1;for(var A=C;A";y.data[0]===wl.Utf8&&(C=Do(y.data,0,x),!(C<0)&&(y.mimeType=As(y.data,x,C),x=C+1,y.pictureType=y.data[x],x++,A=Do(y.data,0,x),!(A<0)&&(y.description=tr(y.data,x,A),x=A+1,y.mimeType===D?y.url=As(y.data,x,y.data.length):y.pictureData=y.data.subarray(x,y.data.length))))},"T*":function(y){y.data[0]===wl.Utf8&&(y.value=tr(y.data,1,y.data.length).replace(/\0*$/,""),y.values=y.value.split("\0"))},TXXX:function(y){var x;y.data[0]===wl.Utf8&&(x=Do(y.data,0,1),x!==-1&&(y.description=tr(y.data,1,x),y.value=tr(y.data,x+1,y.data.length).replace(/\0*$/,""),y.data=y.value))},"W*":function(y){y.url=As(y.data,0,y.data.length).replace(/\0.*$/,"")},WXXX:function(y){var x;y.data[0]===wl.Utf8&&(x=Do(y.data,0,1),x!==-1&&(y.description=tr(y.data,1,x),y.url=As(y.data,x+1,y.data.length).replace(/\0.*$/,"")))},PRIV:function(y){var x;for(x=0;x>>2;Ge*=4,Ge+=we[7]&3,fe.timeStamp=Ge,Z.pts===void 0&&Z.dts===void 0&&(Z.pts=fe.timeStamp,Z.dts=fe.timeStamp),this.trigger("timestamp",fe)}Z.frames.push(fe),J+=10,J+=re}while(J>>4>1&&(W+=D[W]+1),k.pid===0)k.type="pat",y(D.subarray(W),k),this.trigger("data",k);else if(k.pid===this.pmtPid)for(k.type="pmt",y(D.subarray(W),k),this.trigger("data",k);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([D,W,k]):this.processPes_(D,W,k)},this.processPes_=function(D,k,W){W.pid===this.programMapTable.video?W.streamType=Xi.H264_STREAM_TYPE:W.pid===this.programMapTable.audio?W.streamType=Xi.ADTS_STREAM_TYPE:W.streamType=this.programMapTable["timed-metadata"][W.pid],W.type="pes",W.data=D.subarray(k),this.trigger("data",W)}},Sn.prototype=new Rl,Sn.STREAM_TYPES={h264:27,adts:15},kl=function(){var y=this,x=!1,C={data:[],size:0},A={data:[],size:0},D={data:[],size:0},k,W=function(J,re){var fe;const Ee=J[0]<<16|J[1]<<8|J[2];re.data=new Uint8Array,Ee===1&&(re.packetLength=6+(J[4]<<8|J[5]),re.dataAlignmentIndicator=(J[6]&4)!==0,fe=J[7],fe&192&&(re.pts=(J[9]&14)<<27|(J[10]&255)<<20|(J[11]&254)<<12|(J[12]&255)<<5|(J[13]&254)>>>3,re.pts*=4,re.pts+=(J[13]&6)>>>1,re.dts=re.pts,fe&64&&(re.dts=(J[14]&14)<<27|(J[15]&255)<<20|(J[16]&254)<<12|(J[17]&255)<<5|(J[18]&254)>>>3,re.dts*=4,re.dts+=(J[18]&6)>>>1)),re.data=J.subarray(9+J[8]))},Z=function(J,re,fe){var Ee=new Uint8Array(J.size),Ue={type:re},we=0,Ge=0,ot=!1,Ri;if(!(!J.data.length||J.size<9)){for(Ue.trackId=J.data[0].pid,we=0;we>5,J=((x[D+6]&3)+1)*1024,re=J*jn/Nl[(x[D+2]&60)>>>2],x.byteLength-D>>6&3)+1,channelcount:(x[D+2]&1)<<2|(x[D+3]&192)>>>6,samplerate:Nl[(x[D+2]&60)>>>2],samplingfrequencyindex:(x[D+2]&60)>>>2,samplesize:16,data:x.subarray(D+7+W,D+k)}),C++,D+=k}typeof fe=="number"&&(this.skipWarn_(fe,D),fe=null),x=x.subarray(D)}},this.flush=function(){C=0,this.trigger("done")},this.reset=function(){x=void 0,this.trigger("reset")},this.endTimeline=function(){x=void 0,this.trigger("endedtimeline")}},ba.prototype=new Ml;var Sa=ba,Hr;Hr=function(y){var x=y.byteLength,C=0,A=0;this.length=function(){return 8*x},this.bitsAvailable=function(){return 8*x+A},this.loadWord=function(){var D=y.byteLength-x,k=new Uint8Array(4),W=Math.min(4,x);if(W===0)throw new Error("no bytes available");k.set(y.subarray(D,D+W)),C=new DataView(k.buffer).getUint32(0),A=W*8,x-=W},this.skipBits=function(D){var k;A>D?(C<<=D,A-=D):(D-=A,k=Math.floor(D/8),D-=k*8,x-=k,this.loadWord(),C<<=D,A-=D)},this.readBits=function(D){var k=Math.min(A,D),W=C>>>32-k;return A-=k,A>0?C<<=k:x>0&&this.loadWord(),k=D-k,k>0?W<>>D)!==0)return C<<=D,A-=D,D;return this.loadWord(),D+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var D=this.skipLeadingZeros();return this.readBits(D+1)-1},this.readExpGolomb=function(){var D=this.readUnsignedExpGolomb();return 1&D?1+D>>>1:-1*(D>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var ch=Hr,Bl=t,dh=ch,sr,Ps,Fl;Ps=function(){var y=0,x,C;Ps.prototype.init.call(this),this.push=function(A){var D;C?(D=new Uint8Array(C.byteLength+A.data.byteLength),D.set(C),D.set(A.data,C.byteLength),C=D):C=A.data;for(var k=C.byteLength;y3&&this.trigger("data",C.subarray(y+3)),C=null,y=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},Ps.prototype=new Bl,Fl={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},sr=function(){var y=new Ps,x,C,A,D,k,W,Z;sr.prototype.init.call(this),x=this,this.push=function(J){J.type==="video"&&(C=J.trackId,A=J.pts,D=J.dts,y.push(J))},y.on("data",function(J){var re={trackId:C,pts:A,dts:D,data:J,nalUnitTypeCode:J[0]&31};switch(re.nalUnitTypeCode){case 5:re.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:re.nalUnitType="sei_rbsp",re.escapedRBSP=k(J.subarray(1));break;case 7:re.nalUnitType="seq_parameter_set_rbsp",re.escapedRBSP=k(J.subarray(1)),re.config=W(re.escapedRBSP);break;case 8:re.nalUnitType="pic_parameter_set_rbsp";break;case 9:re.nalUnitType="access_unit_delimiter_rbsp";break}x.trigger("data",re)}),y.on("done",function(){x.trigger("done")}),y.on("partialdone",function(){x.trigger("partialdone")}),y.on("reset",function(){x.trigger("reset")}),y.on("endedtimeline",function(){x.trigger("endedtimeline")}),this.flush=function(){y.flush()},this.partialFlush=function(){y.partialFlush()},this.reset=function(){y.reset()},this.endTimeline=function(){y.endTimeline()},Z=function(J,re){var fe=8,Ee=8,Ue,we;for(Ue=0;Ue>4;return C=C>=0?C:0,D?C+20:C+10},ko=function(y,x){return y.length-x<10||y[x]!==73||y[x+1]!==68||y[x+2]!==51?x:(x+=Ul(y,x),ko(y,x))},hh=function(y){var x=ko(y,0);return y.length>=x+2&&(y[x]&255)===255&&(y[x+1]&240)===240&&(y[x+1]&22)===16},Oo=function(y){return y[0]<<21|y[1]<<14|y[2]<<7|y[3]},$l=function(y,x,C){var A,D="";for(A=x;A>5,A=y[x+4]<<3,D=y[x+3]&6144;return D|A|C},Gr=function(y,x){return y[x]===73&&y[x+1]===68&&y[x+2]===51?"timed-metadata":y[x]&!0&&(y[x+1]&240)===240?"audio":null},jl=function(y){for(var x=0;x+5>>2]}return null},Po=function(y){var x,C,A,D;x=10,y[5]&64&&(x+=4,x+=Oo(y.subarray(10,14)));do{if(C=Oo(y.subarray(x+4,x+8)),C<1)return null;if(D=String.fromCharCode(y[x],y[x+1],y[x+2],y[x+3]),D==="PRIV"){A=y.subarray(x+10,x+C+10);for(var k=0;k>>2;return J*=4,J+=Z[7]&3,J}break}}x+=10,x+=C}while(x=3;){if(y[D]===73&&y[D+1]===68&&y[D+2]===51){if(y.length-D<10||(A=Hl.parseId3TagSize(y,D),D+A>y.length))break;W={type:"timed-metadata",data:y.subarray(D,D+A)},this.trigger("data",W),D+=A;continue}else if((y[D]&255)===255&&(y[D+1]&240)===240){if(y.length-D<7||(A=Hl.parseAdtsSize(y,D),D+A>y.length))break;Z={type:"audio",data:y.subarray(D,D+A),pts:x,dts:x},this.trigger("data",Z),D+=A;continue}D++}k=y.length-D,k>0?y=y.subarray(D):y=new Uint8Array},this.reset=function(){y=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){y=new Uint8Array,this.trigger("endedtimeline")}},rr.prototype=new gc;var Gl=rr,ph=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],$g=ph,jg=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Hg=jg,xa=t,Mo=Ae,No=Jt,Vl=Os,tn=le,Hn=Ug,Bo=et,gh=Sa,Gg=Ro.H264Stream,Vg=Gl,qg=pc.isLikelyAacData,mc=et.ONE_SECOND_IN_TS,mh=$g,yh=Hg,ql,Ea,zl,Vr,zg=function(y,x){x.stream=y,this.trigger("log",x)},vh=function(y,x){for(var C=Object.keys(x),A=0;A=-1e4&&fe<=J&&(!Ee||re>fe)&&(Ee=we,re=fe)));return Ee?Ee.gop:null},this.alignGopsAtStart_=function(Z){var J,re,fe,Ee,Ue,we,Ge,ot;for(Ue=Z.byteLength,we=Z.nalCount,Ge=Z.duration,J=re=0;Jfe.pts){J++;continue}re++,Ue-=Ee.byteLength,we-=Ee.nalCount,Ge-=Ee.duration}return re===0?Z:re===Z.length?null:(ot=Z.slice(re),ot.byteLength=Ue,ot.duration=Ge,ot.nalCount=we,ot.pts=ot[0].pts,ot.dts=ot[0].dts,ot)},this.alignGopsAtEnd_=function(Z){var J,re,fe,Ee,Ue,we;for(J=D.length-1,re=Z.length-1,Ue=null,we=!1;J>=0&&re>=0;){if(fe=D[J],Ee=Z[re],fe.pts===Ee.pts){we=!0;break}if(fe.pts>Ee.pts){J--;continue}J===D.length-1&&(Ue=re),re--}if(!we&&Ue===null)return null;var Ge;if(we?Ge=re:Ge=Ue,Ge===0)return Z;var ot=Z.slice(Ge),Ri=ot.reduce(function(Cs,fr){return Cs.byteLength+=fr.byteLength,Cs.duration+=fr.duration,Cs.nalCount+=fr.nalCount,Cs},{byteLength:0,duration:0,nalCount:0});return ot.byteLength=Ri.byteLength,ot.duration=Ri.duration,ot.nalCount=Ri.nalCount,ot.pts=ot[0].pts,ot.dts=ot[0].dts,ot},this.alignGopsWith=function(Z){D=Z}},ql.prototype=new xa,Vr=function(y,x){this.numberOfTracks=0,this.metadataStream=x,y=y||{},typeof y.remux<"u"?this.remuxTracks=!!y.remux:this.remuxTracks=!0,typeof y.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=y.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Vr.prototype.init.call(this),this.push=function(C){if(C.content||C.text)return this.pendingCaptions.push(C);if(C.frames)return this.pendingMetadata.push(C);this.pendingTracks.push(C.track),this.pendingBytes+=C.boxes.byteLength,C.track.type==="video"&&(this.videoTrack=C.track,this.pendingBoxes.push(C.boxes)),C.track.type==="audio"&&(this.audioTrack=C.track,this.pendingBoxes.unshift(C.boxes))}},Vr.prototype=new xa,Vr.prototype.flush=function(y){var x=0,C={captions:[],captionStreams:{},metadata:[],info:{}},A,D,k,W=0,Z;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(W=this.videoTrack.timelineStartInfo.pts,yh.forEach(function(J){C.info[J]=this.videoTrack[J]},this)):this.audioTrack&&(W=this.audioTrack.timelineStartInfo.pts,mh.forEach(function(J){C.info[J]=this.audioTrack[J]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?C.type=this.pendingTracks[0].type:C.type="combined",this.emittedTracks+=this.pendingTracks.length,k=Mo.initSegment(this.pendingTracks),C.initSegment=new Uint8Array(k.byteLength),C.initSegment.set(k),C.data=new Uint8Array(this.pendingBytes),Z=0;Z=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Vr.prototype.setRemux=function(y){this.remuxTracks=y},zl=function(y){var x=this,C=!0,A,D;zl.prototype.init.call(this),y=y||{},this.baseMediaDecodeTime=y.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var k={};this.transmuxPipeline_=k,k.type="aac",k.metadataStream=new Hn.MetadataStream,k.aacStream=new Vg,k.audioTimestampRolloverStream=new Hn.TimestampRolloverStream("audio"),k.timedMetadataTimestampRolloverStream=new Hn.TimestampRolloverStream("timed-metadata"),k.adtsStream=new gh,k.coalesceStream=new Vr(y,k.metadataStream),k.headOfPipeline=k.aacStream,k.aacStream.pipe(k.audioTimestampRolloverStream).pipe(k.adtsStream),k.aacStream.pipe(k.timedMetadataTimestampRolloverStream).pipe(k.metadataStream).pipe(k.coalesceStream),k.metadataStream.on("timestamp",function(W){k.aacStream.setTimestamp(W.timeStamp)}),k.aacStream.on("data",function(W){W.type!=="timed-metadata"&&W.type!=="audio"||k.audioSegmentStream||(D=D||{timelineStartInfo:{baseMediaDecodeTime:x.baseMediaDecodeTime},codec:"adts",type:"audio"},k.coalesceStream.numberOfTracks++,k.audioSegmentStream=new Ea(D,y),k.audioSegmentStream.on("log",x.getLogTrigger_("audioSegmentStream")),k.audioSegmentStream.on("timingInfo",x.trigger.bind(x,"audioTimingInfo")),k.adtsStream.pipe(k.audioSegmentStream).pipe(k.coalesceStream),x.trigger("trackinfo",{hasAudio:!!D,hasVideo:!!A}))}),k.coalesceStream.on("data",this.trigger.bind(this,"data")),k.coalesceStream.on("done",this.trigger.bind(this,"done")),vh(this,k)},this.setupTsPipeline=function(){var k={};this.transmuxPipeline_=k,k.type="ts",k.metadataStream=new Hn.MetadataStream,k.packetStream=new Hn.TransportPacketStream,k.parseStream=new Hn.TransportParseStream,k.elementaryStream=new Hn.ElementaryStream,k.timestampRolloverStream=new Hn.TimestampRolloverStream,k.adtsStream=new gh,k.h264Stream=new Gg,k.captionStream=new Hn.CaptionStream(y),k.coalesceStream=new Vr(y,k.metadataStream),k.headOfPipeline=k.packetStream,k.packetStream.pipe(k.parseStream).pipe(k.elementaryStream).pipe(k.timestampRolloverStream),k.timestampRolloverStream.pipe(k.h264Stream),k.timestampRolloverStream.pipe(k.adtsStream),k.timestampRolloverStream.pipe(k.metadataStream).pipe(k.coalesceStream),k.h264Stream.pipe(k.captionStream).pipe(k.coalesceStream),k.elementaryStream.on("data",function(W){var Z;if(W.type==="metadata"){for(Z=W.tracks.length;Z--;)!A&&W.tracks[Z].type==="video"?(A=W.tracks[Z],A.timelineStartInfo.baseMediaDecodeTime=x.baseMediaDecodeTime):!D&&W.tracks[Z].type==="audio"&&(D=W.tracks[Z],D.timelineStartInfo.baseMediaDecodeTime=x.baseMediaDecodeTime);A&&!k.videoSegmentStream&&(k.coalesceStream.numberOfTracks++,k.videoSegmentStream=new ql(A,y),k.videoSegmentStream.on("log",x.getLogTrigger_("videoSegmentStream")),k.videoSegmentStream.on("timelineStartInfo",function(J){D&&!y.keepOriginalTimestamps&&(D.timelineStartInfo=J,k.audioSegmentStream.setEarliestDts(J.dts-x.baseMediaDecodeTime))}),k.videoSegmentStream.on("processedGopsInfo",x.trigger.bind(x,"gopInfo")),k.videoSegmentStream.on("segmentTimingInfo",x.trigger.bind(x,"videoSegmentTimingInfo")),k.videoSegmentStream.on("baseMediaDecodeTime",function(J){D&&k.audioSegmentStream.setVideoBaseMediaDecodeTime(J)}),k.videoSegmentStream.on("timingInfo",x.trigger.bind(x,"videoTimingInfo")),k.h264Stream.pipe(k.videoSegmentStream).pipe(k.coalesceStream)),D&&!k.audioSegmentStream&&(k.coalesceStream.numberOfTracks++,k.audioSegmentStream=new Ea(D,y),k.audioSegmentStream.on("log",x.getLogTrigger_("audioSegmentStream")),k.audioSegmentStream.on("timingInfo",x.trigger.bind(x,"audioTimingInfo")),k.audioSegmentStream.on("segmentTimingInfo",x.trigger.bind(x,"audioSegmentTimingInfo")),k.adtsStream.pipe(k.audioSegmentStream).pipe(k.coalesceStream)),x.trigger("trackinfo",{hasAudio:!!D,hasVideo:!!A})}}),k.coalesceStream.on("data",this.trigger.bind(this,"data")),k.coalesceStream.on("id3Frame",function(W){W.dispatchType=k.metadataStream.dispatchType,x.trigger("id3Frame",W)}),k.coalesceStream.on("caption",this.trigger.bind(this,"caption")),k.coalesceStream.on("done",this.trigger.bind(this,"done")),vh(this,k)},this.setBaseMediaDecodeTime=function(k){var W=this.transmuxPipeline_;y.keepOriginalTimestamps||(this.baseMediaDecodeTime=k),D&&(D.timelineStartInfo.dts=void 0,D.timelineStartInfo.pts=void 0,tn.clearDtsInfo(D),W.audioTimestampRolloverStream&&W.audioTimestampRolloverStream.discontinuity()),A&&(W.videoSegmentStream&&(W.videoSegmentStream.gopCache_=[]),A.timelineStartInfo.dts=void 0,A.timelineStartInfo.pts=void 0,tn.clearDtsInfo(A),W.captionStream.reset()),W.timestampRolloverStream&&W.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(k){D&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(k)},this.setRemux=function(k){var W=this.transmuxPipeline_;y.remux=k,W&&W.coalesceStream&&W.coalesceStream.setRemux(k)},this.alignGopsWith=function(k){A&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(k)},this.getLogTrigger_=function(k){var W=this;return function(Z){Z.stream=k,W.trigger("log",Z)}},this.push=function(k){if(C){var W=qg(k);W&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!W&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),C=!1}this.transmuxPipeline_.headOfPipeline.push(k)},this.flush=function(){C=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},zl.prototype=new xa;var Kg={Transmuxer:zl},Yg=function(y){return y>>>0},Wg=function(y){return("00"+y.toString(16)).slice(-2)},Aa={toUnsigned:Yg,toHexString:Wg},Fo=function(y){var x="";return x+=String.fromCharCode(y[0]),x+=String.fromCharCode(y[1]),x+=String.fromCharCode(y[2]),x+=String.fromCharCode(y[3]),x},bh=Fo,Sh=Aa.toUnsigned,xh=bh,yc=function(y,x){var C=[],A,D,k,W,Z;if(!x.length)return null;for(A=0;A1?A+D:y.byteLength,k===x[0]&&(x.length===1?C.push(y.subarray(A+8,W)):(Z=yc(y.subarray(A+8,W),x.slice(1)),Z.length&&(C=C.concat(Z)))),A=W;return C},Kl=yc,Eh=Aa.toUnsigned,Ca=r.getUint64,Xg=function(y){var x={version:y[0],flags:new Uint8Array(y.subarray(1,4))};return x.version===1?x.baseMediaDecodeTime=Ca(y.subarray(4)):x.baseMediaDecodeTime=Eh(y[4]<<24|y[5]<<16|y[6]<<8|y[7]),x},vc=Xg,Qg=function(y){var x=new DataView(y.buffer,y.byteOffset,y.byteLength),C={version:y[0],flags:new Uint8Array(y.subarray(1,4)),trackId:x.getUint32(4)},A=C.flags[2]&1,D=C.flags[2]&2,k=C.flags[2]&8,W=C.flags[2]&16,Z=C.flags[2]&32,J=C.flags[0]&65536,re=C.flags[0]&131072,fe;return fe=8,A&&(fe+=4,C.baseDataOffset=x.getUint32(12),fe+=4),D&&(C.sampleDescriptionIndex=x.getUint32(fe),fe+=4),k&&(C.defaultSampleDuration=x.getUint32(fe),fe+=4),W&&(C.defaultSampleSize=x.getUint32(fe),fe+=4),Z&&(C.defaultSampleFlags=x.getUint32(fe)),J&&(C.durationIsEmpty=!0),!A&&re&&(C.baseDataOffsetIsMoof=!0),C},Tc=Qg,Ah=function(y){return{isLeading:(y[0]&12)>>>2,dependsOn:y[0]&3,isDependedOn:(y[1]&192)>>>6,hasRedundancy:(y[1]&48)>>>4,paddingValue:(y[1]&14)>>>1,isNonSyncSample:y[1]&1,degradationPriority:y[2]<<8|y[3]}},Uo=Ah,Da=Uo,Zg=function(y){var x={version:y[0],flags:new Uint8Array(y.subarray(1,4)),samples:[]},C=new DataView(y.buffer,y.byteOffset,y.byteLength),A=x.flags[2]&1,D=x.flags[2]&4,k=x.flags[1]&1,W=x.flags[1]&2,Z=x.flags[1]&4,J=x.flags[1]&8,re=C.getUint32(4),fe=8,Ee;for(A&&(x.dataOffset=C.getInt32(fe),fe+=4),D&&re&&(Ee={flags:Da(y.subarray(fe,fe+4))},fe+=4,k&&(Ee.duration=C.getUint32(fe),fe+=4),W&&(Ee.size=C.getUint32(fe),fe+=4),J&&(x.version===1?Ee.compositionTimeOffset=C.getInt32(fe):Ee.compositionTimeOffset=C.getUint32(fe),fe+=4),x.samples.push(Ee),re--);re--;)Ee={},k&&(Ee.duration=C.getUint32(fe),fe+=4),W&&(Ee.size=C.getUint32(fe),fe+=4),Z&&(Ee.flags=Da(y.subarray(fe,fe+4)),fe+=4),J&&(x.version===1?Ee.compositionTimeOffset=C.getInt32(fe):Ee.compositionTimeOffset=C.getUint32(fe),fe+=4),x.samples.push(Ee);return x},$o=Zg,_c={tfdt:vc,trun:$o},bc={parseTfdt:_c.tfdt,parseTrun:_c.trun},Sc=function(y){for(var x=0,C=String.fromCharCode(y[x]),A="";C!=="\0";)A+=C,x++,C=String.fromCharCode(y[x]);return A+=C,A},xc={uint8ToCString:Sc},jo=xc.uint8ToCString,Ch=r.getUint64,Dh=function(y){var x=4,C=y[0],A,D,k,W,Z,J,re,fe;if(C===0){A=jo(y.subarray(x)),x+=A.length,D=jo(y.subarray(x)),x+=D.length;var Ee=new DataView(y.buffer);k=Ee.getUint32(x),x+=4,Z=Ee.getUint32(x),x+=4,J=Ee.getUint32(x),x+=4,re=Ee.getUint32(x),x+=4}else if(C===1){var Ee=new DataView(y.buffer);k=Ee.getUint32(x),x+=4,W=Ch(y.subarray(x)),x+=8,J=Ee.getUint32(x),x+=4,re=Ee.getUint32(x),x+=4,A=jo(y.subarray(x)),x+=A.length,D=jo(y.subarray(x)),x+=D.length}fe=new Uint8Array(y.subarray(x,y.byteLength));var Ue={scheme_id_uri:A,value:D,timescale:k||1,presentation_time:W,presentation_time_delta:Z,event_duration:J,id:re,message_data:fe};return em(C,Ue)?Ue:void 0},Jg=function(y,x,C,A){return y||y===0?y/x:A+C/x},em=function(y,x){var C=x.scheme_id_uri!=="\0",A=y===0&&wh(x.presentation_time_delta)&&C,D=y===1&&wh(x.presentation_time)&&C;return!(y>1)&&A||D},wh=function(y){return y!==void 0||y!==null},tm={parseEmsgBox:Dh,scaleTime:Jg},Ho;typeof window<"u"?Ho=window:typeof s<"u"?Ho=s:typeof self<"u"?Ho=self:Ho={};var ys=Ho,ar=Aa.toUnsigned,wa=Aa.toHexString,fi=Kl,qr=bh,Yl=tm,Ec=Tc,im=$o,La=vc,Ac=r.getUint64,Ia,Wl,Cc,or,zr,Go,Dc,Gn=ys,Lh=Ll.parseId3Frames;Ia=function(y){var x={},C=fi(y,["moov","trak"]);return C.reduce(function(A,D){var k,W,Z,J,re;return k=fi(D,["tkhd"])[0],!k||(W=k[0],Z=W===0?12:20,J=ar(k[Z]<<24|k[Z+1]<<16|k[Z+2]<<8|k[Z+3]),re=fi(D,["mdia","mdhd"])[0],!re)?null:(W=re[0],Z=W===0?12:20,A[J]=ar(re[Z]<<24|re[Z+1]<<16|re[Z+2]<<8|re[Z+3]),A)},x)},Wl=function(y,x){var C;C=fi(x,["moof","traf"]);var A=C.reduce(function(D,k){var W=fi(k,["tfhd"])[0],Z=ar(W[4]<<24|W[5]<<16|W[6]<<8|W[7]),J=y[Z]||9e4,re=fi(k,["tfdt"])[0],fe=new DataView(re.buffer,re.byteOffset,re.byteLength),Ee;re[0]===1?Ee=Ac(re.subarray(4,12)):Ee=fe.getUint32(4);let Ue;return typeof Ee=="bigint"?Ue=Ee/Gn.BigInt(J):typeof Ee=="number"&&!isNaN(Ee)&&(Ue=Ee/J),Ue11?(D.codec+=".",D.codec+=wa(we[9]),D.codec+=wa(we[10]),D.codec+=wa(we[11])):D.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(D.codec)?(we=Ue.subarray(28),Ge=qr(we.subarray(4,8)),Ge==="esds"&&we.length>20&&we[19]!==0?(D.codec+="."+wa(we[19]),D.codec+="."+wa(we[20]>>>2&63).replace(/^0/,"")):D.codec="mp4a.40.2"):D.codec=D.codec.toLowerCase())}var ot=fi(A,["mdia","mdhd"])[0];ot&&(D.timescale=Go(ot)),C.push(D)}),C},Dc=function(y,x=0){var C=fi(y,["emsg"]);return C.map(A=>{var D=Yl.parseEmsgBox(new Uint8Array(A)),k=Lh(D.message_data);return{cueTime:Yl.scaleTime(D.presentation_time,D.timescale,D.presentation_time_delta,x),duration:Yl.scaleTime(D.event_duration,D.timescale),frames:k}})};var Ra={findBox:fi,parseType:qr,timescale:Ia,startTime:Wl,compositionStartTime:Cc,videoTrackIds:or,tracks:zr,getTimescaleFromMediaHeader:Go,getEmsgID3:Dc};const{parseTrun:Ih}=bc,{findBox:Rh}=Ra;var kh=ys,sm=function(y){var x=Rh(y,["moof","traf"]),C=Rh(y,["mdat"]),A=[];return C.forEach(function(D,k){var W=x[k];A.push({mdat:D,traf:W})}),A},Oh=function(y,x,C){var A=x,D=C.defaultSampleDuration||0,k=C.defaultSampleSize||0,W=C.trackId,Z=[];return y.forEach(function(J){var re=Ih(J),fe=re.samples;fe.forEach(function(Ee){Ee.duration===void 0&&(Ee.duration=D),Ee.size===void 0&&(Ee.size=k),Ee.trackId=W,Ee.dts=A,Ee.compositionTimeOffset===void 0&&(Ee.compositionTimeOffset=0),typeof A=="bigint"?(Ee.pts=A+kh.BigInt(Ee.compositionTimeOffset),A+=kh.BigInt(Ee.duration)):(Ee.pts=A+Ee.compositionTimeOffset,A+=Ee.duration)}),Z=Z.concat(fe)}),Z},wc={getMdatTrafPairs:sm,parseSamples:Oh},Lc=ns.discardEmulationPreventionBytes,sn=Ur.CaptionStream,ka=Kl,Ms=vc,Oa=Tc,{getMdatTrafPairs:Ic,parseSamples:Xl}=wc,Ql=function(y,x){for(var C=y,A=0;A0?Ms(fe[0]).baseMediaDecodeTime:0,Ue=ka(W,["trun"]),we,Ge;x===re&&Ue.length>0&&(we=Xl(Ue,Ee,J),Ge=Rc(k,we,re),C[re]||(C[re]={seiNals:[],logs:[]}),C[re].seiNals=C[re].seiNals.concat(Ge.seiNals),C[re].logs=C[re].logs.concat(Ge.logs))}),C},Ph=function(y,x,C){var A;if(x===null)return null;A=Kr(y,x);var D=A[x]||{};return{seiNals:D.seiNals,logs:D.logs,timescale:C}},Zl=function(){var y=!1,x,C,A,D,k,W;this.isInitialized=function(){return y},this.init=function(Z){x=new sn,y=!0,W=Z?Z.isPartial:!1,x.on("data",function(J){J.startTime=J.startPts/D,J.endTime=J.endPts/D,k.captions.push(J),k.captionStreams[J.stream]=!0}),x.on("log",function(J){k.logs.push(J)})},this.isNewInit=function(Z,J){return Z&&Z.length===0||J&&typeof J=="object"&&Object.keys(J).length===0?!1:A!==Z[0]||D!==J[A]},this.parse=function(Z,J,re){var fe;if(this.isInitialized()){if(!J||!re)return null;if(this.isNewInit(J,re))A=J[0],D=re[A];else if(A===null||!D)return C.push(Z),null}else return null;for(;C.length>0;){var Ee=C.shift();this.parse(Ee,J,re)}return fe=Ph(Z,A,D),fe&&fe.logs&&(k.logs=k.logs.concat(fe.logs)),fe===null||!fe.seiNals?k.logs.length?{logs:k.logs,captions:[],captionStreams:[]}:null:(this.pushNals(fe.seiNals),this.flushStream(),k)},this.pushNals=function(Z){if(!this.isInitialized()||!Z||Z.length===0)return null;Z.forEach(function(J){x.push(J)})},this.flushStream=function(){if(!this.isInitialized())return null;W?x.partialFlush():x.flush()},this.clearParsedCaptions=function(){k.captions=[],k.captionStreams={},k.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;x.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){C=[],A=null,D=null,k?this.clearParsedCaptions():k={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},Pa=Zl;const{parseTfdt:nm}=bc,Ei=Kl,{getTimescaleFromMediaHeader:kc}=Ra,{parseSamples:Vn,getMdatTrafPairs:Mh}=wc;var lr=function(){let y=9e4;this.init=function(x){const C=Ei(x,["moov","trak","mdia","mdhd"])[0];C&&(y=kc(C))},this.parseSegment=function(x){const C=[],A=Mh(x);let D=0;return A.forEach(function(k){const W=k.mdat,Z=k.traf,J=Ei(Z,["tfdt"])[0],re=Ei(Z,["tfhd"])[0],fe=Ei(Z,["trun"]);if(J&&(D=nm(J).baseMediaDecodeTime),fe.length&&re){const Ee=Vn(fe,D,re);let Ue=0;Ee.forEach(function(we){const Ge="utf-8",ot=new TextDecoder(Ge),Ri=W.slice(Ue,Ue+we.size);if(Ei(Ri,["vtte"])[0]){Ue+=we.size;return}Ei(Ri,["vttc"]).forEach(function(Ko){const ui=Ei(Ko,["payl"])[0],Yr=Ei(Ko,["sttg"])[0],qn=we.pts/y,pr=(we.pts+we.duration)/y;let Ht,xn;if(ui)try{Ht=ot.decode(ui)}catch(Qi){console.error(Qi)}if(Yr)try{xn=ot.decode(Yr)}catch(Qi){console.error(Qi)}we.duration&&Ht&&C.push({cueText:Ht,start:qn,end:pr,settings:xn})}),Ue+=we.size})}}),C}},Vo=Un,Pc=function(y){var x=y[1]&31;return x<<=8,x|=y[2],x},Ma=function(y){return!!(y[1]&64)},qo=function(y){var x=0;return(y[3]&48)>>>4>1&&(x+=y[4]+1),x},Ns=function(y,x){var C=Pc(y);return C===0?"pat":C===x?"pmt":x?"pes":null},Na=function(y){var x=Ma(y),C=4+qo(y);return x&&(C+=y[C]+1),(y[C+10]&31)<<8|y[C+11]},Ba=function(y){var x={},C=Ma(y),A=4+qo(y);if(C&&(A+=y[A]+1),!!(y[A+5]&1)){var D,k,W;D=(y[A+1]&15)<<8|y[A+2],k=3+D-4,W=(y[A+10]&15)<<8|y[A+11];for(var Z=12+W;Z=y.byteLength)return null;var A=null,D;return D=y[C+7],D&192&&(A={},A.pts=(y[C+9]&14)<<27|(y[C+10]&255)<<20|(y[C+11]&254)<<12|(y[C+12]&255)<<5|(y[C+13]&254)>>>3,A.pts*=4,A.pts+=(y[C+13]&6)>>>1,A.dts=A.pts,D&64&&(A.dts=(y[C+14]&14)<<27|(y[C+15]&255)<<20|(y[C+16]&254)<<12|(y[C+17]&255)<<5|(y[C+18]&254)>>>3,A.dts*=4,A.dts+=(y[C+18]&6)>>>1)),A},vs=function(y){switch(y){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},Bs=function(y){for(var x=4+qo(y),C=y.subarray(x),A=0,D=0,k=!1,W;D3&&(W=vs(C[D+3]&31),W==="slice_layer_without_partitioning_rbsp_idr"&&(k=!0)),k},ur={parseType:Ns,parsePat:Na,parsePmt:Ba,parsePayloadUnitStartIndicator:Ma,parsePesType:Jl,parsePesTime:zo,videoPacketContainsKeyFrame:Bs},nn=Un,as=$r.handleRollover,mt={};mt.ts=ur,mt.aac=pc;var cr=et.ONE_SECOND_IN_TS,Vi=188,Fs=71,Nh=function(y,x){for(var C=0,A=Vi,D,k;A=0;){if(y[A]===Fs&&(y[D]===Fs||D===y.byteLength)){if(k=y.subarray(A,D),W=mt.ts.parseType(k,x.pid),W==="pes"&&(Z=mt.ts.parsePesType(k,x.table),J=mt.ts.parsePayloadUnitStartIndicator(k),Z==="audio"&&J&&(re=mt.ts.parsePesTime(k),re&&(re.type="audio",C.audio.push(re),fe=!0))),fe)break;A-=Vi,D-=Vi;continue}A--,D--}},ii=function(y,x,C){for(var A=0,D=Vi,k,W,Z,J,re,fe,Ee,Ue,we=!1,Ge={data:[],size:0};D=0;){if(y[A]===Fs&&y[D]===Fs){if(k=y.subarray(A,D),W=mt.ts.parseType(k,x.pid),W==="pes"&&(Z=mt.ts.parsePesType(k,x.table),J=mt.ts.parsePayloadUnitStartIndicator(k),Z==="video"&&J&&(re=mt.ts.parsePesTime(k),re&&(re.type="video",C.video.push(re),we=!0))),we)break;A-=Vi,D-=Vi;continue}A--,D--}},xt=function(y,x){if(y.audio&&y.audio.length){var C=x;(typeof C>"u"||isNaN(C))&&(C=y.audio[0].dts),y.audio.forEach(function(k){k.dts=as(k.dts,C),k.pts=as(k.pts,C),k.dtsTime=k.dts/cr,k.ptsTime=k.pts/cr})}if(y.video&&y.video.length){var A=x;if((typeof A>"u"||isNaN(A))&&(A=y.video[0].dts),y.video.forEach(function(k){k.dts=as(k.dts,A),k.pts=as(k.pts,A),k.dtsTime=k.dts/cr,k.ptsTime=k.pts/cr}),y.firstKeyFrame){var D=y.firstKeyFrame;D.dts=as(D.dts,A),D.pts=as(D.pts,A),D.dtsTime=D.dts/cr,D.ptsTime=D.pts/cr}}},dr=function(y){for(var x=!1,C=0,A=null,D=null,k=0,W=0,Z;y.length-W>=3;){var J=mt.aac.parseType(y,W);switch(J){case"timed-metadata":if(y.length-W<10){x=!0;break}if(k=mt.aac.parseId3TagSize(y,W),k>y.length){x=!0;break}D===null&&(Z=y.subarray(W,W+k),D=mt.aac.parseAacTimestamp(Z)),W+=k;break;case"audio":if(y.length-W<7){x=!0;break}if(k=mt.aac.parseAdtsSize(y,W),k>y.length){x=!0;break}A===null&&(Z=y.subarray(W,W+k),A=mt.aac.parseSampleRate(Z)),C++,W+=k;break;default:W++;break}if(x)return null}if(A===null||D===null)return null;var re=cr/A,fe={audio:[{type:"audio",dts:D,pts:D},{type:"audio",dts:D+C*1024*re,pts:D+C*1024*re}]};return fe},Us=function(y){var x={pid:null,table:null},C={};Nh(y,x);for(var A in x.table)if(x.table.hasOwnProperty(A)){var D=x.table[A];switch(D){case nn.H264_STREAM_TYPE:C.video=[],ii(y,x,C),C.video.length===0&&delete C.video;break;case nn.ADTS_STREAM_TYPE:C.audio=[],Fi(y,x,C),C.audio.length===0&&delete C.audio;break}}return C},Mc=function(y,x){var C=mt.aac.isLikelyAacData(y),A;return C?A=dr(y):A=Us(y),!A||!A.audio&&!A.video?null:(xt(A,x),A)},hr={inspect:Mc,parseAudioPes_:Fi};const Bh=function(y,x){x.on("data",function(C){const A=C.initSegment;C.initSegment={data:A.buffer,byteOffset:A.byteOffset,byteLength:A.byteLength};const D=C.data;C.data=D.buffer,y.postMessage({action:"data",segment:C,byteOffset:D.byteOffset,byteLength:D.byteLength},[C.data])}),x.on("done",function(C){y.postMessage({action:"done"})}),x.on("gopInfo",function(C){y.postMessage({action:"gopInfo",gopInfo:C})}),x.on("videoSegmentTimingInfo",function(C){const A={start:{decode:et.videoTsToSeconds(C.start.dts),presentation:et.videoTsToSeconds(C.start.pts)},end:{decode:et.videoTsToSeconds(C.end.dts),presentation:et.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:et.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=et.videoTsToSeconds(C.prependedContentDuration)),y.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:A})}),x.on("audioSegmentTimingInfo",function(C){const A={start:{decode:et.videoTsToSeconds(C.start.dts),presentation:et.videoTsToSeconds(C.start.pts)},end:{decode:et.videoTsToSeconds(C.end.dts),presentation:et.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:et.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(A.prependedContentDuration=et.videoTsToSeconds(C.prependedContentDuration)),y.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:A})}),x.on("id3Frame",function(C){y.postMessage({action:"id3Frame",id3Frame:C})}),x.on("caption",function(C){y.postMessage({action:"caption",caption:C})}),x.on("trackinfo",function(C){y.postMessage({action:"trackinfo",trackInfo:C})}),x.on("audioTimingInfo",function(C){y.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:et.videoTsToSeconds(C.start),end:et.videoTsToSeconds(C.end)}})}),x.on("videoTimingInfo",function(C){y.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:et.videoTsToSeconds(C.start),end:et.videoTsToSeconds(C.end)}})}),x.on("log",function(C){y.postMessage({action:"log",log:C})})};class Nc{constructor(x,C){this.options=C||{},this.self=x,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new Kg.Transmuxer(this.options),Bh(this.self,this.transmuxer)}pushMp4Captions(x){this.captionParser||(this.captionParser=new Pa,this.captionParser.init());const C=new Uint8Array(x.data,x.byteOffset,x.byteLength),A=this.captionParser.parse(C,x.trackIds,x.timescales);this.self.postMessage({action:"mp4Captions",captions:A&&A.captions||[],logs:A&&A.logs||[],data:C.buffer},[C.buffer])}initMp4WebVttParser(x){this.webVttParser||(this.webVttParser=new lr);const C=new Uint8Array(x.data,x.byteOffset,x.byteLength);this.webVttParser.init(C)}getMp4WebVttText(x){this.webVttParser||(this.webVttParser=new lr);const C=new Uint8Array(x.data,x.byteOffset,x.byteLength),A=this.webVttParser.parseSegment(C);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:A||[],data:C.buffer},[C.buffer])}probeMp4StartTime({timescales:x,data:C}){const A=Ra.startTime(x,C);this.self.postMessage({action:"probeMp4StartTime",startTime:A,data:C},[C.buffer])}probeMp4Tracks({data:x}){const C=Ra.tracks(x);this.self.postMessage({action:"probeMp4Tracks",tracks:C,data:x},[x.buffer])}probeEmsgID3({data:x,offset:C}){const A=Ra.getEmsgID3(x,C);this.self.postMessage({action:"probeEmsgID3",id3Frames:A,emsgData:x},[x.buffer])}probeTs({data:x,baseStartTime:C}){const A=typeof C=="number"&&!isNaN(C)?C*et.ONE_SECOND_IN_TS:void 0,D=hr.inspect(x,A);let k=null;D&&(k={hasVideo:D.video&&D.video.length===2||!1,hasAudio:D.audio&&D.audio.length===2||!1},k.hasVideo&&(k.videoStart=D.video[0].ptsTime),k.hasAudio&&(k.audioStart=D.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:k,data:x},[x.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(x){const C=new Uint8Array(x.data,x.byteOffset,x.byteLength);this.transmuxer.push(C)}reset(){this.transmuxer.reset()}setTimestampOffset(x){const C=x.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(et.secondsToVideoTs(C)))}setAudioAppendStart(x){this.transmuxer.setAudioAppendStart(Math.ceil(et.secondsToVideoTs(x.appendStart)))}setRemux(x){this.transmuxer.setRemux(x.remux)}flush(x){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(x){this.transmuxer.alignGopsWith(x.gopsToAlignWith.slice())}}self.onmessage=function(y){if(y.data.action==="init"&&y.data.options){this.messageHandlers=new Nc(self,y.data.options);return}this.messageHandlers||(this.messageHandlers=new Nc(self)),y.data&&y.data.action&&y.data.action!=="init"&&this.messageHandlers[y.data.action]&&this.messageHandlers[y.data.action](y.data)}}));var W3=CD(Y3);const X3=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:o,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:o,metadata:u});const f=s.data.segment.boxes||{data:s.data.segment.data},g={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"&&(g.videoFrameDtsTime=c),typeof d<"u"&&(g.videoFramePtsTime=d),t(g)},Q3=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},Z3=(s,e)=>{e.gopInfo=s.data.gopInfo},LD=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:o,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:g,onId3:m,onCaptions:v,onDone:_,onEndedTimeline:b,onTransmuxerLog:E,isEndOfTimeline:w,segment:L,triggerSegmentEventFn:I}=s,F={buffer:[]};let B=w;const V=q=>{e.currentTransmux===s&&(q.data.action==="data"&&X3(q,F,o),q.data.action==="trackinfo"&&u(q.data.trackInfo),q.data.action==="gopInfo"&&Z3(q,F),q.data.action==="audioTimingInfo"&&c(q.data.audioTimingInfo),q.data.action==="videoTimingInfo"&&d(q.data.videoTimingInfo),q.data.action==="videoSegmentTimingInfo"&&f(q.data.videoSegmentTimingInfo),q.data.action==="audioSegmentTimingInfo"&&g(q.data.audioSegmentTimingInfo),q.data.action==="id3Frame"&&m([q.data.id3Frame],q.data.id3Frame.dispatchType),q.data.action==="caption"&&v(q.data.caption),q.data.action==="endedtimeline"&&(B=!1,b()),q.data.action==="log"&&E(q.data.log),q.data.type==="transmuxed"&&(B||(e.onmessage=null,Q3({transmuxedData:F,callback:_}),ID(e))))},N=()=>{const q={message:"Received an error message from the transmuxer worker",metadata:{errorType:ye.Error.StreamingFailedToTransmuxSegment,segmentInfo:dl({segment:L})}};_(null,q)};if(e.onmessage=V,e.onerror=N,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(n)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:n}),typeof r<"u"&&e.postMessage({action:"setRemux",remux:r}),t.byteLength){const q=t instanceof ArrayBuffer?t:t.buffer,R=t instanceof ArrayBuffer?0:t.byteOffset;I({type:"segmenttransmuxingstart",segment:L}),e.postMessage({action:"push",data:q,byteOffset:R,byteLength:t.byteLength},[q])}w&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},ID=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():LD(s.currentTransmux))},WE=(s,e)=>{s.postMessage({action:e}),ID(s)},RD=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,WE(e,s);return}e.transmuxQueue.push(WE.bind(null,e,s))},J3=s=>{RD("reset",s)},e4=s=>{RD("endTimeline",s)},kD=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,LD(s);return}s.transmuxer.transmuxQueue.push(s)},t4=s=>{const e=new W3;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 xy={reset:J3,endTimeline:e4,transmux:kD,createTransmuxer:t4};const Fu=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=Mi({},s,{endAction:null,transmuxer:null,callback:null}),r=o=>{o.data.action===t&&(e.removeEventListener("message",r),o.data.data&&(o.data.data=new Uint8Array(o.data.data,s.byteOffset||0,s.byteLength||o.data.data.byteLength),s.data&&(s.data=o.data.data)),i(o.data))};if(e.addEventListener("message",r),s.data){const o=s.data instanceof ArrayBuffer;n.byteOffset=o?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[o?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},wr={FAILURE:2,TIMEOUT:-101,ABORTED:-102},OD="wvtt",wv=s=>{s.forEach(e=>{e.abort()})},i4=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),s4=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},jT=(s,e)=>{const{requestType:t}=e,i=Tl({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:wr.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:wr.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:wr.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:wr.FAILURE,xhr:e,metadata:i}:null},XE=(s,e,t,i)=>(n,r)=>{const o=r.response,u=jT(n,r);if(u)return t(u,s);if(o.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:wr.FAILURE,xhr:r},s);const c=new DataView(o),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let g=0;g{e===OD&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},r4=(s,e,t)=>{e===OD&&Fu({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},PD=(s,e)=>{const t=cT(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:wr.FAILURE,metadata:{mediaType:n}})}Fu({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"&&n4(s,r.codec))}),e(null))})},a4=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=jT(i,n);if(r)return e(r,s);const o=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=o,e(null,s);s.map.bytes=o,PD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},o4=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const o=jT(n,r);if(o)return e(o,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:z3(r.responseText.substring(s.lastReachedChar||0));return s.stats=i4(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},l4=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})=>{const _=s.map&&s.map.tracks||{},b=!!(_.audio&&_.video);let E=i.bind(null,s,"audio","start");const w=i.bind(null,s,"audio","end");let L=i.bind(null,s,"video","start");const I=i.bind(null,s,"video","end"),F=()=>kD({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:b,onData:B=>{B.type=B.type==="combined"?"video":B.type,f(s,B)},onTrackInfo:B=>{t&&(b&&(B.isMuxed=!0),t(s,B))},onAudioTimingInfo:B=>{E&&typeof B.start<"u"&&(E(B.start),E=null),w&&typeof B.end<"u"&&w(B.end)},onVideoTimingInfo:B=>{L&&typeof B.start<"u"&&(L(B.start),L=null),I&&typeof B.end<"u"&&I(B.end)},onVideoSegmentTimingInfo:B=>{const V={pts:{start:B.start.presentation,end:B.end.presentation},dts:{start:B.start.decode,end:B.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),n(B)},onAudioSegmentTimingInfo:B=>{const V={pts:{start:B.start.pts,end:B.end.pts},dts:{start:B.start.dts,end:B.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:V}),r(B)},onId3:(B,V)=>{o(s,B,V)},onCaptions:B=>{u(s,[B])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:m,onDone:(B,V)=>{g&&(B.type=B.type==="combined"?"video":B.type,v({type:"segmenttransmuxingcomplete",segment:s}),g(V,s,B))},segment:s,triggerSegmentEventFn:v});Fu({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:B=>{s.bytes=e=B.data;const V=B.result;V&&(t(s,{hasAudio:V.hasAudio,hasVideo:V.hasVideo,isMuxed:b}),t=null),F()}})},MD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})=>{let _=new Uint8Array(e);if(LM(_)){s.isFmp4=!0;const{tracks:b}=s.map;if(b.text&&(!b.audio||!b.video)){f(s,{data:_,type:"text"}),r4(s,b.text.codec,g);return}const w={isFmp4:!0,hasVideo:!!b.video,hasAudio:!!b.audio};b.audio&&b.audio.codec&&b.audio.codec!=="enca"&&(w.audioCodec=b.audio.codec),b.video&&b.video.codec&&b.video.codec!=="encv"&&(w.videoCodec=b.video.codec),b.video&&b.audio&&(w.isMuxed=!0),t(s,w);const L=(I,F)=>{f(s,{data:_,type:w.hasAudio&&!w.isMuxed?"audio":"video"}),F&&F.length&&o(s,F),I&&I.length&&u(s,I),g(null,s,{})};Fu({action:"probeMp4StartTime",timescales:s.map.timescales,data:_,transmuxer:s.transmuxer,callback:({data:I,startTime:F})=>{e=I.buffer,s.bytes=_=I,w.hasAudio&&!w.isMuxed&&i(s,"audio","start",F),w.hasVideo&&i(s,"video","start",F),Fu({action:"probeEmsgID3",data:_,transmuxer:s.transmuxer,offset:F,callback:({emsgData:B,id3Frames:V})=>{if(e=B.buffer,s.bytes=_=B,!b.video||!B.byteLength||!s.transmuxer){L(void 0,V);return}Fu({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:_,timescales:s.map.timescales,trackIds:[b.video.id],callback:N=>{e=N.data.buffer,s.bytes=_=N.data,N.logs.forEach(function(q){m(jt(q,{stream:"mp4CaptionParser"}))}),L(N.captions,V)}})}})}});return}if(!s.transmuxer){g(null,s,{});return}if(typeof s.container>"u"&&(s.container=cT(_)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),g(null,s,{});return}l4({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})},ND=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},o){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;o(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=dl({segment:n}),g={message:d,metadata:{error:new Error(d),errorType:ye.Error.StreamingFailedToDecryptSegment,segmentInfo:f,keyInfo:{uri:n.key.resolvedUri||n.map.key.resolvedUri}}};r(g,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(_D({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},u4=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),ND({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:g},_=>{e.bytes=_,v({type:"segmentdecryptioncomplete",segment:e}),MD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})})},c4=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})=>{let _=0,b=!1;return(E,w)=>{if(!b){if(E)return b=!0,wv(s),g(E,w);if(_+=1,_===s.length){const L=function(){if(w.encryptedBytes)return u4({decryptionWorker:e,segment:w,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v});MD({segment:w,bytes:w.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:g,onTransmuxerLog:m,triggerSegmentEventFn:v})};if(w.endOfAllRequests=Date.now(),w.map&&w.map.encryptedBytes&&!w.map.bytes)return v({type:"segmentdecryptionstart",segment:w}),ND({decryptionWorker:e,id:w.requestId+"-init",encryptedBytes:w.map.encryptedBytes,key:w.map.key,segment:w,doneFn:g},I=>{w.map.bytes=I,v({type:"segmentdecryptioncomplete",segment:w}),PD(w,F=>{if(F)return wv(s),g(F,w);L()})});L()}}}},d4=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},h4=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:o,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>g=>{if(!g.target.aborted)return s.stats=jt(s.stats,s4(g)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(g,s)},f4=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:g,isEndOfTimeline:m,endedTimelineFn:v,dataFn:_,doneFn:b,onTransmuxerLog:E,triggerSegmentEventFn:w})=>{const L=[],I=c4({activeXhrs:L,decryptionWorker:t,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:g,isEndOfTimeline:m,endedTimelineFn:v,dataFn:_,doneFn:b,onTransmuxerLog:E,triggerSegmentEventFn:w});if(i.key&&!i.key.bytes){const q=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&q.push(i.map.key);const R=jt(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),P=XE(i,q,I,w),z={uri:i.key.resolvedUri};w({type:"segmentkeyloadstart",segment:i,keyInfo:z});const ee=s(R,P);L.push(ee)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const ee=jt(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),ie=XE(i,[i.map.key],I,w),Q={uri:i.map.key.resolvedUri};w({type:"segmentkeyloadstart",segment:i,keyInfo:Q});const oe=s(ee,ie);L.push(oe)}const R=jt(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:Cv(i.map),requestType:"segment-media-initialization"}),P=a4({segment:i,finishProcessingFn:I,triggerSegmentEventFn:w});w({type:"segmentloadstart",segment:i});const z=s(R,P);L.push(z)}const F=jt(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:Cv(i),requestType:"segment"}),B=o4({segment:i,finishProcessingFn:I,responseType:F.responseType,triggerSegmentEventFn:w});w({type:"segmentloadstart",segment:i});const V=s(F,B);V.addEventListener("progress",h4({segment:i,progressFn:r,trackInfoFn:o,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:g,isEndOfTimeline:m,endedTimelineFn:v,dataFn:_})),L.push(V);const N={};return L.forEach(q=>{q.addEventListener("loadend",d4({loadendState:N,abortFn:n}))}),()=>wv(L)},jf=Nn("PlaylistSelector"),QE=function(s){if(!s||!s.playlist)return;const e=s.playlist;return JSON.stringify({id:e.id,bandwidth:s.bandwidth,width:s.width,height:s.height,codecs:e.attributes&&e.attributes.CODECS||""})},Uu=function(s,e){if(!s)return"";const t=ne.getComputedStyle(s);return t?t[e]:""},$u=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})},HT=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||ne.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||ne.Number.MAX_VALUE,t-i},p4=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||ne.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||ne.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let BD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:o,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:o};let d=e.playlists;Ws.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(N=>{let q;const R=N.attributes&&N.attributes.RESOLUTION&&N.attributes.RESOLUTION.width,P=N.attributes&&N.attributes.RESOLUTION&&N.attributes.RESOLUTION.height;return q=N.attributes&&N.attributes.BANDWIDTH,q=q||ne.Number.MAX_VALUE,{bandwidth:q,width:R,height:P,playlist:N}});$u(f,(N,q)=>N.bandwidth-q.bandwidth),f=f.filter(N=>!Ws.isIncompatible(N.playlist));let g=f.filter(N=>Ws.isEnabled(N.playlist));g.length||(g=f.filter(N=>!Ws.isDisabled(N.playlist)));const m=g.filter(N=>N.bandwidth*ts.BANDWIDTH_VARIANCEN.bandwidth===v.bandwidth)[0];if(o===!1){const N=_||g[0]||f[0];if(N&&N.playlist){let q="sortedPlaylistReps";return _&&(q="bandwidthBestRep"),g[0]&&(q="enabledPlaylistReps"),jf(`choosing ${QE(N)} using ${q} with options`,c),N.playlist}return jf("could not choose a playlist with options",c),null}const b=m.filter(N=>N.width&&N.height);$u(b,(N,q)=>N.width-q.width);const E=b.filter(N=>N.width===i&&N.height===n);v=E[E.length-1];const w=E.filter(N=>N.bandwidth===v.bandwidth)[0];let L,I,F;w||(L=b.filter(N=>r==="cover"?N.width>i&&N.height>n:N.width>i||N.height>n),I=L.filter(N=>N.width===L[0].width&&N.height===L[0].height),v=I[I.length-1],F=I.filter(N=>N.bandwidth===v.bandwidth)[0]);let B;if(u.leastPixelDiffSelector){const N=b.map(q=>(q.pixelDiff=Math.abs(q.width-i)+Math.abs(q.height-n),q));$u(N,(q,R)=>q.pixelDiff===R.pixelDiff?R.bandwidth-q.bandwidth:q.pixelDiff-R.pixelDiff),B=N[0]}const V=B||F||w||_||g[0]||f[0];if(V&&V.playlist){let N="sortedPlaylistReps";return B?N="leastPixelDiffRep":F?N="resolutionPlusOneRep":w?N="resolutionBestRep":_?N="bandwidthBestRep":g[0]&&(N="enabledPlaylistReps"),jf(`choosing ${QE(V)} using ${N} with options`,c),V.playlist}return jf("could not choose a playlist with options",c),null};const ZE=function(){let s=this.useDevicePixelRatio&&ne.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),BD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(Uu(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(Uu(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?Uu(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},g4=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&&ne.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),BD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(Uu(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(Uu(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?Uu(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},m4=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:o,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(_=>!Ws.isIncompatible(_));let f=d.filter(Ws.isEnabled);f.length||(f=d.filter(_=>!Ws.isDisabled(_)));const m=f.filter(Ws.hasAttribute.bind(null,"BANDWIDTH")).map(_=>{const E=c.getSyncPoint(_,n,u,t)?1:2,L=Ws.estimateSegmentRequestTime(r,i,_)*E-o;return{playlist:_,rebufferingImpact:L}}),v=m.filter(_=>_.rebufferingImpact<=0);return $u(v,(_,b)=>HT(b.playlist,_.playlist)),v.length?v[0]:($u(m,(_,b)=>_.rebufferingImpact-b.rebufferingImpact),m[0]||null)},y4=function(){const s=this.playlists.main.playlists.filter(Ws.isEnabled);return $u(s,(t,i)=>HT(t,i)),s.filter(t=>!!Md(this.playlists.main,t).video)[0]||null},v4=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 FD(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const T4=function(s,e,t){if(!s[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const n=e.textTracks().getTrackById(i);if(n)s[t]=n;else{const r=e.options_.vhs&&e.options_.vhs.captionServices||{};let o=t,u=t,c=!1;const d=r[i];d&&(o=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:o,language:u},!1).track}}},_4=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=ne.WebKitDataCue||ne.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(o=>{const u=new i(n.startTime+t,n.endTime+t,o.text);u.line=o.line,u.align="left",u.position=o.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},b4=function(s){Object.defineProperties(s.frame,{id:{get(){return ye.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return ye.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return ye.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},S4=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=ne.WebKitDataCue||ne.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const g=f.cueTime+t;typeof g!="number"||ne.isNaN(g)||g<0||!(g<1/0)||!f.frames||!f.frames.length||f.frames.forEach(m=>{const v=new n(g,g,m.value||m.url||m.data||"");v.frame=m,v.value=m,b4(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const o=r.cues,u=[];for(let f=0;f{const m=f[g.startTime]||[];return m.push(g),f[g.startTime]=m,f},{}),d=Object.keys(c).sort((f,g)=>Number(f)-Number(g));d.forEach((f,g)=>{const m=c[f],v=isFinite(i)?i:f,_=Number(d[g+1])||v;m.forEach(b=>{b.endTime=_})})},x4={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"},E4=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),A4=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=ne.WebKitDataCue||ne.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(E4.has(r))continue;const o=new i(n.startTime,n.endTime,"");o.id=n.id,o.type="com.apple.quicktime.HLS",o.value={key:x4[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(o.value.data=new Uint8Array(o.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(o)}n.processDateRange()})},JE=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,ye.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},Ad=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)},C4=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}},D4=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*fl.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},w4=(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)},L4=(s,e,t,i)=>{const n=Math.ceil((e-i)*fl.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*fl.ONE_SECOND_IN_TS),o=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return o;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),o.splice(c,u-c+1),o},I4=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]},yd=1,k4=500,e1=s=>typeof s=="number"&&isFinite(s),Hf=1/60,O4=(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,P4=(s,e,t)=>{let i=e-ts.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},_u=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:o,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,g=u.length-1;let m="mediaIndex/partIndex increment";s.getMediaInfoForTime?m=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(m="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(m+=` with independent ${s.independent}`);const v=typeof d=="number",_=s.segment.uri?"segment":"pre-segment",b=v?iD({preloadSegment:i})-1:0;return`${_} [${r+c}/${r+g}]`+(v?` part [${d}/${b}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(v?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${f}] selected by [${m}] playlist [${o}]`},t1=s=>`${s}TimingInfo`,M4=({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},N4=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)},B4=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(Lv({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&N4(s.timelineChangeController_)){if(B4(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},F4=s=>{let e=0;return["video","audio"].forEach(function(t){const i=s[`${t}TimingInfo`];if(!i)return;const{start:n,end:r}=i;let o;typeof n=="bigint"||typeof r=="bigint"?o=ne.BigInt(r)-ne.BigInt(n):typeof n=="number"&&typeof r=="number"&&(o=r-n),typeof o<"u"&&o>e&&(e=o)}),typeof e=="bigint"&&es?Math.round(s)>e+Cr:!1,U4=(s,e)=>{if(e!=="hls")return null;const t=F4({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=i1({segmentDuration:t,maxDuration:i*2}),r=i1({segmentDuration:t,maxDuration:i}),o=`Segment with index ${s.mediaIndex} from playlist ${s.playlist.id} has a duration of ${t} when the reported duration is ${s.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return n||r?{severity:n?"warn":"info",message:o}:null},dl=({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 Iv extends ye.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_=Nn(`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_():no(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(Mi({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():no(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(Mi({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():no(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():no(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return xy.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_&&ne.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,ne.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_&&xy.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return ss();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=$p(e);let n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e}segmentKey(e,t=!1){if(!e)return null;const i=bD(e);let n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(n||e).resolvedUri};return n&&(r.bytes=n.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: +currentTime: ${this.currentTime_()} +bufferedEnd: ${by(this.buffered_())} +`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const o=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${o}]`),this.mediaIndex!==null)if(this.mediaIndex-=o,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const u=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!u.parts||!u.parts.length||!u.parts[this.partIndex])){const c=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=c}}n&&(n.mediaIndex-=o,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(ne.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_&&xy.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},n=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1;const o=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,o)),(n||this.loaderType_==="main")&&(this.gopBuffer_=L4(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,o));for(const u in this.inbandTextTracks_)Ad(e,t,this.inbandTextTracks_[u]);Ad(e,t,this.segmentMetadataTrack_),o()}monitorBuffer_(){this.checkBufferTimeout_&&ne.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=ne.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&ne.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=ne.setTimeout(this.monitorBufferTick_.bind(this),k4)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:dl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const n=typeof e=="number"&&t.segments[e],r=e+1===t.segments.length,o=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&o}chooseNextRequest_(){const e=this.buffered_(),t=by(e)||0,i=BT(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),o=this.playlist_.segments;if(!o.length||n||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const u={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(u.isSyncRequest)u.mediaIndex=R4(this.currentTimeline_,o,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const m=o[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=m.end?m.end:t,m.parts&&m.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let m,v,_;const b=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: +For TargetTime: ${b}. +CurrentTime: ${this.currentTime_()} +BufferedEnd: ${t} +Fetch At Buffer: ${this.fetchAtBuffer_} +`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const E=this.getSyncInfoFromMediaSequenceSync_(b);if(!E){const w="No sync info found while using media sequence sync";return this.error({message:w,metadata:{errorType:ye.Error.StreamingFailedToSelectNextSegment,error:new Error(w)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${E.start} --> ${E.end})`),m=E.segmentIndex,v=E.partIndex,_=E.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const E=Ws.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:b,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});m=E.segmentIndex,v=E.partIndex,_=E.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${b}`:`currentTime ${b}`,u.mediaIndex=m,u.startOfSegment=_,u.partIndex=v,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${u.mediaIndex} `)}const c=o[u.mediaIndex];let d=c&&typeof u.partIndex=="number"&&c.parts&&c.parts[u.partIndex];if(!c||typeof u.partIndex=="number"&&!d)return null;typeof u.partIndex!="number"&&c.parts&&(u.partIndex=0,d=c.parts[0]);const f=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!f&&!d.independent)if(u.partIndex===0){const m=o[u.mediaIndex-1],v=m.parts&&m.parts.length&&m.parts[m.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=m.parts.length-1,u.independent="previous segment")}else c.parts[u.partIndex-1].independent&&(u.partIndex-=1,u.independent="previous part");const g=this.mediaSource_&&this.mediaSource_.readyState==="ended";return u.mediaIndex>=o.length-1&&g&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,u.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(u))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const n=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return n?(n.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),n):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:r,isSyncRequest:o,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],g=typeof u=="number"&&f.parts[u],m={requestId:"segment-loader-"+Math.random(),uri:g&&g.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:g?u:null,isSyncRequest:o,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:f.timeline,duration:g&&g.duration||f.duration,segment:f,part:g,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},v=typeof c<"u"?c:this.isPendingTimestampOffset_;m.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const _=by(this.sourceUpdater_.audioBuffered());return typeof _=="number"&&(m.audioAppendStart=_-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(m.gopsToAlignWith=D4(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),m}timestampOffsetForSegment_(e){return M4(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=Ws.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),o=s3(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=o)return;const u=m4({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:o,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-o-u.rebufferingImpact;let f=.5;o<=Cr&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[o.stream]=r[o.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[o.stream];u.startTime=Math.min(u.startTime,o.startTime+n),u.endTime=Math.max(u.endTime,o.endTime+n),u.captions.push(o)}),Object.keys(r).forEach(o=>{const{startTime:u,endTime:c,captions:d}=r[o],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${o}`),T4(f,this.vhs_.tech_,o),Ad(u,c,f[o]),_4({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_()?!Lv({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||Lv({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_()){no(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[t1(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let o;r&&(o=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:r,firstVideoFrameTimeForData:o,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const n=this.chooseNextRequest_();if(n.mediaIndex!==i.mediaIndex||n.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:n}){if(i){const r=$p(i);if(this.activeInitSegmentId_===r)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=r}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=n,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},n){const r=this.sourceUpdater_.audioBuffered(),o=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+pl(r).join(", ")),o.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+pl(o).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=o.length?o.start(0):0,f=o.length?o.end(o.length-1):0;if(c-u<=yd&&f-d<=yd){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${pl(r).join(", ")}, video buffer: ${pl(o).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const m=this.currentTime_()-yd;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${m}`),this.remove(0,m,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${yd}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=ne.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},yd*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===fD){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:ye.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=v4({bytes:c,segments:u})}const o={segmentInfo:dl({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:o}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const n=this.pendingSegment_.segment,r=`${e}TimingInfo`;n[r]||(n[r]={}),n[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[r].transmuxedPresentationStart=i.start.presentation,n[r].transmuxedDecodeStart=i.start.decode,n[r].transmuxedPresentationEnd=i.end.presentation,n[r].transmuxedDecodeEnd=i.end.decode,n[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:n}=t;if(!n||!n.byteLength||i==="audio"&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:n})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){no(this),this.loadQueue_.push(()=>{const t=Mi({},e,{forceTimestampOffset:!0});Mi(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),n=this.mediaIndex!==null,r=e.timeline!==this.currentTimeline_&&e.timeline>0,o=i||n&&r;this.logger_(`Requesting +${FD(e.uri)} +${_u(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=f4({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:o,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:u,level:c,stream:d})=>{this.logger_(`${_u(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:g})=>{const v={segmentInfo:dl({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),g&&(v.timingInfo=g),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=P4(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,n=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,o={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:n,isMediaInitialization:r},u=e.playlist.segments[e.mediaIndex-1];if(u&&u.timeline===t.timeline&&(u.videoTimingInfo?o.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(o.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);o.key=this.segmentKey(t.key),o.key.iv=c}return t.map&&(o.map=this.initSegmentForMap(t.map)),o}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e"u"||d.end!==n+r?n:u.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:n,isMuxed:r}=t,o=this.loaderType_==="main"&&n,u=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}o&&e.waitingOnAppends++,u&&e.waitingOnAppends++,o&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),u&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=O4(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:dl({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=U4(e,this.sourceType_);if(t&&(t.severity==="warn"?ye.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 ${_u(e)}`);return}this.logger_(`Appended ${_u(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,n=e.part,r=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,o=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||o){this.logger_(`bad ${r?"segment":"part"} ${_u(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())},$4=["video","audio"],Rv=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},j4=(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(),ju("audio",e),ju("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||Rv(s,e))){if(i.type!==s){if(t=j4(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,ju(s,e);return}}},$D=(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)},xr=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,cn={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(xr(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(o){n.logger_(`Error with code ${o.code} `+(o.code===fD?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(o)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(xr(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`];xr(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){ye.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){ye.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(xr(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){ye.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=UD(s),n=zu(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($D(s,e),!!xr(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){ye.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],n=zu(s);if(!xr(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),o=t.codecs[e];if(o.substring(0,o.indexOf("."))===r)return;const c={codecsChangeInfo:{from:o,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${o} to ${s}`);try{i.changeType(n),t.codecs[e]=s}catch(d){c.errorType=ye.Error.StreamingCodecsChangeError,c.error=d,d.metadata=c,t.error_=d,t.trigger("error"),ye.log.warn(`Failed to changeType on ${e}Buffer`,d)}}},dn=({type:s,sourceUpdater:e,action:t,doneFn:i,name:n})=>{e.queue.push({type:s,action:t,doneFn:i,name:n}),ju(s,e)},s1=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=e3(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_`])}ju(s,e)};class jD extends ye.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>ju("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Nn("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=s1("video",this),this.onAudioUpdateEnd_=s1("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){dn({type:"mediaSource",sourceUpdater:this,action:cn.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){dn({type:e,sourceUpdater:this,action:cn.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){ye.log.error("removeSourceBuffer is not supported!");return}dn({type:"mediaSource",sourceUpdater:this,action:cn.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!ye.browser.IS_FIREFOX&&ne.MediaSource&&ne.MediaSource.prototype&&typeof ne.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return ne.SourceBuffer&&ne.SourceBuffer.prototype&&typeof ne.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){ye.log.error("changeType is not supported!");return}dn({type:e,sourceUpdater:this,action:cn.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:n,bytes:r}=e;if(this.processedAppend_=!0,n==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}const o=t;if(dn({type:n,sourceUpdater:this,action:cn.appendBuffer(r,i||{mediaIndex:-1},o),doneFn:t,name:"appendBuffer"}),n==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const u=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${u.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,u.forEach(c=>{this.appendBuffer.apply(this,c)})}}audioBuffered(){return xr(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:ss()}videoBuffered(){return xr(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:ss()}buffered(){const e=xr(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=xr(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():i3(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=fa){dn({type:"mediaSource",sourceUpdater:this,action:cn.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=fa){typeof e!="string"&&(e=void 0),dn({type:"mediaSource",sourceUpdater:this,action:cn.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=fa){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}dn({type:"audio",sourceUpdater:this,action:cn.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=fa){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}dn({type:"video",sourceUpdater:this,action:cn.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(Rv("audio",this)||Rv("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(dn({type:"audio",sourceUpdater:this,action:cn.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(dn({type:"video",sourceUpdater:this,action:cn.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&dn({type:"audio",sourceUpdater:this,action:cn.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&dn({type:"video",sourceUpdater:this,action:cn.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),$4.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>$D(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const n1=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),H4=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},r1=new Uint8Array(` + +`.split("").map(s=>s.charCodeAt(0)));class G4 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class V4 extends Iv{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 ss();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return ss([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=$p(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=r1.byteLength+e.bytes.byteLength,o=new Uint8Array(r);o.set(e.bytes),o.set(r1,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:o}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Ad(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===wr.TIMEOUT&&this.handleTimeout_(),e.code===wr.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const n=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(n.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const o=n.segment;if(o.map&&(o.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof ne.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}o.requested=!0;try{this.parseVTTCues_(n)}catch(u){this.stopForError({message:u.message,metadata:{errorType:ye.Error.StreamingVttParserError,error:u}});return}if(r||this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=o.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new ne.VTTCue(u.startTime,u.endTime,u.text):u)}),C4(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&e.type==="vtt",n=t&&t.type==="text";i&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const n=i.start+t,r=i.end+t,o=new ne.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];o[d]=isNaN(f)?f:Number(f)}),e.cues.push(o)})}parseVTTCues_(e){let t,i=!1;if(typeof ne.WebVTT!="function")throw new G4;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof ne.TextDecoder=="function"?t=new ne.TextDecoder("utf8"):(t=ne.WebVTT.StringDecoder(),i=!0);const n=new ne.WebVTT.Parser(ne,ne.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=o=>{e.timestampmap=o},n.onparsingerror=o=>{ye.log.warn("Error encountered when parsing cues: "+o.message)},e.segment.map){let o=e.segment.map.bytes;i&&(o=n1(o)),n.parse(o)}let r=e.bytes;i&&(r=n1(r)),n.parse(r),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length){n.empty=!0;return}const{MPEGTS:r,LOCAL:o}=e.timestampmap,c=r/fl.ONE_SECOND_IN_TS-o+t.mapping;if(e.cues.forEach(d=>{const f=d.endTime-d.startTime,g=this.handleRollover_(d.startTime+c,t.time);d.startTime=Math.max(g,0),d.endTime=Math.max(g+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*fl.ONE_SECOND_IN_TS;const n=t*fl.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/fl.ONE_SECOND_IN_TS}}const q4=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},z4=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=` +`,o=i,u=t;this.start_=o,e.forEach((c,d)=>{const f=this.storage_.get(u),g=o,m=g+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),_=new a1({start:g,end:m,appended:v,segmentIndex:d});c.syncInfo=_;let b=o;const E=(c.parts||[]).map((w,L)=>{const I=b,F=b+w.duration,B=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[L]&&f.partsSyncInfo[L].isAppended),V=new a1({start:I,end:F,appended:B,segmentIndex:d,partIndex:L});return b=F,r+=`Media Sequence: ${u}.${L} | Range: ${I} --> ${F} | Appended: ${B} +`,w.syncInfo=V,V});n.set(u,new K4(_,E)),r+=`${FD(c.resolvedUri)} | Media Sequence: ${u} | Range: ${g} --> ${m} | Appended: ${v} +`,u++,o=m}),this.end_=o,this.storage_=n,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(et!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(s,e,t,i,n,r)=>{const o=s.getMediaSequenceSync(r);if(!o||!o.isReliable)return null;const u=o.getSyncInfoForTime(n);return u?{time:u.start,partIndex:u.partIndex,segmentIndex:u.segmentIndex}:null}},{name:"ProgramDateTime",run:(s,e,t,i,n)=>{if(!Object.keys(s.timelineToDatetimeMappings).length)return null;let r=null,o=null;const u=bv(e);n=n||0;for(let c=0;c{let r=null,o=null;n=n||0;const u=bv(e);for(let c=0;c=v)&&(o=v,r={time:m,segmentIndex:f.segmentIndex,partIndex:f.partIndex})}}return r}},{name:"Discontinuity",run:(s,e,t,i,n)=>{let r=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let o=null;for(let u=0;u=g)&&(o=g,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 W4 extends ye.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new HD,i=new o1(t),n=new o1(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=Nn("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return Ey.find(({name:c})=>c==="VOD").run(this,e,t);const o=this.runStrategies_(e,t,i,n,r);if(!o.length)return null;for(const u of o){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:g}=c;if(f<0)continue;const m=e.segments[f],v=g,_=v+m.duration;if(this.logger_(`Strategy: ${d}. Current time: ${n}. selected segment: ${f}. Time: [${v} -> ${_}]}`),n>=v&&n<_)return this.logger_("Found sync point with exact match: ",c),c}return this.selectSyncPoint_(o,{key:"time",value:n})}getExpiredTime(e,t){if(!e||!e.segments)return null;const i=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!i.length)return null;const n=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return n.segmentIndex>0&&(n.time*=-1),Math.abs(n.time+Pd({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const o=[];for(let u=0;uY4){ye.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let n=i-1;n>=0;n--){const r=e.segments[n];if(r&&typeof r.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:r.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const r=n.dateTimeObject;n.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[n.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const n=e.segment,r=e.part;let o=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),u=e.startOfSegment,c=t.end+o.mapping;else if(o)u=t.start+o.mapping,c=t.end+o.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-Pd({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+Pd({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[o]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class X4 extends ye.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 Q4=DD(wD(function(){var s=(function(){function b(){this.listeners={}}var E=b.prototype;return E.on=function(L,I){this.listeners[L]||(this.listeners[L]=[]),this.listeners[L].push(I)},E.off=function(L,I){if(!this.listeners[L])return!1;var F=this.listeners[L].indexOf(I);return this.listeners[L]=this.listeners[L].slice(0),this.listeners[L].splice(F,1),F>-1},E.trigger=function(L){var I=this.listeners[L];if(I)if(arguments.length===2)for(var F=I.length,B=0;B>7)*283)^F]=F;for(B=V=0;!L[B];B^=R||1,V=q[V]||1)for(ee=V^V<<1^V<<2^V<<3^V<<4,ee=ee>>8^ee&255^99,L[B]=ee,I[ee]=B,z=N[P=N[R=N[B]]],Q=z*16843009^P*65537^R*257^B*16843008,ie=N[ee]*257^ee*16843008,F=0;F<4;F++)E[F][B]=ie=ie<<24^ie>>>8,w[F][ee]=Q=Q<<24^Q>>>8;for(F=0;F<5;F++)E[F]=E[F].slice(0),w[F]=w[F].slice(0);return b};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 w,L,I;const F=this._tables[0][4],B=this._tables[1],V=E.length;let N=1;if(V!==4&&V!==6&&V!==8)throw new Error("Invalid aes key size");const q=E.slice(0),R=[];for(this._key=[q,R],w=V;w<4*V+28;w++)I=q[w-1],(w%V===0||V===8&&w%V===4)&&(I=F[I>>>24]<<24^F[I>>16&255]<<16^F[I>>8&255]<<8^F[I&255],w%V===0&&(I=I<<8^I>>>24^N<<24,N=N<<1^(N>>7)*283)),q[w]=q[w-V]^I;for(L=0;w;L++,w--)I=q[L&3?w:w-4],w<=4||L<4?R[L]=I:R[L]=B[0][F[I>>>24]]^B[1][F[I>>16&255]]^B[2][F[I>>8&255]]^B[3][F[I&255]]}decrypt(E,w,L,I,F,B){const V=this._key[1];let N=E^V[0],q=I^V[1],R=L^V[2],P=w^V[3],z,ee,ie;const Q=V.length/4-2;let oe,H=4;const X=this._tables[1],te=X[0],ae=X[1],ce=X[2],$=X[3],se=X[4];for(oe=0;oe>>24]^ae[q>>16&255]^ce[R>>8&255]^$[P&255]^V[H],ee=te[q>>>24]^ae[R>>16&255]^ce[P>>8&255]^$[N&255]^V[H+1],ie=te[R>>>24]^ae[P>>16&255]^ce[N>>8&255]^$[q&255]^V[H+2],P=te[P>>>24]^ae[N>>16&255]^ce[q>>8&255]^$[R&255]^V[H+3],H+=4,N=z,q=ee,R=ie;for(oe=0;oe<4;oe++)F[(3&-oe)+B]=se[N>>>24]<<24^se[q>>16&255]<<16^se[R>>8&255]<<8^se[P&255]^V[H++],z=N,N=q,q=R,R=P,P=z}}class r extends s{constructor(){super(s),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(E){this.jobs.push(E),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const o=function(b){return b<<24|(b&65280)<<8|(b&16711680)>>8|b>>>24},u=function(b,E,w){const L=new Int32Array(b.buffer,b.byteOffset,b.byteLength>>2),I=new n(Array.prototype.slice.call(E)),F=new Uint8Array(b.byteLength),B=new Int32Array(F.buffer);let V,N,q,R,P,z,ee,ie,Q;for(V=w[0],N=w[1],q=w[2],R=w[3],Q=0;Q{const L=b[w];m(L)?E[w]={bytes:L.buffer,byteOffset:L.byteOffset,byteLength:L.byteLength}:E[w]=L}),E};self.onmessage=function(b){const E=b.data,w=new Uint8Array(E.encrypted.bytes,E.encrypted.byteOffset,E.encrypted.byteLength),L=new Uint32Array(E.key.bytes,E.key.byteOffset,E.key.byteLength/4),I=new Uint32Array(E.iv.bytes,E.iv.byteOffset,E.iv.byteLength/4);new c(w,L,I,function(F,B){self.postMessage(_({source:E.source,decrypted:B}),[B.buffer])})}}));var Z4=CD(Q4);const J4=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},GD=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},kv=(s,e)=>{e.activePlaylistLoader=s,s.load()},eB=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),o=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(o&&c&&o.id===c.id)&&(n.lastGroup_=o,n.lastTrack_=r,GD(t,n),!(!o||o.isMainPlaylist))){if(!o.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),kv(o.playlistLoader,n)}},tB=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},iB=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,o=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&o&&d.id===o.id)&&(r.lastGroup_=u,r.lastTrack_=o,GD(i,r),!!u)){if(u.isMainPlaylist){if(!o||!d||o.id===d.id)return;const f=e.vhs.playlistController_,g=f.selectPlaylist();if(f.media()===g)return;r.logger_(`track change. Switching main audio from ${d.id} to ${o.id}`),t.pause(),n.resetEverything(),f.fastQualityChange_(g);return}if(s==="AUDIO"){if(!u.playlistLoader){n.setAudio(!0),n.resetEverything();return}i.setAudio(!0),n.setAudio(!1)}if(c===u.playlistLoader){kv(u.playlistLoader,r);return}i.track&&i.track(o),i.resetEverything(),kv(u.playlistLoader,r)}},jp={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),o=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[o];if(n===u){i({error:{message:"Problem encountered loading the default audio track."}});return}ye.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;ye.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},l1={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const o=e.media();r.playlist(o,n),(!i.paused()||o.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",jp[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:o}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(o.activeTrack()),(!i.paused()||u.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",jp[s](s,t))}},sB={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,g=rh(f.main);(!o[s]||Object.keys(o[s]).length===0)&&(o[s]={main:{default:{default:!0}}},g&&(o[s].main.default.playlists=f.main.playlists));for(const m in o[s]){u[m]||(u[m]=[]);for(const v in o[s][m]){let _=o[s][m][v],b;if(g?(d(`AUDIO group '${m}' label '${v}' is a main playlist`),_.isMainPlaylist=!0,b=null):i==="vhs-json"&&_.playlists?b=new Iu(_.playlists[0],t,r):_.resolvedUri?b=new Iu(_.resolvedUri,t,r):_.playlists&&i==="dash"?b=new Dv(_.playlists[0],t,r,f):b=null,_=jt({id:v,playlistLoader:b},_),l1[s](s,_.playlistLoader,e),u[m].push(_),typeof c[v]>"u"){const E=new ye.AudioTrack({id:v,kind:J4(_),enabled:!1,language:_.language,default:_.default,label:v});c[v]=E}}}n.on("error",jp[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:o,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const g in u[s]){c[g]||(c[g]=[]);for(const m in u[s][g]){if(!i.options_.useForcedSubtitles&&u[s][g][m].forced)continue;let v=u[s][g][m],_;if(n==="hls")_=new Iu(v.resolvedUri,i,o);else if(n==="dash"){if(!v.playlists.filter(E=>E.excludeUntil!==1/0).length)return;_=new Dv(v.playlists[0],i,o,f)}else n==="vhs-json"&&(_=new Iu(v.playlists?v.playlists[0]:v.resolvedUri,i,o));if(v=jt({id:m,playlistLoader:_},v),l1[s](s,v.playlistLoader,e),c[g].push(v),typeof d[m]>"u"){const b=t.addRemoteTextTrack({id:m,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:m},!1).track;d[m]=b}}}r.on("error",jp[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const o in i[s]){n[o]||(n[o]=[]);for(const u in i[s][o]){const c=i[s][o][u];if(!/^(?:CC|SERVICE)/.test(c.instreamId))continue;const d=t.options_.vhs&&t.options_.vhs.captionServices||{};let f={label:u,language:c.language,instreamId:c.instreamId,default:c.default&&c.autoselect};if(d[f.instreamId]&&(f=jt(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[o].push(jt({id:u},c)),typeof r[u]>"u"){const g=t.addRemoteTextTrack({id:f.instreamId,kind:"captions",default:f.default,language:f.language,label:f.label},!1).track;r[u]=g}}}}},VD=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let o=null;r.attributes[s]&&(o=n[r.attributes[s]]);const u=Object.keys(n);if(!o)if(s==="AUDIO"&&u.length>1&&rh(e.main))for(let c=0;c"u"?o:t===null||!o?null:o.filter(c=>c.id===t.id)[0]||null},rB={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}},aB=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},oB=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{sB[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:o}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=nB(d,s),e[d].activeTrack=rB[d](d,s),e[d].onGroupChanged=eB(d,s),e[d].onGroupChanging=tB(d,s),e[d].onTrackChanged=iB(d,s),e[d].getActiveGroup=aB(d,s)});const u=e.AUDIO.activeGroup();if(u){const d=(u.filter(g=>g.default)[0]||u[0]).id;e.AUDIO.tracks[d].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(o.setAudio(!1),r.setAudio(!0)):o.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanging())});const c=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",c),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{i.audioTracks().removeEventListener("change",c),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const d in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[d])},lB=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:fa,activeTrack:fa,getActiveGroup:fa,onGroupChanged:fa,onTrackChanged:fa,lastTrack_:null,logger_:Nn(`MediaGroups[${e}]`)}}),s};class u1{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_=Ys(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 uB=class extends ye.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new u1,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_=Nn("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=Ys(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,o)=>{if(r){if(o.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(o.status===429){const d=o.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${d} seconds.`),this.startTTLTimeout_(parseInt(d,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let u;try{u=JSON.parse(this.request_.responseText)}catch(d){const f={errorType:ye.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 ne.URL(e),i=new ne.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(ne.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new ne.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_=ne.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){ne.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 u1}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&&(Ys(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const cB=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},dB=10;let ro;const hB=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],fB=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},pB=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:o,bufferBasedABR:u,log:c}){if(!i)return ye.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=!!Lu(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 g=BT(e,t),m=u?ts.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:ts.MAX_BUFFER_LOW_WATER_LINE;if(o_)&&g>=n){let b=`${d} as forwardBuffer >= bufferLowWaterLine (${g} >= ${n})`;return u&&(b+=` and next bandwidth > current bandwidth (${v} > ${_})`),c(b),!0}return c(`not ${d} as no switching criteria met`),!1};class gB extends ye.EventTarget{constructor(e){super(),this.fastQualityChange_=cB(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:o,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:g,bufferBasedABR:m,leastPixelDiffSelector:v,captionServices:_,experimentalUseMMS:b}=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),ro=o,this.bufferBasedABR=!!m,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_=lB(),b&&ne.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new ne.ManagedMediaSource,this.usingManagedMediaSource_=!0,ye.log("Using ManagedMediaSource")):ne.MediaSource&&(this.mediaSource=new ne.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_=ss(),this.hasPlayed_=!1,this.syncController_=new W4(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new Z4,this.sourceUpdater_=new jD(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new X4,this.keyStatusMap_=new Map;const w={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:_,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:g,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new Dv(t,this.vhs_,jt(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Iu(t,this.vhs_,jt(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Iv(jt(w,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Iv(jt(w,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new V4(jt(w,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((F,B)=>{function V(){n.off("vttjserror",N),F()}function N(){n.off("vttjsloaded",V),B()}n.one("vttjsloaded",V),n.one("vttjserror",N),n.addWebVttScript_()})}),e);const L=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new uB(this.vhs_.xhr,L),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),hB.forEach(F=>{this[F+"_"]=fB.bind(this,F)}),this.logger_=Nn("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 I=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(I,()=>{const F=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-F,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const n=this.media(),r=n&&(n.id||n.uri),o=e&&(e.id||e.uri);if(r&&r!==o){this.logger_(`switch media ${r} -> ${o} from ${t}`);const u={renditionInfo:{id:o,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:u}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(i&&n){const o=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);o.length&&this.mediaTypes_[e].activePlaylistLoader.media(o[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=ne.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(ne.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,n=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const u=i.main||n.length&&i[n[0]];for(const c in u)if(u[c].default){r={label:c};break}}if(!r)return t;const o=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)o.push.apply(o,c.playlists);else if(c.uri)o.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;Sv(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()),oB({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;Sv(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(Mi({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let n=!0;const r=Object.keys(i.AUDIO);for(const o in i.AUDIO)for(const u in i.AUDIO[o])i.AUDIO[o][u].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),ro.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),n=this.bufferLowWaterLine(),r=this.bufferHighWaterLine(),o=this.tech_.buffered();return pB({buffered:o,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const n=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(n)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:dB}))});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(Mi({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(Mi({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(Mi({},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=ro.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),o=this.tech_.buffered();if(!o.length)return n-r<=Dr;const u=o.end(o.length-1);return u-r<=Dr&&n-u<=Dr}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(Og),o=r.length===1&&r[0]===e;if(n.length===1&&i!==1/0)return ye.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(o);if(o){if(this.main().contentSteering){const _=this.pathwayAttribute_(e),b=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(_),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(_)},b);return}let v=!1;n.forEach(_=>{if(_===e)return;const b=_.excludeUntil;typeof b<"u"&&b!==1/0&&(v=!0,delete _.excludeUntil)}),v&&(ye.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_:ye.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 g=c.targetDuration/2*1e3||5*1e3,m=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=g;return this.switchMedia_(c,"exclude",o||m)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],n=e==="all";(n||e==="main")&&i.push(this.mainPlaylistLoader_);const r=[];(n||e==="audio")&&r.push("AUDIO"),(n||e==="subtitle")&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(o=>{const u=this.mediaTypes_[o]&&this.mediaTypes_[o].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(o=>{const u=this[`${o}SegmentLoader_`];u&&(e===o||e==="all")&&i.push(u)}),i.forEach(o=>t.forEach(u=>{typeof o[u]=="function"&&o[u]()}))}setCurrentTime(e){const t=Lu(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:ro.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=ro.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return ss([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const o=ro.Playlist.seekable(i,r,ro.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return o.length?o:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),o=t.end(0);return r>n||i>o?e:ss([[Math.max(i,r),Math.min(n,o)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${eD(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=Md(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||sP),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||Zx}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||Zx,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const o=(d,f)=>d?Id(f,this.usingManagedMediaSource_):ny(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!o(e[d].isFmp4,n[d])){const f=e[d].isFmp4?"browser":"muxer";u[f]=u[f]||[],u[f].push(n[d]),d==="audio"&&(c=f)}}),r&&c&&t.attributes.AUDIO){const d=t.attributes.AUDIO;this.main().playlists.forEach(f=>{(f.attributes&&f.attributes.AUDIO)===d&&f!==t&&(f.excludeUntil=1/0)}),this.logger_(`excluding audio group ${d} as ${c} does not support codec(s): "${n.audio}"`)}if(Object.keys(u).length){const d=Object.keys(u).reduce((f,g)=>(f&&(f+=", "),f+=`${g} does not support codec(s): "${u[g].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 g=(Sr(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,m=(Sr(n[f]||"")[0]||{}).type;g&&m&&g.toLowerCase()!==m.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=Md(this.main,n),o=[];r.audio&&!ny(r.audio)&&!Id(r.audio,this.usingManagedMediaSource_)&&o.push(`audio codec ${r.audio}`),r.video&&!ny(r.video)&&!Id(r.video,this.usingManagedMediaSource_)&&o.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&o.push(`text codec ${r.text}`),o.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${o.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=Gd(Sr(e)),r=qE(n),o=n.video&&Sr(n.video)[0]||null,u=n.audio&&Sr(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=[],g=Md(this.mainPlaylistLoader_.main,d),m=qE(g);if(!(!g.audio&&!g.video)){if(m!==r&&f.push(`codec count "${m}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=g.video&&Sr(g.video)[0]||null,_=g.audio&&Sr(g.audio)[0]||null;v&&o&&v.type.toLowerCase()!==o.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${o.type}"`),_&&u&&_.type.toLowerCase()!==u.type.toLowerCase()&&f.push(`audio codec "${_.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)),z4(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=ts.GOAL_BUFFER_LENGTH,i=ts.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,ts.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=ts.BUFFER_LOW_WATER_LINE,i=ts.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,ts.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,ts.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return ts.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){JE(this.inbandTextTracks_,"com.apple.streaming",this.tech_),A4({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();JE(this.inbandTextTracks_,e,this.tech_),S4({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(Mi({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),o=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(o.push(c),!r.has(c)))return!0}return!!(!o.length&&r.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,n=new Set;let r=!1;Object.keys(i).forEach(o=>{const u=i[o],c=this.pathwayAttribute_(u),d=c&&e!==c;u.excludeUntil===1/0&&u.lastExcludeReason_==="content-steering"&&!d&&(delete u.excludeUntil,delete u.lastExcludeReason_,r=!0);const g=!u.excludeUntil&&u.excludeUntil!==1/0;!n.has(u.id)&&d&&g&&(n.add(u.id),u.excludeUntil=1/0,u.lastExcludeReason_="content-steering",this.logger_(`excluding ${u.id} for ${u.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(o=>{const u=this.mediaTypes_[o];if(u.activePlaylistLoader){const c=u.activePlaylistLoader.media_;c&&c.attributes.serviceLocation!==e&&(r=!0)}}),r&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,n=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||n&&n.size){for(const[o,u]of i.entries())n.get(o)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(o));for(const[o,u]of n.entries()){const c=i.get(o);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(o);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(o))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...n])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const r in i)if(i[r]!==n[r])return!1;for(const r in n)if(i[r]!==n[r])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=this.mainPlaylistLoader_.getKeyIdSet(i);!n||!n.size||n.forEach(r=>{const o="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===o,c=i.lastExcludeReason_===t&&i.excludeUntil===1/0;u?u&&c&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${r} is ${o}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${r} doesn't exist in the keyStatusMap or is not ${o}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const n=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,r=i.excludeUntil===1/0&&i.lastExcludeReason_===t;n&&r&&(delete i.excludeUntil,ye.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:H4(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 mB=(s,e,t)=>i=>{const n=s.main.playlists[e],r=UT(n),o=Og(n);if(typeof i>"u")return o;i?delete n.disabled:n.disabled=!0;const u={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return i!==o&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class yB{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const o=t.attributes.RESOLUTION;this.width=o&&o.width,this.height=o&&o.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=Md(n.main(),t),this.playlist=t,this.id=i,this.enabled=mB(e.playlists,t.id,r)}}const vB=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=rh(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!UT(i)).map((i,n)=>new yB(s,i,i.id)):[]}},c1=["seeking","seeked","pause","playing","error"];class TB extends ye.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_=Nn("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),o=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},o[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(g=>{o[`${g}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(c1,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(c1,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),u.forEach(f=>{o[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),o[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&ne.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&ne.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=ne.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=n3(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const o={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:o}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:pl(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+Dr>=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(ss([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 _=t.start(0);r=_+(_===t.end(0)?0:Dr)}if(typeof r<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${eD(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const o=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=o.audioBuffer?o.audioBuffered():null,d=o.videoBuffer?o.videoBuffered():null,f=this.media(),g=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-Cr)*2,m=[c,d];for(let _=0;_ ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const u=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${u}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(u),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const o=$f(n,t);return o.length>0?(this.logger_(`Stopped at ${t} and seeking to ${o.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,n=!1){if(!e.length)return!1;let r=e.end(e.length-1)+Dr;const o=!i.endList,u=typeof i.partTargetDuration=="number";return o&&(u||n)&&(r=e.end(e.length-1)+i.targetDuration*3),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:o}}return null}}const _B={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},qD=function(s,e){let t=0,i=0;const n=jt(_B,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},o=function(f){f!=null&&(i=s.duration()!==1/0&&s.currentTime()||0,s.one("loadedmetadata",r),s.src(f),s.trigger({type:"usage",name:"vhs-error-reload"}),s.play())},u=function(){if(Date.now()-t{Object.defineProperty(bi,s,{get(){return ye.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),ts[s]},set(e){if(ye.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){ye.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}ts[s]=e}})});const KD="videojs-vhs",YD=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),YD(s,e.playlists)};bi.canPlaySource=function(){return ye.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const DB=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=Gd(Sr(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=zu(i.video),r=zu(i.audio),o={};for(const u in s)o[u]={},r&&(o[u].audioContentType=r),n&&(o[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(o[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(o[u].url=s[u]);return jt(s,o)},wB=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,o)=>{const u=i.contentProtection[o];return u&&u.pssh&&(r[o]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),LB=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=wB(n,Object.keys(e)),o=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),o.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},g=>{if(g){f(g);return}d()})}))}),Promise.race([Promise.all(o),Promise.race(u)])},IB=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=DB(e,t,i);return n?(s.currentSource().keySystems=n,n&&!s.eme?(ye.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},WD=()=>{if(!ne.localStorage)return null;const s=ne.localStorage.getItem(KD);if(!s)return null;try{return JSON.parse(s)}catch{return null}},RB=s=>{if(!ne.localStorage)return!1;let e=WD();e=e?jt(e,s):s;try{ne.localStorage.setItem(KD,JSON.stringify(e))}catch{return!1}return e},kB=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,XD=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},QD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},ZD=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},JD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};bi.supportsNativeHls=(function(){if(!Ne||!Ne.createElement)return!1;const s=Ne.createElement("video");return ye.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})();bi.supportsNativeDash=(function(){return!Ne||!Ne.createElement||!ye.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(Ne.createElement("video").canPlayType("application/dash+xml"))})();bi.supportsTypeNatively=s=>s==="hls"?bi.supportsNativeHls:s==="dash"?bi.supportsNativeDash:!1;bi.isSupported=function(){return ye.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};bi.xhr.onRequest=function(s){XD(bi.xhr,s)};bi.xhr.onResponse=function(s){QD(bi.xhr,s)};bi.xhr.offRequest=function(s){ZD(bi.xhr,s)};bi.xhr.offResponse=function(s){JD(bi.xhr,s)};const OB=ye.getComponent("Component");class ew extends OB{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Nn("VhsHandler"),t.options_&&t.options_.playerId){const n=ye.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(Ne,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=Ne.fullscreenElement||Ne.webkitFullscreenElement||Ne.mozFullScreenElement||Ne.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_=jt(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=WD();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=ts.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===ts.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=kB(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=bi,this.options_.sourceType=bA(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new gB(this.options_);const i=jt({liveRangeSafeTimeDelta:Dr},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new TB(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=ye.players[this.tech_.options_.playerId];let o=this.playlistController_.error;typeof o=="object"&&!o.code?o.code=3:typeof o=="string"&&(o={message:o,code:3}),r.error(o)});const n=this.options_.bufferBasedABR?bi.movingAverageBandwidthSelector(.55):bi.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=bi.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(r){this.playlistController_.selectPlaylist=r.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(r){this.playlistController_.mainSegmentLoader_.throughput.rate=r,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let r=this.playlistController_.mainSegmentLoader_.bandwidth;const o=ne.navigator.connection||ne.navigator.mozConnection||ne.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&o){const c=o.downlink*1e3*1e3;c>=u&&r>=u?r=Math.max(r,c):r=c}return r},set(r){this.playlistController_.mainSegmentLoader_.bandwidth=r,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const r=1/(this.bandwidth||1);let o;return this.throughput>0?o=1/this.throughput:o=0,Math.floor(1/(r+o))},set(){ye.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:()=>pl(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:()=>pl(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&&RB({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{vB(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_=ne.URL.createObjectURL(this.playlistController_.mediaSource),(ye.browser.IS_ANY_SAFARI||ye.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"),LB({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=IB({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=ye.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{CB(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{YD(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":zD,"mux.js":SB,"mpd-parser":xB,"m3u8-parser":EB,"aes-decrypter":AB}}version(){return this.constructor.version()}canChangeType(){return jD.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_&&ne.URL.revokeObjectURL&&(ne.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return B3({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return ED({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=>{XD(this.xhr,e)},this.xhr.onResponse=e=>{QD(this.xhr,e)},this.xhr.offRequest=e=>{ZD(this.xhr,e)},this.xhr.offResponse=e=>{JD(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(Mi({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(Mi({},n))})})}}const Hp={name:"videojs-http-streaming",VERSION:zD,canHandleSource(s,e={}){const t=jt(ye.options,e);return!t.vhs.experimentalUseMMS&&!Id("avc1.4d400d,mp4a.40.2",!1)?!1:Hp.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=jt(ye.options,t);return e.vhs=new ew(s,e,i),e.vhs.xhr=TD(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=bA(s);if(!t)return"";const i=Hp.getOverrideNative(e);return!bi.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(ye.browser.IS_ANY_SAFARI||ye.browser.IS_IOS),{overrideNative:i=t}=e;return i}},PB=()=>Id("avc1.4d400d,mp4a.40.2",!0);PB()&&ye.getTech("Html5").registerSourceHandler(Hp,0);ye.VhsHandler=ew;ye.VhsSourceHandler=Hp;ye.Vhs=bi;ye.use||ye.registerComponent("Vhs",bi);ye.options.vhs=ye.options.vhs||{};(!ye.getPlugin||!ye.getPlugin("reloadSourceOnError"))&&ye.registerPlugin("reloadSourceOnError",bB);function MB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 NB=Y.forwardRef(MB);function BB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 FB=Y.forwardRef(BB);function UB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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"}),Y.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 $B=Y.forwardRef(UB);function jB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6.633 10.25c.806 0 1.533-.446 2.031-1.08a9.041 9.041 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 .75-.75 2.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.282m0 0h3.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.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23H5.904m10.598-9.75H14.25M5.904 18.5c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 0 1-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 9.953 4.167 9.5 5 9.5h1.053c.472 0 .745.556.5.96a8.958 8.958 0 0 0-1.302 4.665c0 1.194.232 2.333.654 3.375Z"}))}const HB=Y.forwardRef(jB);function GB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 VB=Y.forwardRef(GB);function qB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.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 zB=Y.forwardRef(qB);function KB({title:s,titleId:e,...t},i){return Y.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?Y.createElement("title",{id:e},s):null,Y.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const YB=Y.forwardRef(KB),d1=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function vd(...s){return s.filter(Boolean).join(" ")}function WB({job:s,expanded:e,onClose:t,onToggleExpand:i,className:n,isHot:r=!1,isFavorite:o=!1,isLiked:u=!1,onDelete:c,onToggleHot:d,onToggleFavorite:f,onToggleLike:g}){const m=Y.useMemo(()=>d1(s.output?.trim()||"")||s.id,[s.output,s.id]);Y.useEffect(()=>{const B=V=>V.key==="Escape"&&t();return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t]);const v=Y.useMemo(()=>{if(s.status==="running")return{src:`/api/record/preview?id=${encodeURIComponent(s.id)}&file=index_hq.m3u8`,type:"application/x-mpegURL"};const B=d1(s.output?.trim()||"");return B?{src:`/api/record/video?file=${encodeURIComponent(B)}`,type:"video/mp4"}:{src:`/api/record/video?id=${encodeURIComponent(s.id)}`,type:"video/mp4"}},[s.id,s.output,s.status]),_=Y.useRef(null),b=Y.useRef(null),E=Y.useRef(null),[w,L]=Y.useState(!1);if(Y.useEffect(()=>L(!0),[]),Y.useLayoutEffect(()=>{if(!w||!_.current||b.current)return;const B=document.createElement("video");B.className="video-js vjs-big-play-centered w-full h-full",B.setAttribute("playsinline","true"),_.current.appendChild(B),E.current=B;const V=ye(B,{autoplay:!0,muted:!0,controls:!0,preload:"auto",playsinline:!0,responsive:!0,fluid:!1,fill:!0,controlBar:{skipButtons:{backward:10,forward:10},children:["playToggle","progressControl","currentTimeDisplay","timeDivider","durationDisplay","volumePanel","playbackRateMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});return b.current=V,()=>{try{b.current&&(b.current.dispose(),b.current=null)}finally{E.current&&(E.current.remove(),E.current=null)}}},[w]),Y.useEffect(()=>{if(!w)return;const B=b.current;if(!B||B.isDisposed?.())return;const V=B.currentTime()||0;B.muted(!0),B.src({src:v.src,type:v.type});const N=()=>{const q=B.play?.();q&&typeof q.catch=="function"&&q.catch(()=>{})};B.one("loadedmetadata",()=>{B.isDisposed?.()||(V>0&&v.type!=="application/x-mpegURL"&&B.currentTime(V),N())}),N()},[w,v.src,v.type]),Y.useEffect(()=>{const B=b.current;!B||B.isDisposed?.()||queueMicrotask(()=>B.trigger("resize"))},[e]),!w)return null;const I=!e,F=U.jsxs("div",{className:"flex items-center gap-1",children:[U.jsx(ci,{variant:r?"soft":"secondary",size:"xs",className:vd("px-2 py-1",!r&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:r?"HOT entfernen":"Als HOT markieren","aria-label":r?"HOT entfernen":"Als HOT markieren",onClick:()=>d?.(s),disabled:!d,children:U.jsx($B,{className:"h-4 w-4"})}),U.jsx(ci,{variant:o?"soft":"secondary",size:"xs",className:vd("px-2 py-1",!o&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:o?"Favorite entfernen":"Als Favorite markieren","aria-label":o?"Favorite entfernen":"Als Favorite markieren",onClick:()=>f?.(s),disabled:!f,children:U.jsx(VB,{className:"h-4 w-4"})}),U.jsx(ci,{variant:u?"soft":"secondary",size:"xs",className:vd("px-2 py-1",!u&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:u?"Like entfernen":"Like hinzufügen","aria-label":u?"Like entfernen":"Like hinzufügen",onClick:()=>g?.(s),disabled:!g,children:U.jsx(HB,{className:"h-4 w-4"})}),U.jsx(ci,{variant:"secondary",size:"xs",className:"px-2 py-1 bg-transparent shadow-none hover:bg-red-50 text-red-600 dark:hover:bg-red-500/10 dark:text-red-400",title:"Löschen","aria-label":"Löschen",onClick:()=>c?.(s),disabled:!c,children:U.jsx(zB,{className:"h-4 w-4"})})]});return tg.createPortal(U.jsxs(U.Fragment,{children:[e&&U.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:t,"aria-hidden":"true"}),U.jsx(In,{className:vd("fixed z-50 shadow-xl border flex flex-col",e?"inset-6":"bottom-4 right-4 w-[380px]",n??""),noBodyPadding:!0,bodyClassName:"flex flex-col flex-1 min-h-0 p-0",header:U.jsxs("div",{className:"flex items-center justify-between gap-3",children:[U.jsx("div",{className:"min-w-0",children:U.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:m})}),U.jsxs("div",{className:"flex shrink-0 gap-2",children:[U.jsx(ci,{variant:"secondary",size:"xs",className:"px-2 py-1",onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?U.jsx(NB,{className:"h-5 w-5"}):U.jsx(FB,{className:"h-5 w-5"})}),U.jsx(ci,{variant:"secondary",size:"xs",className:"px-2 py-1",onClick:t,title:"Schließen","aria-label":"Schließen",children:U.jsx(YB,{className:"h-5 w-5"})})]})]}),footer:U.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-gray-600 dark:text-gray-300",children:[U.jsxs("div",{className:"min-w-0 truncate",children:["Status: ",U.jsx("span",{className:"font-medium",children:s.status}),s.output?U.jsxs("span",{className:"ml-2 opacity-70",children:["• ",s.output]}):null]}),I?F:null]}),grayBody:!1,children:U.jsx("div",{className:e?"flex-1 min-h-0":"aspect-video",children:U.jsx("div",{className:vd("w-full h-full min-h-0",I&&"vjs-mini"),children:U.jsx("div",{ref:_,className:"w-full h-full"})})})})]}),document.body)}const He=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},XB=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=QB},QB=Number.MAX_SAFE_INTEGER||9007199254740991;let Ye=(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})({}),me=(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})({}),M=(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 bt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},qe={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class bu{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 ZB{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 bu(e),this.fast_=new bu(t),this.defaultTTFB_=n,this.ttfb_=new bu(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new bu(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new bu(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new bu(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 JB(s,e,t){return(e=tF(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Zt(){return Zt=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):fo}function f1(s,e,t){return e[s]?e[s].bind(e):sF(s,t)}const Pv=Ov();function nF(s,e,t){const i=Ov();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=f1(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Ov()}n.forEach(r=>{Pv[r]=f1(r,s)})}else Zt(Pv,i);return i}const zt=Pv;function So(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function rF(s){return typeof self<"u"&&s===self.ManagedMediaSource}function tw(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(o=>i.indexOf(o)===-1)}function mn(s,e=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(e){const f=d.indexOf("\0");return f!==-1?d.substring(0,f):d}return d.replace(/\0/g,"")}const t=s.length;let i,n,r,o="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],o+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],o+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return o}function ds(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(!He(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Pi(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const n=t[e];n&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,o=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:o};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,i),c.startDTS=Math.min(c.startDTS,n),c.endDTS=Math.max(c.endDTS,r)}}class lF extends sw{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function nw(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||nw(t,e)}}function uF(s,e){const t=nw(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const g1=Math.pow(2,32)-1,cF=[].push,rw={video:1,audio:2,id3:3,text:4};function zi(s){return String.fromCharCode.apply(null,s)}function aw(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function at(s,e){const t=ow(s,e);return t<0?4294967296+t:t}function m1(s,e){let t=at(s,e);return t*=Math.pow(2,32),t+=at(s,e+4),t}function ow(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function dF(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 vt(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=vt(s.subarray(n+8,u),e.slice(1));c.length&&cF.apply(t,c)}n=u}return t}function hF(s){const e=[],t=s[0];let i=8;const n=at(s,i);i+=4;let r=0,o=0;t===0?(r=at(s,i),o=at(s,i+4),i+=8):(r=m1(s,i),o=m1(s,i+8),i+=16),i+=2;let u=s.length+o;const c=aw(s,i);i+=2;for(let d=0;d>>31===1)return zt.warn("SIDX has hierarchical references (not supported)"),null;const _=at(s,f);f+=4,e.push({referenceSize:m,subsegmentDuration:_,info:{duration:_/n,start:u,end:u+m-1}}),u+=m,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function lw(s){const e=[],t=vt(s,["moov","trak"]);for(let n=0;n{const r=at(n,4),o=e[r];o&&(o.default={duration:at(n,12),flags:at(n,20)})}),e}function fF(s){const e=s.subarray(8),t=e.subarray(86),i=zi(e.subarray(4,8));let n=i,r;const o=i==="enca"||i==="encv";if(o){const d=vt(e,[i])[0].subarray(i==="enca"?28:78);vt(d,["sinf"]).forEach(g=>{const m=vt(g,["schm"])[0];if(m){const v=zi(m.subarray(4,8));if(v==="cbcs"||v==="cenc"){const _=vt(g,["frma"])[0];_&&(n=zi(_))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=vt(t,["avcC"])[0];c&&c.length>3&&(n+="."+Vf(c[1])+Vf(c[2])+Vf(c[3]),r=Gf(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=vt(e,[i])[0],d=vt(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=Dy(d,f),f+=2;const g=d[f++];if(g&128&&(f+=2),g&64&&(f+=d[f++]),d[f++]!==4)break;f=Dy(d,f);const m=d[f++];if(m===64)n+="."+Vf(m);else break;if(f+=12,d[f++]!==5)break;f=Dy(d,f);const v=d[f++];let _=(v&248)>>3;_===31&&(_+=1+((v&7)<<3)+((d[f]&224)>>5)),n+="."+_}break}case"hvc1":case"hev1":{const c=vt(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],g=d&31,m=at(c,2),v=(d&32)>>5?"H":"L",_=c[12],b=c.subarray(6,12);n+="."+f+g,n+="."+pF(m).toString(16).toUpperCase(),n+="."+v+_;let E="";for(let w=b.length;w--;){const L=b[w];(L||E)&&(E="."+L.toString(16).toUpperCase()+E)}n+=E}r=Gf(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Gf(n,t)||n;break}case"vp09":{const c=vt(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],g=c[6]>>4&15;n+="."+br(d)+"."+br(f)+"."+br(g)}break}case"av01":{const c=vt(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,g=c[2]>>>7?"H":"M",m=(c[2]&64)>>6,v=(c[2]&32)>>5,_=d===2&&m?v?12:10:m?10:8,b=(c[2]&16)>>4,E=(c[2]&8)>>3,w=(c[2]&4)>>2,L=c[2]&3;n+="."+d+"."+br(f)+g+"."+br(_)+"."+b+"."+E+w+L+"."+br(1)+"."+br(1)+"."+br(1)+"."+0,r=Gf("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:r}}function Gf(s,e){const t=vt(e,["dvvC"]),i=t.length?t[0]:vt(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+br(n)+"."+br(r)}}function pF(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Dy(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(o=>o!==0)||(zt.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${ds(r)} -> ${ds(t)}`),i.set(t,8))})}function mF(s){const e=[];return uw(s,t=>e.push(t.subarray(8,24))),e}function uw(s,e){vt(s,["moov","trak"]).forEach(i=>{const n=vt(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let o=vt(r,["enca"]);const u=o.length>0;u||(o=vt(r,["encv"])),o.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);vt(d,["sinf"]).forEach(g=>{const m=cw(g);m&&e(m,u)})})})}function cw(s){const e=vt(s,["schm"])[0];if(e){const t=zi(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=vt(s,["schi","tenc"])[0];if(i)return i}}}function yF(s,e,t){const i={},n=vt(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,o=0;const u=vt(s,["sidx"]);for(let c=0;cg+m.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale)}}o&&He(o)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=o*i[c].timescale-i[c].start)})}return i}function vF(s){const e={valid:null,remainder:null},t=vt(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 Pn(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function y1(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let o=!1;return vt(i,["moof"]).map(c=>{const d=c.byteOffset-8;vt(c,["traf"]).map(g=>{const m=vt(g,["tfdt"]).map(v=>{const _=v[0];let b=at(v,4);return _===1&&(b*=Math.pow(2,32),b+=at(v,8)),b/n})[0];return m!==void 0&&(s=m),vt(g,["tfhd"]).map(v=>{const _=at(v,4),b=at(v,0)&16777215,E=(b&1)!==0,w=(b&2)!==0,L=(b&8)!==0;let I=0;const F=(b&16)!==0;let B=0;const V=(b&32)!==0;let N=8;_===r&&(E&&(N+=8),w&&(N+=4),L&&(I=at(v,N),N+=4),F&&(B=at(v,N),N+=4),V&&(N+=4),e.type==="video"&&(o=Pg(e.codec)),vt(g,["trun"]).map(q=>{const R=q[0],P=at(q,0)&16777215,z=(P&1)!==0;let ee=0;const ie=(P&4)!==0,Q=(P&256)!==0;let oe=0;const H=(P&512)!==0;let X=0;const te=(P&1024)!==0,ae=(P&2048)!==0;let ce=0;const $=at(q,4);let se=8;z&&(ee=at(q,se),se+=4),ie&&(se+=4);let he=ee+d;for(let Se=0;Se<$;Se++){if(Q?(oe=at(q,se),se+=4):oe=I,H?(X=at(q,se),se+=4):X=B,te&&(se+=4),ae&&(R===0?ce=at(q,se):ce=ow(q,se),se+=4),e.type===ni.VIDEO){let be=0;for(;be>1&63;return t===39||t===40}else return(e&31)===6}function qT(s,e,t,i){const n=dw(s);let r=0;r+=e;let o=0,u=0,c=0;for(;r=n.length)break;c=n[r++],o+=c}while(c===255);u=0;do{if(r>=n.length)break;c=n[r++],u+=c}while(c===255);const d=n.length-r;let f=r;if(ud){zt.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(o===4){if(n[f++]===181){const m=aw(n,f);if(f+=2,m===49){const v=at(n,f);if(f+=4,v===1195456820){const _=n[f++];if(_===3){const b=n[f++],E=31&b,w=64&b,L=w?2+E*3:0,I=new Uint8Array(L);if(w){I[0]=b;for(let F=1;F16){const g=[];for(let _=0;_<16;_++){const b=n[f++].toString(16);g.push(b.length==1?"0"+b:b),(_===3||_===5||_===7||_===9)&&g.push("-")}const m=u-16,v=new Uint8Array(m);for(let _=0;_>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),bF([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,o,t)}function xF(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let i=0;for(;i+32>>24;if(r!==0&&r!==1)return{offset:t,size:e};const o=s.buffer,u=ds(new Uint8Array(o,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const m=s.getUint32(28);if(!m||i<32+m*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),tc={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 zT(s,e){const t=tc[e];return!!t&&!!t[s.slice(0,4)]}function Vd(s,e,t=!0){return!s.split(",").some(i=>!KT(i,e,t))}function KT(s,e,t=!0){var i;const n=So(t);return(i=n?.isTypeSupported(qd(s,e)))!=null?i:!1}function qd(s,e){return`${e}/mp4;codecs=${s}`}function v1(s){if(s){const e=s.substring(0,4);return tc.video[e]}return 2}function Gp(s){const e=hw();return s.split(",").reduce((t,i)=>{const r=e&&Pg(i)?9:tc.video[i];return r?(r*2+t)/(t?3:2):(tc.audio[i]+t)/(t?2:1)},0)}const wy={};function AF(s,e=!0){if(wy[s])return wy[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;nAF(t.toLowerCase(),e))}function DF(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)&&(T1(s,"audio")||T1(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 T1(s,e){return zT(s,e)&&KT(s,e)}function wF(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 LF(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 _1(s){const e=So(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 Mv(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const IF={supported:!0,powerEfficient:!0,smooth:!0},RF={supported:!1,smooth:!1,powerEfficient:!1},fw={supported:!0,configurations:[],decodingInfoResults:[IF]};function pw(s,e){return{supported:!1,configurations:e,decodingInfoResults:[RF],error:s}}function kF(s,e,t,i,n,r){const o=s.videoCodec,u=s.audioCodec?s.audioGroups:null,c=r?.audioCodec,d=r?.channels,f=d?parseInt(d):c?1/0:2;let g=null;if(u!=null&&u.length)try{u.length===1&&u[0]?g=e.groups[u[0]].channels:g=u.reduce((m,v)=>{if(v){const _=e.groups[v];if(!_)throw new Error(`Audio track group ${v} not found`);Object.keys(_.channels).forEach(b=>{m[b]=(m[b]||0)+_.channels[b]})}return m},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(m=>Pg(m))||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))||!!g&&He(f)&&Object.keys(g).some(m=>parseInt(m)>f)}function gw(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(fw);const r=[],o=OF(s),u=o.length,c=PF(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const g={type:"media-source"};if(u&&(g.video=o[f%u]),d){g.audio=c[f%d];const m=g.audio.bitrate;g.video&&m&&(g.video.bitrate-=m)}r.push(g)}if(n){const f=navigator.userAgent;if(n.split(",").some(g=>Pg(g))&&hw())return Promise.resolve(pw(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const g=NF(f);return i[g]||(i[g]=t.decodingInfo(f))})).then(f=>({supported:!f.some(g=>!g.supported),configurations:r,decodingInfoResults:f})).catch(f=>({supported:!1,configurations:r,decodingInfoResults:[],error:f}))}function OF(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=mw(s),n=s.width||640,r=s.height||480,o=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:qd(LF(c),"video"),width:n,height:r,bitrate:i,framerate:o};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function PF(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=mw(s);return n&&s.audioGroups?s.audioGroups.reduce((o,u)=>{var c;const d=u?(c=e.groups[u])==null?void 0:c.tracks:null;return d?d.reduce((f,g)=>{if(g.groupId===u){const m=parseFloat(g.channels||"");n.forEach(v=>{const _={contentType:qd(v,"audio"),bitrate:t?MF(v,r):r};m&&(_.channels=""+m),f.push(_)})}return f},o):o},[]):[]}function MF(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 mw(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function NF(s){let e="";const{audio:t,video:i}=s;if(i){const n=Mv(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=Mv(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const Nv=["NONE","TYPE-0","TYPE-1",null];function BF(s){return Nv.indexOf(s)>-1}const qp=["SDR","PQ","HLG"];function FF(s){return!!s&&qp.indexOf(s)>-1}var hp={No:"",Yes:"YES",v2:"v2"};function b1(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 x1(this._audioGroups,e)}hasSubtitleGroup(e){return x1(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 x1(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function UF(){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 $F(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||qp.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&UF(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const jF=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}},ai=(s,e)=>JSON.stringify(s,jF(e));function HF(s,e,t,i,n){const r=Object.keys(s),o=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=o&&parseInt(o)===2;let f=!1,g=!1,m=1/0,v=1/0,_=1/0,b=1/0,E=0,w=[];const{preferHDR:L,allowedVideoRanges:I}=$F(e,n);for(let q=r.length;q--;){const R=s[r[q]];f||(f=R.channels[2]>0),m=Math.min(m,R.minHeight),v=Math.min(v,R.minFramerate),_=Math.min(_,R.minBitrate),I.filter(z=>R.videoRanges[z]>0).length>0&&(g=!0)}m=He(m)?m:0,v=He(v)?v:0;const F=Math.max(1080,m),B=Math.max(30,v);_=He(_)?_:t,t=Math.max(_,t),g||(e=void 0);const V=r.length>1;return{codecSet:r.reduce((q,R)=>{const P=s[R];if(R===q)return q;if(w=g?I.filter(z=>P.videoRanges[z]>0):[],V){if(P.minBitrate>t)return vr(R,`min bitrate of ${P.minBitrate} > current estimate of ${t}`),q;if(!P.hasDefaultAudio)return vr(R,"no renditions with default or auto-select sound found"),q;if(u&&R.indexOf(u.substring(0,4))%5!==0)return vr(R,`audio codec preference "${u}" not found`),q;if(o&&!d){if(!P.channels[o])return vr(R,`no renditions with ${o} channel sound found (channels options: ${Object.keys(P.channels)})`),q}else if((!u||d)&&f&&P.channels[2]===0)return vr(R,"no renditions with stereo sound found"),q;if(P.minHeight>F)return vr(R,`min resolution of ${P.minHeight} > maximum of ${F}`),q;if(P.minFramerate>B)return vr(R,`min framerate of ${P.minFramerate} > maximum of ${B}`),q;if(!w.some(z=>P.videoRanges[z]>0))return vr(R,`no variants with VIDEO-RANGE of ${ai(w)} found`),q;if(c&&R.indexOf(c.substring(0,4))%5!==0)return vr(R,`video codec preference "${c}" not found`),q;if(P.maxScore=Gp(q)||P.fragmentError>s[q].fragmentError)?q:(b=P.minIndex,E=P.maxScore,R)},void 0),videoRanges:w,preferHDR:L,minFramerate:v,minBitrate:_,minIndex:b}}function vr(s,e){zt.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function yw(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 GF(s,e,t,i){return s.slice(t,i+1).reduce((n,r,o)=>{if(!r.codecSet)return n;const u=r.audioGroups;let c=n[r.codecSet];c||(n[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!u,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const d=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,u&&u.forEach(f=>{if(!f)return;const g=e.groups[f];g&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?g.hasDefault:g.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(g.channels).forEach(m=>{c.channels[m]=(c.channels[m]||0)+g.channels[m]}))}),n},{})}function E1(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 Lr(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 ul(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 zF(s,e,t,i,n){const r=e[i],u=e.reduce((m,v,_)=>{const b=v.uri;return(m[b]||(m[b]=[])).push(_),m},{})[r.uri];u.length>1&&(i=Math.max.apply(Math,u));const c=r.videoRange,d=r.frameRate,f=r.codecSet.substring(0,4),g=A1(e,i,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==f)return!1;const v=m.audioGroups,_=t.filter(b=>!v||v.indexOf(b.groupId)!==-1);return Lr(s,_,n)>-1});return g>-1?g:A1(e,i,m=>{const v=m.audioGroups,_=t.filter(b=>!v||v.indexOf(b.groupId)!==-1);return Lr(s,_,n)>-1})}function A1(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i{var i;const{fragCurrent:n,partCurrent:r,hls:o}=this,{autoLevelEnabled:u,media:c}=o;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,g=r?r.duration:n.duration,m=d-f.loading.start,v=o.minAutoLevel,_=n.level,b=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||_<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!u)return;const E=b>-1&&b!==_,w=!!t||E;if(!w&&(c.paused||!c.playbackRate||!c.readyState))return;const L=o.mainForwardBufferInfo;if(!w&&L===null)return;const I=this.bwEstimator.getEstimateTTFB(),F=Math.abs(c.playbackRate);if(m<=Math.max(I,1e3*(g/(F*2))))return;const B=L?L.len/F:0,V=f.loading.first?f.loading.first-f.loading.start:-1,N=f.loaded&&V>-1,q=this.getBwEstimate(),R=o.levels,P=R[_],z=Math.max(f.loaded,Math.round(g*(n.bitrate||P.averageBitrate)/8));let ee=N?m-V:m;ee<1&&N&&(ee=Math.min(m,f.loaded*8/q));const ie=N?f.loaded*1e3/ee:0,Q=I/1e3,oe=ie?(z-f.loaded)/ie:z*8/q+Q;if(oe<=B)return;const H=ie?ie*8:q,X=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,te=this.hls.config.abrBandWidthUpFactor;let ae=Number.POSITIVE_INFINITY,ce;for(ce=_-1;ce>v;ce--){const Se=R[ce].maxBitrate,be=!R[ce].details||X;if(ae=this.getTimeToLoadFrag(Q,H,g*Se,be),ae=oe||ae>g*10)return;N?this.bwEstimator.sample(m-Math.min(I,V),f.loaded):this.bwEstimator.sampleTTFB(m);const $=R[ce].maxBitrate;this.getBwEstimate()*te>$&&this.resetEstimator($);const se=this.findBestLevel($,v,ce,0,B,1,1);se>-1&&(ce=se),this.warn(`Fragment ${n.sn}${r?" part "+r.index:""} of level ${_} is loading too slowly; + Fragment duration: ${n.duration.toFixed(3)} + Time to underbuffer: ${B.toFixed(3)} s + Estimated load time for current fragment: ${oe.toFixed(3)} s + Estimated load time for down switch fragment: ${ae.toFixed(3)} s + TTFB estimate: ${V|0} ms + Current BW estimate: ${He(q)?q|0:"Unknown"} bps + New BW estimate: ${this.getBwEstimate()|0} bps + Switching to level ${ce} @ ${$|0} bps`),o.nextLoadLevel=o.nextAutoLevel=ce,this.clearTimer();const he=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===ce&&ce>0){const Se=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ce>0?"and switching down":""} + Fragment duration: ${n.duration.toFixed(3)} s + Time to underbuffer: ${Se.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,ce>v){let be=this.findBestLevel(this.hls.levels[v].bitrate,v,ce,0,Se,1,1);be===-1&&(be=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=be,this.resetEstimator(this.hls.levels[be].bitrate)}}};E||oe>ae*2?he():this.timer=self.setInterval(he,ae*1e3),o.trigger(M.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 ZB(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.FRAG_LOADING,this.onFragLoading,this),e.on(M.FRAG_LOADED,this.onFragLoaded,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.FRAG_LOADING,this.onFragLoading,this),e.off(M.FRAG_LOADED,this.onFragLoaded,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(M.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 me.BUFFER_ADD_CODEC_ERROR:case me.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case me.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const o=performance.now(),u=r?r.stats:i.stats,c=o-u.loading.start,d=u.loading.first?u.loading.first-u.loading.start:-1;if(u.loaded&&d>-1){const g=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(g,d),u.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,o=n?e+this.lastLevelLoadSec:0;return r+o}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;He(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===qe.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,o=this.hls.levels[t.level],u=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+r;o.loaded={bytes:u,duration:c},o.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(M.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==qe.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,n,1,1);if(r>-1)return r;const o=this.hls.firstLevel,u=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,r)&&o[e].loadError<=o[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:o}=i,u=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let f=r.abrBandWidthFactor,g=r.abrBandWidthUpFactor;if(d){const E=this.findBestLevel(c,o,n,d,0,f,g);if(E>=0)return this.rebufferNotice=-1,E}let m=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const E=this.bitrateTestDelay;E&&(m=(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*m)} ms`),f=g=1)}const v=this.findBestLevel(c,o,n,d,m,f,g);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${v}`)),v>-1)return v;const _=i.levels[o],b=i.loadLevelObj;return b&&_?.bitrate=t;H--){var oe;const X=_[H],te=H>g;if(!X)continue;if(w.useMediaCapabilities&&!X.supportedResult&&!X.supportedPromise){const be=navigator.mediaCapabilities;typeof be?.decodingInfo=="function"&&kF(X,P,V,N,e,q)?(X.supportedPromise=gw(X,P,be,this.supportedCache),X.supportedPromise.then(Pe=>{if(!this.hls)return;X.supportedResult=Pe;const Ae=this.hls.levels,Be=Ae.indexOf(X);Pe.error?this.warn(`MediaCapabilities decodingInfo error: "${Pe.error}" for level ${Be} ${ai(Pe)}`):Pe.supported?Pe.decodingInfoResults.some($e=>$e.smooth===!1||$e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Be} not smooth or powerEfficient: ${ai(Pe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Be} ${ai(Pe)}`),Be>-1&&Ae.length>1&&(this.log(`Removing unsupported level ${Be}`),this.hls.removeLevel(Be),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Pe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Pe}`)})):X.supportedResult=fw}if((B&&X.codecSet!==B||V&&X.videoRange!==V||te&&N>X.frameRate||!te&&N>0&&Nbe.smooth===!1))&&(!F||H!==z)){Q.push(H);continue}const ae=X.details,ce=(v?ae?.partTarget:ae?.averagetargetduration)||ee;let $;te?$=u*e:$=o*e;const se=ee&&n>=ee*2&&r===0?X.averageBitrate:X.maxBitrate,he=this.getTimeToLoadFrag(ie,$,se*ce,ae===void 0);if($>=se&&(H===f||X.loadError===0&&X.fragmentError===0)&&(he<=ie||!He(he)||I&&!this.bitrateTestDelay||he${H} adjustedbw(${Math.round($)})-bitrate=${Math.round($-se)} ttfb:${ie.toFixed(1)} avgDuration:${ce.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${he.toFixed(1)} firstSelection:${F} codecSet:${X.codecSet} videoRange:${X.videoRange} hls.loadLevel:${E}`)),F&&(this.firstSelection=H),H}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const vw={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const o=e(r);if(o>0)t=n+1;else if(o<0)i=n-1;else return r}return null}};function YF(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!He(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)&&C1(t,i,r)===0||WF(r,s,Math.min(n,i))))return r;const o=vw.search(e,C1.bind(null,t,i));return o&&(o!==s||!r)?o:r}function WF(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 C1(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 XF(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function Tw(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 vw.search(i,o=>o.cce?-1:(r=o,o.end<=t?1:o.start>t?-1:0)),r||null}return null}function Kp(s){switch(s.details){case me.FRAG_LOAD_TIMEOUT:case me.KEY_LOAD_TIMEOUT:case me.LEVEL_LOAD_TIMEOUT:case me.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function _w(s){return s.details.startsWith("key")}function bw(s){return _w(s)&&!!s.frag&&!s.frag.decryptdata}function D1(s,e){const t=Kp(e);return s.default[`${t?"timeout":"error"}Retry`]}function YT(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function w1(s){return qt(qt({},s),{errorRetry:null,timeoutRetry:null})}function Yp(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function Bv(s){return s===0&&navigator.onLine===!1}var us={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},fn={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class ZF extends Bn{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(M.ERROR,this.onError,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(M.ERROR,this.onError,this),e.off(M.ERROR,this.onErrorOut,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===qe.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var u;return(u=o.details)==null?void 0:u.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const n=this.hls,r=t.context;switch(t.details){case me.FRAG_LOAD_ERROR:case me.FRAG_LOAD_TIMEOUT:case me.KEY_LOAD_ERROR:case me.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case me.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Hu();return}case me.FRAG_GAP:case me.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=us.SendAlternateToPenaltyBox;return}case me.LEVEL_EMPTY_ERROR:case me.LEVEL_PARSING_ERROR:{var o;const c=t.parent===qe.MAIN?t.level:n.loadLevel;t.details===me.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case me.LEVEL_LOAD_ERROR:case me.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case me.AUDIO_TRACK_LOAD_ERROR:case me.AUDIO_TRACK_LOAD_TIMEOUT:case me.SUBTITLE_LOAD_ERROR:case me.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===bt.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===bt.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=us.SendAlternateToPenaltyBox,t.errorAction.flags=fn.MoveAllAlternatesMatchingHost;return}}return;case me.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:us.SendAlternateToPenaltyBox,flags:fn.MoveAllAlternatesMatchingHDCP};return;case me.KEY_SYSTEM_SESSION_UPDATE_FAILED:case me.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case me.KEY_SYSTEM_NO_SESSION:t.errorAction={action:us.SendAlternateToPenaltyBox,flags:fn.MoveAllAlternatesMatchingKey};return;case me.BUFFER_ADD_CODEC_ERROR:case me.REMUX_ALLOC_ERROR:case me.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case me.INTERNAL_EXCEPTION:case me.BUFFER_APPENDING_ERROR:case me.BUFFER_FULL_ERROR:case me.LEVEL_SWITCH_ERROR:case me.BUFFER_STALLED_ERROR:case me.BUFFER_SEEK_OVER_HOLE:case me.BUFFER_NUDGE_ON_STALL:t.errorAction=Hu();return}t.type===Ye.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Hu())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=D1(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Yp(n,r,Kp(e),e.response))return{action:us.RetryRequest,flags:fn.None,retryConfig:n,retryCount:r};const u=this.getLevelSwitchAction(e,t);return n&&(u.retryConfig=n,u.retryCount=r),u}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:o}=t.config,u=D1(_w(e)?o:r,e),c=t.levels.reduce((f,g)=>f+g.fragmentError,0);if(n&&(e.details!==me.FRAG_GAP&&n.fragmentError++,!bw(e)&&Yp(u,c,Kp(e),e.response)))return{action:us.RetryRequest,flags:fn.None,retryConfig:u,retryCount:c};const d=this.getLevelSwitchAction(e,i);return u&&(d.retryConfig=u,d.retryCount=c),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n){var r,o;const d=e.details;n.loadError++,d===me.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:g,loadLevel:m,minAutoLevel:v,maxAutoLevel:_}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const b=(r=e.frag)==null?void 0:r.type,w=(b===qe.AUDIO&&d===me.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===me.BUFFER_ADD_CODEC_ERROR||d===me.BUFFER_APPEND_ERROR))&&g.some(({audioCodec:V})=>n.audioCodec!==V),I=e.sourceBufferName==="video"&&(d===me.BUFFER_ADD_CODEC_ERROR||d===me.BUFFER_APPEND_ERROR)&&g.some(({codecSet:V,audioCodec:N})=>n.codecSet!==V&&n.audioCodec===N),{type:F,groupId:B}=(o=e.context)!=null?o:{};for(let V=g.length;V--;){const N=(V+m)%g.length;if(N!==m&&N>=v&&N<=_&&g[N].loadError===0){var u,c;const q=g[N];if(d===me.FRAG_GAP&&b===qe.MAIN&&e.frag){const R=g[N].details;if(R){const P=El(e.frag,R.fragments,e.frag.start);if(P!=null&&P.gap)continue}}else{if(F===bt.AUDIO_TRACK&&q.hasAudioGroup(B)||F===bt.SUBTITLE_TRACK&&q.hasSubtitleGroup(B))continue;if(b===qe.AUDIO&&(u=n.audioGroups)!=null&&u.some(R=>q.hasAudioGroup(R))||b===qe.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(R=>q.hasSubtitleGroup(R))||w&&n.audioCodec===q.audioCodec||I&&n.codecSet===q.codecSet||!w&&n.codecSet!==q.codecSet)continue}f=N;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:us.SendAlternateToPenaltyBox,flags:fn.None,nextAutoLevel:f}}return{action:us.SendAlternateToPenaltyBox,flags:fn.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case us.DoNothing:break;case us.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==me.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 fn.None:this.switchLevel(e,r);break;case fn.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=Nv[Nv.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case fn.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let m=f;m--;)if(this.variantHasKey(d[m],c)){var o,u;this.log(`Banned key found in level ${m} (${d[m].bitrate}bps) or audio group "${(o=d[m].audioGroups)==null?void 0:o.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${ds(c.keyId||[])}`),d[m].fragmentError++,d[m].loadError++,this.log(`Removing level ${m} with key error (${e.error})`),this.hls.removeLevel(m)}const g=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===i&&this.removeFragment(c.body);return}const d=c.range[e];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(f=>{const g=!this.isTimeBuffered(f.startPTS,f.endPTS,t);return g&&this.removeFragment(c.body),g})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,n=Su(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=o||c.partial===!0;r.range[u]=this.getBufferedTimes(i,e.part,f,d)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),qf(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]=L1(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Su(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},o=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||o;for(let f=0;f=g&&c<=m){r.time.push({startPTS:Math.max(o,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(og){const v=Math.max(o,n.start(f)),_=Math.min(u,n.end(f));_>v&&(r.partial=!0,r.time.push({startPTS:v,endPTS:_}))}else if(u<=g)break}return r}getPartialFragment(e){let t=null,i,n,r,o=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&qf(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),o<=i&&(t=f.body,o=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||qf(t))}getState(e){const t=Su(e),i=this.fragments[t];return i?i.buffered?qf(i)?Ki.PARTIAL:Ki.OK:Ki.APPENDING:Ki.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let o=0;o=n&&t<=r)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,n=t.part?null:t,r=Su(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r,type:o}=t;if(i.sn==="initSegment")return;const u=i.type;if(n){let d=this.activePartLists[u];d||(this.activePartLists[u]=d=[]),d.push(n)}this.timeRanges=r;const c=r[o];this.detectEvictedFragments(o,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Su(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let n=i.length;n--;){const r=t[i[n]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const u=this.fragments[o];if(!u)return;const c=u.body;c.type!==i||n&&!c.gap||c.starte&&(u.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Su(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=L1(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 qf(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 Su(s){return`${s.type}_${s.level}_${s.sn}`}function L1(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var xo={cbc:0,ctr:1};class e5{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 xo.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case xo.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 t5(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class i5{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let n=0;n<4;n++)i[n]=t.getUint32(n*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,n=i[0],r=i[1],o=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],g=c[2],m=c[3],v=new Uint32Array(256);let _=0,b=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 w=b^b<<1^b<<2^b<<3^b<<4;w=w>>>8^w&255^99,e[_]=w,t[w]=_;const L=v[_],I=v[L],F=v[I];let B=v[w]*257^w*16843008;n[_]=B<<24|B>>>8,r[_]=B<<16|B>>>16,o[_]=B<<8|B>>>24,u[_]=B,B=F*16843009^I*65537^L*257^_*16843008,d[w]=B<<24|B>>>8,f[w]=B<<16|B>>>16,g[w]=B<<8|B>>>24,m[w]=B,_?(_=L^v[v[v[F^L]]],b^=v[v[b]]):_=b=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;n{const u=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(u,t,i,n);const c=this.flush();c?r(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:o,remainderData:u}=this;if(n!==xo.cbc||t.byteLength!==16)return zt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=Pn(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 i5),d.expandKey(t);const f=o;return this.currentResult=d.decrypt(c.buffer,0,i),this.currentIV=c.slice(-16).buffer,f||null}webCryptoDecrypt(e,t,i,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,n));this.key=t,this.fastAesKey=new s5(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new e5(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(zt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,n)))}onWebCryptoError(e,t,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%r5;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(zt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const I1=Math.pow(2,17);class a5{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 ua({type:Ye.NETWORK_ERROR,details:me.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(_=>_[0]==="GAP")){c(k1(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new o(n),f=R1(e);e.loader=d;const g=w1(n.fragLoadPolicy.default),m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:I1};e.stats=d.stats;const v={onSuccess:(_,b,E,w)=>{this.resetLoader(e,d);let L=_.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(L.slice(0,16)),L=L.slice(16)),u({frag:e,part:null,payload:L,networkDetails:w})},onError:(_,b,E,w)=>{this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qt({url:i,data:void 0},_),error:new Error(`HTTP Error ${_.code} ${_.text}`),networkDetails:E,stats:w}))},onAbort:(_,b,E)=>{this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:_}))},onTimeout:(_,b,E)=>{this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:E,stats:_}))}};t&&(v.onProgress=(_,b,E,w)=>t({frag:e,part:null,payload:E,networkDetails:w})),d.load(f,m,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,o=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(k1(e,t));return}const d=this.loader=r?new r(n):new o(n),f=R1(e,t);e.loader=d;const g=w1(n.fragLoadPolicy.default),m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:I1};t.stats=d.stats,d.load(f,m,{onSuccess:(v,_,b,E)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const w={frag:e,part:t,payload:v.data,networkDetails:E};i(w),u(w)},onError:(v,_,b,E)=>{this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qt({url:f.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:b,stats:E}))},onAbort:(v,_,b)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:b,stats:v}))},onTimeout:(v,_,b)=>{this.resetLoader(e,d),c(new ua({type:Ye.NETWORK_ERROR,details:me.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:b,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),g=(c-d)*Math.round(i.loaded/d);i.total=i.loaded+g}else i.total=Math.max(i.loaded,i.total);const o=i.loading,u=n.loading;o.start?o.first+=u.first-u.start:(o.start=u.start,o.first=u.first),o.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function R1(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(He(n)&&He(r)){var o;let u=n,c=r;if(s.sn==="initSegment"&&o5((o=s.decryptdata)==null?void 0:o.method)){const d=r-n;d%16&&(c=r+(16-d%16)),n!==0&&(i.resetIV=!0,u=n-16)}i.rangeStart=u,i.rangeEnd=c}return i}function k1(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:Ye.MEDIA_ERROR,details:me.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new ua(i)}function o5(s){return s==="AES-128"||s==="AES-256"}class ua extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Sw extends Bn{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 XT{constructor(e,t,i,n=0,r=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=zf(),this.buffering={audio:zf(),video:zf(),audiovideo:zf()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=o}}function zf(){return{start:0,executeStart:0,executeEnd:0,end:0}}const O1={length:0,start:()=>0,end:()=>0};class ut{static isBuffered(e,t){if(e){const i=ut.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=ut.getBuffered(e);return ut.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i1&&e.sort((f,g)=>f.start-g.start||g.end-f.end);let n=-1,r=[];if(i)for(let f=0;f=e[f].start&&t<=e[f].end&&(n=f);const g=r.length;if(g){const m=r[g-1].end;e[f].start-mm&&(r[g-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let o=0,u,c=t,d=t;for(let f=0;f=g&&t<=m&&(n=f),t+i>=g&&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 M1(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))r=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function l5(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 u5=/^(\d+)x(\d+)$/,N1=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ti{constructor(e,t){typeof e=="string"&&(e=Ti.parseAttrList(e,t)),Zt(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=u5.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(N1.lastIndex=0;(i=N1.exec(e))!==null;){const o=i[1].trim();let u=i[2];const c=u.indexOf('"')===0&&u.lastIndexOf('"')===u.length-1;let d=!1;if(c)u=u.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=Fv(t,u);else if(!d&&!c)switch(o){case"CLOSED-CAPTIONS":if(u==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":zt.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=u}return n}}const c5="com.apple.hls.interstitial";function d5(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function h5(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class Ew{constructor(e,t,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:i,t){const r=t.attr;for(const o in r)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==r[o]){zt.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=Zt(new Ti({}),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"]);He(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(zt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(He(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===c5}get isValid(){return!!this.id&&!this._badValueForSameId&&He(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 f5=10;class p5{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?He(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||f5}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 Wp(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function B1(s,e){return!s&&!e?!0:!s||!e?!1:Wp(s,e)}function Gu(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function QT(s){switch(s){case"AES-128":case"AES-256":return xo.cbc;case"AES-256-CTR":return xo.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function ZT(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Uv(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function g5(s){const e=Uv(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Aw(s){const e=function(i,n,r){const o=i[n];i[n]=i[r],i[r]=o};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function Cw(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",o=n[1];r?(i.splice(-1,1),t=ZT(o)):t=g5(o)}}return t}const Xp=typeof self<"u"?self:void 0;var _i={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},hs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function fp(s){switch(s){case hs.FAIRPLAY:return _i.FAIRPLAY;case hs.PLAYREADY:return _i.PLAYREADY;case hs.WIDEVINE:return _i.WIDEVINE;case hs.CLEARKEY:return _i.CLEARKEY}}function Ly(s){switch(s){case _i.FAIRPLAY:return hs.FAIRPLAY;case _i.PLAYREADY:return hs.PLAYREADY;case _i.WIDEVINE:return hs.WIDEVINE;case _i.CLEARKEY:return hs.CLEARKEY}}function Cd(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[_i.FAIRPLAY,_i.WIDEVINE,_i.PLAYREADY,_i.CLEARKEY].filter(n=>!!e[n]):[];return!i[_i.WIDEVINE]&&t&&i.push(_i.WIDEVINE),i}const Dw=(function(s){return Xp!=null&&(s=Xp.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function m5(s,e,t,i){let n;switch(s){case _i.FAIRPLAY:n=["cenc","sinf"];break;case _i.WIDEVINE:case _i.PLAYREADY:n=["cenc"];break;case _i.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return y5(n,e,t,i)}function y5(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 v5(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function ww(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){const u=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(u){const c=ZT(u).subarray(0,16);return Aw(c),c}}return null}let xu={};class To{static clearKeyUriToKeyIdMap(){xu={}}static setKeyIdForUri(e,t){xu[e]=t}static addKeyIdForUri(e){const t=Object.keys(xu).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),xu[e]=i,i}constructor(e,t,i,n=[1],r=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Gu(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(iw(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Wp(e.keyFormatVersions,this.keyFormatVersions)&&B1(e.iv,this.iv)&&B1(e.keyId,this.keyId)}isSupported(){if(this.method){if(Gu(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case hs.FAIRPLAY:case hs.WIDEVINE:case hs.PLAYREADY:case hs.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(Gu(this.method)){let r=this.iv;return r||(typeof e!="number"&&(zt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=_5(e)),new To(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=xu[this.uri];if(r&&!Wp(this.keyId,r)&&To.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Cw(this.uri);if(i)switch(this.keyFormat){case hs.WIDEVINE:if(this.pssh=i,!this.keyId){const r=xF(i.buffer);if(r.length){var n;const o=r[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=F1(t));break;case hs.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=SF(r,null,i),this.keyId=ww(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const o=new Uint8Array(16);o.set(r,16-r.length),r=o}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=T5(t),r||(r=F1(t),r||(r=xu[this.uri])),r&&(this.keyId=r,To.setKeyIdForUri(this.uri,r))}return this}}function T5(s){const e=s?.[hs.WIDEVINE];return e?e.keyId:null}function F1(s){const e=s?.[hs.PLAYREADY];if(e){const t=Cw(e.uri);if(t)return ww(t)}return null}function _5(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const U1=/#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,$1=/#EXT-X-MEDIA:(.*)/g,b5=/^#EXT(?:INF|-X-TARGETDURATION):/m,Iy=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),S5=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 Ir{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:o.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for($1.lastIndex=0;(n=$1.exec(e))!==null;){const d=new Ti(n[1],i),f=d.TYPE;if(f){const g=u[f],m=r[f]||[];r[f]=m;const v=d.LANGUAGE,_=d["ASSOC-LANGUAGE"],b=d.CHANNELS,E=d.CHARACTERISTICS,w=d["INSTREAM-ID"],L={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?Ir.resolve(d.URI,t):""};if(_&&(L.assocLang=_),b&&(L.channels=b),E&&(L.characteristics=E),w&&(L.instreamId=w),g!=null&&g.length){const I=Ir.findGroup(g,L.groupId)||g[0];V1(L,I,"audioCodec"),V1(L,I,"textCodec")}m.push(L)}}return r}static parseLevelPlaylist(e,t,i,n,r,o){var u;const c={url:t},d=new p5(t),f=d.fragments,g=[];let m=null,v=0,_=0,b=0,E=0,w=0,L=null,I=new Cy(n,c),F,B,V,N=-1,q=!1,R=null,P;if(Iy.lastIndex=0,d.m3u8=e,d.hasVariableRefs=P1(e),((u=Iy.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(F=Iy.exec(e))!==null;){q&&(q=!1,I=new Cy(n,c),I.playlistOffset=b,I.setStart(b),I.sn=v,I.cc=E,w&&(I.bitrate=w),I.level=i,m&&(I.initSegment=m,m.rawProgramDateTime&&(I.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(I.setByteRange(R),R=null)));const Q=F[1];if(Q){I.duration=parseFloat(Q);const oe=(" "+F[2]).slice(1);I.title=oe||null,I.tagList.push(oe?["INF",Q,oe]:["INF",Q])}else if(F[3]){if(He(I.duration)){I.playlistOffset=b,I.setStart(b),V&&z1(I,V,d),I.sn=v,I.level=i,I.cc=E,f.push(I);const oe=(" "+F[3]).slice(1);I.relurl=Fv(d,oe),$v(I,L,g),L=I,b+=I.duration,v++,_=0,q=!0}}else{if(F=F[0].match(S5),!F){zt.warn("No matches on slow regex match for level playlist!");continue}for(B=1;B0&&K1(d,oe,F),v=d.startSN=parseInt(H);break;case"SKIP":{d.skippedSegments&&oa(d,oe,F);const te=new Ti(H,d),ae=te.decimalInteger("SKIPPED-SEGMENTS");if(He(ae)){d.skippedSegments+=ae;for(let $=ae;$--;)f.push(null);v+=ae}const ce=te.enumeratedString("RECENTLY-REMOVED-DATERANGES");ce&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ce.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&oa(d,oe,F),d.targetduration=Math.max(parseInt(H),1);break;case"VERSION":d.version!==null&&oa(d,oe,F),d.version=parseInt(H);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||oa(d,oe,F),d.live=!1;break;case"#":(H||X)&&I.tagList.push(X?[H,X]:[H]);break;case"DISCONTINUITY":E++,I.tagList.push(["DIS"]);break;case"GAP":I.gap=!0,I.tagList.push([oe]);break;case"BITRATE":I.tagList.push([oe,H]),w=parseInt(H)*1e3,He(w)?I.bitrate=w:w=0;break;case"DATERANGE":{const te=new Ti(H,d),ae=new Ew(te,d.dateRanges[te.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ae.isValid||d.skippedSegments?d.dateRanges[ae.id]=ae:zt.warn(`Ignoring invalid DATERANGE tag: "${H}"`),I.tagList.push(["EXT-X-DATERANGE",H]);break}case"DEFINE":{{const te=new Ti(H,d);"IMPORT"in te?l5(d,te,o):M1(d,te,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?oa(d,oe,F):f.length>0&&K1(d,oe,F),d.startCC=E=parseInt(H);break;case"KEY":{const te=j1(H,t,d);if(te.isSupported()){if(te.method==="NONE"){V=void 0;break}V||(V={});const ae=V[te.keyFormat];ae!=null&&ae.matches(te)||(ae&&(V=Zt({},V)),V[te.keyFormat]=te)}else zt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${H}"`);break}case"START":d.startTimeOffset=H1(H);break;case"MAP":{const te=new Ti(H,d);if(I.duration){const ae=new Cy(n,c);q1(ae,te,i,V),m=ae,I.initSegment=m,m.rawProgramDateTime&&!I.rawProgramDateTime&&(I.rawProgramDateTime=m.rawProgramDateTime)}else{const ae=I.byteRangeEndOffset;if(ae){const ce=I.byteRangeStartOffset;R=`${ae-ce}@${ce}`}else R=null;q1(I,te,i,V),m=I,q=!0}m.cc=E;break}case"SERVER-CONTROL":{P&&oa(d,oe,F),P=new Ti(H),d.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),d.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&oa(d,oe,F);const te=new Ti(H);d.partTarget=te.decimalFloatingPoint("PART-TARGET");break}case"PART":{let te=d.partList;te||(te=d.partList=[]);const ae=_>0?te[te.length-1]:void 0,ce=_++,$=new Ti(H,d),se=new lF($,I,c,ce,ae);te.push(se),I.duration+=se.duration;break}case"PRELOAD-HINT":{const te=new Ti(H,d);d.preloadHint=te;break}case"RENDITION-REPORT":{const te=new Ti(H,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(te);break}default:zt.warn(`line parsed but not handled: ${F}`);break}}}L&&!L.relurl?(f.pop(),b-=L.duration,d.partList&&(d.fragmentHint=L)):d.partList&&($v(I,L,g),I.cc=E,d.fragmentHint=I,V&&z1(I,V,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const z=f.length,ee=f[0],ie=f[z-1];if(b+=d.skippedSegments*d.targetduration,b>0&&z&&ie){d.averagetargetduration=b/z;const Q=ie.sn;d.endSN=Q!=="initSegment"?Q:0,d.live||(ie.endList=!0),N>0&&(E5(f,N),ee&&g.unshift(ee))}return d.fragmentHint&&(b+=d.fragmentHint.duration),d.totalduration=b,g.length&&d.dateRangeTagCount&&ee&&Lw(g,d),d.endCC=E,d}}function Lw(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const u=e.fragments[e.fragments.length-1];s.push(u),t++}else return;const i=s[t-1],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let u=r.length;u--;){const c=e.dateRanges[r[u]],d=c.startDate.getTime();c.tagAnchor=i.ref;for(let f=t;f--;){var o;if(((o=s[f])==null?void 0:o.sn)=u||i===0){var o;const c=(((o=t[i+1])==null?void 0:o.start)||n)-r.start;if(e<=u+c*1e3){const d=t[i].sn-s.startSN;if(d<0)return-1;const f=s.fragments;if(f.length>t.length){const m=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=m;v>d;v--){const _=f[v].programDateTime;if(e>=_&&e<_+f[v].duration*1e3)return v}}return d}}}return-1}function j1(s,e,t){var i,n;const r=new Ti(s,t),o=(i=r.METHOD)!=null?i:"",u=r.URI,c=r.hexadecimalInteger("IV"),d=r.KEYFORMATVERSIONS,f=(n=r.KEYFORMAT)!=null?n:"identity";u&&r.IV&&!c&&zt.error(`Invalid IV: ${r.IV}`);const g=u?Ir.resolve(u,e):"",m=(d||"1").split("/").map(Number).filter(Number.isFinite);return new To(o,g,f,m,c,r.KEYID)}function H1(s){const t=new Ti(s).decimalFloatingPoint("TIME-OFFSET");return He(t)?t:null}function G1(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const n=t.filter(r=>zT(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 V1(s,e,t){const i=e[t];i&&(s[t]=i)}function E5(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 $v(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function q1(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 z1(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 oa(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function K1(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Ry(s,e){const t=e.startPTS;if(He(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 Iw(s,e,t,i,n,r,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let c=t,d=i;const f=e.startPTS,g=e.endPTS;if(He(f)){const w=Math.abs(f-t);s&&w>s.totalduration?o.warn(`media timestamps and playlist times differ by ${w}s for level ${e.level} ${s.url}`):He(e.deltaPTS)?e.deltaPTS=Math.max(w,e.deltaPTS):e.deltaPTS=w,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,g),i=Math.max(i,g),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const m=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 _;const b=v-s.startSN,E=s.fragments;for(E[b]=e,_=b;_>0;_--)Ry(E[_],E[_-1]);for(_=b;_=0;f--){const g=n[f].initSegment;if(g){i=g;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;w5(s,e,(f,g,m,v)=>{if((!e.startCC||e.skippedSegments)&&g.cc!==f.cc){const _=f.cc-g.cc;for(let b=m;b{var g;f&&(!f.initSegment||f.initSegment.relurl===((g=i)==null?void 0:g.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=C5(s.dateRanges,e,t));const f=s.fragments.filter(g=>g.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let g=1;g{g.elementaryStreams=f.elementaryStreams,g.stats=f.stats}),r?Iw(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Rw(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const d=e.advancedDateTime;if(e.advanced&&d){const f=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=f),e.driftEndTime=d,e.driftEnd=f}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function C5(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=Zt({},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 Ew(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ai(i[c].attr)}"`)}),r):i}function D5(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const o=s[n],u=e[n+i];o&&u&&o.index===u.index&&o.fragment.sn===u.fragment.sn?t(o,u):i--}}}function w5(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,u=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=n;d<=r;d++){const f=c[o+d];let g=u[d];if(i&&!g&&f&&(g=e.fragments[d]=f),f&&g){t(f,g,d,u);const m=f.relurl,v=g.relurl;if(m&&L5(m,v)){e.playlistParsingError=Y1(`media sequence mismatch ${g.sn}:`,s,e,f,g);return}else if(f.cc!==g.cc){e.playlistParsingError=Y1(`discontinuity sequence mismatch (${f.cc}!=${g.cc})`,s,e,f,g);return}}}}function Y1(s,e,t,i,n){return new Error(`${s} ${n.url} +Playlist starting @${e.startSN} +${e.m3u8} + +Playlist starting @${t.startSN} +${t.m3u8}`)}function Rw(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let o=0;if(r&&ie){const r=i[i.length-1].duration*1e3;r{var i;(i=e.details)==null||i.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function L5(s,e){return s!==e&&e?X1(s)!==X1(e):!1}function X1(s){return s.replace(/\?[^?]*$/,"")}function Nd(s,e){for(let i=0,n=s.length;is.startCC)}function Q1(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Nw(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:o,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,g=c?c.currentTime:0,m=ut.bufferInfo(d||c,g,o.maxBufferHole),v=!m.len;if(this.log(`Media seeking to ${He(g)?g.toFixed(3):g}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===Ie.ENDED)this.resetLoadingState();else if(u){const _=o.maxFragLookUpTolerance,b=u.start-_,E=u.start+u.duration+_;if(v||Em.end){const w=g>E;(g_&&(this.lastCurrentTime=g),!this.loadingParts){const b=Math.max(m.end,g),E=this.shouldLoadParts(this.getLevelDetails(),b);E&&(this.log(`LL-Part loading ON after seeking to ${g.toFixed(2)} with buffer @${b.toFixed(2)}`),this.loadingParts=E)}}this.hls.hasEnoughToStart||(this.log(`Setting ${v?"startPosition":"nextLoadPosition"} to ${g} for seek without enough to start`),this.nextLoadPosition=g,v&&(this.startPosition=g)),v&&this.state===Ie.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 a5(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new WT(e.config)}registerListeners(){const{hls:e}=this;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Ie.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=Ie.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=ut.bufferedInfo(r,e.start,0));const o=e.nextStart;if(o&&o>n&&o{const o=r.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(o,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const o=this.state,u=r.frag;if(this.fragContextChanged(u)){(o===Ie.FRAG_LOADING||!this.fragCurrent&&o===Ie.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=Ie.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(M.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===Ie.STOPPED||this.state===Ie.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Ki.APPENDING){const r=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(u,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ki.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(M.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const n=i?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{frag:r,payload:o}=i,u=r.decryptdata;if(o&&o.byteLength>0&&u!=null&&u.key&&u.iv&&Gu(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),u.key.buffer,u.iv.buffer,QT(u.method)).catch(d=>{throw n.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(M.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===Ie.STOPPED||this.state===Ie.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!==Ie.STOPPED&&(this.state=Ie.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,n;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(n=r.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(u.message),!o||o.mediaKeys?!1:(this.hls.trigger(M.ERROR,{type:Ye.KEY_SYSTEM_ERROR,details:me.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?k5.toString(ut.getBuffered(i)):"(detached)"})`),Pi(e)){var n;if(e.type!==qe.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(u=>!!o[u])){this.state=Ie.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=Ie.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,o=!r||r.length===0||r.some(c=>!c),u=new XT(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Ie.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(M.KEY_LOADED,m),this.state===Ie.KEY_LOADING&&(this.state=Ie.IDLE),m}),this.hls.trigger(M.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(u=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Pi(e)&&(!c||e.sn!==c.sn)){const m=this.shouldLoadParts(t.details,e.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=m)}if(i=Math.max(e.start,i||0),this.loadingParts&&Pi(e)){const m=o.partList;if(m&&n){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const v=this.getNextPart(m,e,i);if(v>-1){const _=m[v];e=this.fragCurrent=_.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${_.index} (${v}/${m.length-1}) of ${this.fragInfo(e,!1,_)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=_.start+_.duration,this.state=Ie.FRAG_LOADING;let b;return u?b=u.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,_,t,n)).catch(E=>this.handleFragLoadError(E)):b=this.doFragPartsLoad(e,_,t,n).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(M.FRAG_LOADING,{frag:e,part:_,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):b}else if(!e.url||this.loadedEndOfParts(m,i))return Promise.resolve(null)}}if(Pi(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=o.partList)==null?void 0:d.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),He(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ie.FRAG_LOADING;const f=this.config.progressive&&e.type!==qe.SUBTITLE;let g;return f&&u?g=u.then(m=>!m||this.fragContextChanged(m.frag)?null:this.fragmentLoader.load(e,n)).catch(m=>this.handleFragLoadError(m)):g=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([m])=>(!f&&n&&n(m),m)).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(M.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g}doFragPartsLoad(e,t,i,n){return new Promise((r,o)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=g=>{this.fragmentLoader.loadPart(e,g,n).then(m=>{c[g.index]=m;const v=m.part;this.hls.trigger(M.FRAG_LOADED,m);const _=W1(i.details,e.sn,g.index+1)||Pw(d,e.sn,g.index+1);if(_)f(_);else return r({frag:e,part:v,partsLoaded:c})}).catch(o)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===me.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ye.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(M.ERROR,t)}else this.hls.trigger(M.ERROR,{type:Ye.OTHER_ERROR,details:me.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Ie.PARSING){!this.fragCurrent&&this.state!==Ie.STOPPED&&this.state!==Ie.ERROR&&(this.state=Ie.IDLE);return}const{frag:i,part:n,level:r}=t,o=self.performance.now();i.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const u=this.getLevelDetails(),d=u&&i.sn>u.endSN||this.shouldLoadParts(u,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,n,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===qe.SUBTITLE)return!1;const o=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const u=t[n],c=u.details,d=o>-1?W1(c,r,o):null,f=d?d.fragment:Ow(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!==Ie.PARSING)return;const{data1:o,data2:u}=e;let c=o;if(u&&(c=Pn(o,u)),!c.length)return;const d=this.initPTS[t.cc],f=d?-d.baseTime/d.timescale:void 0,g={type:e.type,frag:t,part:i,chunkMeta:n,offset:f,parent:t.type,data:c};if(this.hls.trigger(M.BUFFER_APPENDING,g),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ut.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=ut.bufferInfo(t,i,0),r=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-o,n.end-o),i+o);e.start-u>o&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!He(n))return null;const o=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,i,n){const r=ut.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(r.nextStart<=o.end||o.gap)){const u=Math.max(Math.min(r.nextStart,o.end)-t,n);return ut.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=qe.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,o=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const g=r.initialLiveManifestSize;if(n=o?m:v)||c.start:e;this.log(`Setting startPosition to ${_} to match start frag at live edge. mainStart: ${m} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=_}}else e<=o&&(c=i[0]);if(!c){const g=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,g,t)}let f=this.filterReplacedPrimary(c,t);if(!f&&c){const g=c.sn-t.startSN;f=this.filterReplacedPrimary(i[g+1]||null,t)}return this.mapToInitFragWhenRequired(f)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Ki.OK||i===Ki.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){const u=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(u!==null&&i.len+u.len>=r){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(Z1(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(Z1(this.config)&&e.type!==qe.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const r=i?.playerQueue;if(r)for(let o=r.length;o--;){const u=r[o].interstitial;if(u.appendInPlace&&e.start>=u.startTime&&e.end<=u.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,o=!0;for(let u=0,c=e.length;u-1&&ii.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=YF(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const o=t[r-e.startSN];i.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Tw(e,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:o,endSN:u}=i;const{fragmentHint:c}=i,{maxFragLookUpTolerance:d}=n,f=i.partList,g=!!(this.loadingParts&&f!=null&&f.length&&c);g&&!this.bitrateTest&&f[f.length-1].fragment.sn===c.sn&&(o=o.concat(c),u=c.sn);let m;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;m=El(r,o,e,b)}else m=o[o.length-1];if(m){const _=m.sn-i.startSN,b=this.fragmentTracker.getState(m);if((b===Ki.OK||b===Ki.PARTIAL&&m.gap)&&(r=m),r&&m.sn===r.sn&&(!g||f[0].fragment.sn>m.sn||!i.live)&&m.level===r.level){const w=o[_+1];m.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&&Pi(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!==Ie.FRAG_LOADING_WAITING_RETRY)&&(this.state=Ie.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const w=this.getCurrentContext(t.chunkMeta);w&&(t.frag=w.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var r;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const o=t.details===me.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=Ie.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:g}=u,m=!!g,v=m&&c===us.RetryRequest,_=m&&!u.resolved&&d===fn.MoveAllAlternatesMatchingHost,b=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&_&&Pi(n)&&!n.endList&&b&&!bw(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||_)&&f=t||i&&!Bv(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ie.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Ie.PARSING||this.state===Ie.PARSED){const t=e.frag,i=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,t?.duration||10);const o=!r;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===qe.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ie.STOPPED&&(this.state=Ie.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=ut.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===Ie.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ie.STOPPED&&(this.state=Ie.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 g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),c||!1;const m=n?0:Iw(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(M.LEVEL_PTS_UPDATED,{details:r,level:i,drift:m,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(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.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=Ie.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(M.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===qe.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 Z1(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class Fw{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=O5(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function O5(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function $5(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],o=r>>2&15;if(o>12){const v=new Error(`invalid ADTS sampling index:${o}`);s.emit(M.ERROR,M.ERROR,{type:Ye.MEDIA_ERROR,details:me.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const u=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,d="mp4a.40."+u,f=n[o];let g=o;(u===5||u===29)&&(g-=3);const m=[u<<3|(g&14)>>1,(g&1)<<7|c<<3];return zt.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${o})`),{config:m,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function $w(s,e){return s[e]===255&&(s[e+1]&246)===240}function jw(s,e){return s[e+1]&1?7:9}function i_(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function j5(s,e){return e+5=s.length)return!1;const i=i_(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||Zp(s,n)}return!1}function Hw(s,e,t,i,n){if(!s.samplerate){const r=$5(e,t,i,n);if(!r)return;Zt(s,r)}}function Gw(s){return 1024*9e4/s}function V5(s,e){const t=jw(s,e);if(e+t<=s.length){const i=i_(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Vw(s,e,t,i,n){const r=Gw(s.samplerate),o=i+n*r,u=V5(e,t);let c;if(u){const{frameLength:g,headerLength:m}=u,v=m+g,_=Math.max(0,t+v-e.length);_?(c=new Uint8Array(v-m),c.set(e.subarray(t+m,e.length),0)):c=e.subarray(t+m,t+v);const b={unit:c,pts:o};return _||s.samples.push(b),{sample:b,length:v,missing:_}}const d=e.length-t;return c=new Uint8Array(d),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:d,missing:-1}}function q5(s,e){return t_(s,e)&&Mg(s,e+6)+10<=s.length-e}function z5(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Oy(s,e=0,t=1/0){return K5(s,e,t,Uint8Array)}function K5(s,e,t,i){const n=Y5(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const o=W5(s)?s.byteOffset:0,u=(o+s.byteLength)/r,c=(o+e)/r,d=Math.floor(Math.max(0,Math.min(c,u))),f=Math.floor(Math.min(d+Math.max(t,0),u));return new i(n,d,f-d)}function Y5(s){return s instanceof ArrayBuffer?s:s.buffer}function W5(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function X5(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=mn(Oy(s.data,1,i)),r=s.data[2+i],o=s.data.subarray(3+i).indexOf(0);if(o===-1)return;const u=mn(Oy(s.data,3+i,o));let c;return n==="-->"?c=mn(Oy(s.data,4+i+o)):c=z5(s.data.subarray(4+i+o)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function Q5(s){if(s.size<2)return;const e=mn(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function Z5(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=mn(s.data.subarray(t),!0);t+=i.length+1;const n=mn(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=mn(s.data.subarray(1));return{key:s.type,info:"",data:e}}function J5(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=mn(s.data.subarray(t),!0);t+=i.length+1;const n=mn(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=mn(s.data);return{key:s.type,info:"",data:e}}function eU(s){return s.type==="PRIV"?Q5(s):s.type[0]==="W"?J5(s):s.type==="APIC"?X5(s):Z5(s)}function tU(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Mg(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const Kf=10,iU=10;function qw(s){let e=0;const t=[];for(;t_(s,e);){const i=Mg(s,e+6);s[e+5]>>6&1&&(e+=Kf),e+=Kf;const n=e+i;for(;e+iU0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:gn.audioId3,duration:Number.POSITIVE_INFINITY});n{if(He(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Yf=null;const rU=[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],aU=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],oU=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],lU=[0,1,1,4];function Kw(s,e,t,i,n){if(t+24>e.length)return;const r=Yw(e,t);if(r&&t+r.frameLength<=e.length){const o=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*o,c={unit:e.subarray(t,t+r.frameLength),pts:u,dts:u};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function Yw(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const o=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=rU[c*14+n-1]*1e3,g=aU[(t===3?0:t===2?1:2)*3+r],m=u===3?1:2,v=oU[t][i],_=lU[i],b=v*8*_,E=Math.floor(v*d/g+o)*_;if(Yf===null){const I=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yf=I?parseInt(I[1]):0}return Yf&&Yf<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:g,channelCount:m,frameLength:E,samplesPerFrame:b}}}function r_(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Ww(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=s[e];const u=Math.min(i,8),c=8-u;r[0]=4278190080>>>24+c<>c,t=t?t<e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const u=[48e3,44100,32e3][r],c=e[t+4]&63,f=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+f>e.length)return-1;const g=e[t+6]>>5;let m=0;g===2?m+=2:(g&1&&g!==1&&(m+=2),g&4&&(m+=2));const v=(e[t+6]<<8|e[t+7])>>12-m&1,b=[2,1,2,3,3,4,4,5][g]+v,E=e[t+5]>>3,w=e[t+5]&7,L=new Uint8Array([r<<6|E<<1|w>>2,(w&3)<<6|g<<3|v<<2|c>>4,c<<4&224]),I=1536/u*9e4,F=i+n*I,B=e.subarray(t,t+f);return s.config=L,s.channelCount=b,s.samplerate=u,s.samples.push({unit:B,pts:F}),f}class hU extends n_{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=Yd(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&s_(t)!==void 0&&Qw(e,i)<=16)return!1;for(let n=e.length;i{const o=_F(r);if(fU.test(o.schemeIdUri)){const u=e2(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=o.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:gn.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=e2(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:u,pts:u,type:gn.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 e2(s,e){return He(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class gU{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new WT(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xo.cbc)}decryptAacSample(e,t,i){const n=e[t].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),o=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(o).then(u=>{const c=new Uint8Array(u);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r{r.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)}).catch(n)}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const o=r[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,n,o),!this.decrypter.isSync()))return}}}}class Jw{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,n=i.length;if(n){const r=i[n-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const n=t.byteLength;let r=e.naluState||0;const o=r,u=[];let c=0,d,f,g,m=-1,v=0;for(r===-1&&(m=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const _={data:t.subarray(m,f),type:v};u.push(_)}else{const _=this.getLastNalUnit(e.samples);_&&(o&&c<=4-o&&_.state&&(_.data=_.data.subarray(0,_.data.byteLength-o)),f>0&&(_.data=Pn(_.data,t.subarray(0,f)),_.state=0))}c=0&&r>=0){const _={data:t.subarray(m,n),type:v,state:r};u.push(_)}if(u.length===0){const _=this.getLastNalUnit(e.samples);_&&(_.data=Pn(_.data,t))}return e.naluState=r,u}}class Bd{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,n=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");n.set(e.subarray(i,i+r)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&zt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class mU extends Jw{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let o=this.VideoSample,u,c=!1;i.data=null,o&&r.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(d=>{var f,g;switch(d.type){case 1:{let b=!1;u=!0;const E=d.data;if(c&&E.length>4){const w=this.readSliceType(E);(w===2||w===4||w===7||w===9)&&(b=!0)}if(b){var m;(m=o)!=null&&m.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=b;break}case 5:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:{u=!0,qT(d.data,1,i.pts,t.samples);break}case 7:{var v,_;u=!0,c=!0;const b=d.data,E=this.readSPS(b);if(!e.sps||e.width!==E.width||e.height!==E.height||((v=e.pixelRatio)==null?void 0:v[0])!==E.pixelRatio[0]||((_=e.pixelRatio)==null?void 0:_[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[b];const w=b.subarray(1,4);let L="avc1.";for(let I=0;I<3;I++){let F=w[I].toString(16);F.length<2&&(F="0"+F),L+=F}e.codec=L}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(g=o)!=null&&g.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Bd(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let o=0;o{var f,g;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var m;(m=o)!=null&&m.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:u=!0,(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:u=!0,qT(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Zt(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 _ in v.params)e.params[_]=v.params[_]}this.pushParameterSet(e.sps,d.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(u=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const v=this.readPPS(d.data);for(const _ in v)e.params[_]=v[_]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:u=!0,e.audFound=!0,(g=o)!=null&&g.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}o&&u&&o.units.push(d)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[i]=e[n],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Bd(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 Bd(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const n=t.readBits(2),r=t.readBoolean(),o=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),v=t.readUByte(),_=t.readUByte(),b=t.readUByte(),E=t.readUByte(),w=t.readUByte(),L=[],I=[];for(let We=0;We0)for(let We=i;We<8;We++)t.readBits(2);for(let We=0;We1&&t.readEG();for(let _t=0;_t0&&Ct<16?(se=Gi[Ct-1],he=$t[Ct-1]):Ct===255&&(se=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(),Ae=t.readBoolean(),Ae&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(be=t.readBits(32),Pe=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const $t=t.readBoolean(),xs=t.readBoolean();let Oe=!1;($t||xs)&&(Oe=t.readBoolean(),Oe&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Oe&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Fe=0;Fe<=i;Fe++){Se=t.readBoolean();const je=Se||t.readBoolean();let Qe=!1;je?t.readEG():Qe=t.readBoolean();const rt=Qe?1:t.readUEG()+1;if($t)for(let pt=0;pt>We&1)<<31-We)>>>0;let It=Ni.toString(16);return o===1&&It==="2"&&(It="6"),{codecString:`hvc1.${ht}${o}.${It}.${r?"H":"L"}${w}.B0`,params:{general_tier_flag:r,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[g,m,v,_,b,E],general_level_idc:w,bit_depth:ee+8,bit_depth_luma_minus8:ee,bit_depth_chroma_minus8:ie,min_spatial_segmentation_idc:$,chroma_format_idc:F,frame_rate:{fixed:Se,fps:Pe/be}},width:$e,height:Je,pixelRatio:[se,he]}}readPPS(e){const t=new Bd(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),r=t.readBoolean();let o=1;return r&&n?o=0:r?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ji=188;class po{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=po.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(Ji*5,t-Ji)+1,n=0;for(;n1&&(o===0&&u>2||c+Ji>i))return o}else{if(u)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:rw[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=po.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=po.createTrack("audio",n),this._id3Track=po.createTrack("id3"),this._txtTrack=po.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const o=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=o.pid,g=o.pesData,m=u.pid,v=c.pid,_=u.pesData,b=c.pesData,E=null,w=this.pmtParsed,L=this._pmtId,I=e.length;if(this.remainderData&&(e=Pn(this.remainderData,e),I=e.length,this.remainderData=null),I>4;let z;if(P>1){if(z=N+5+e[N+4],z===N+Ji)continue}else z=N+4;switch(R){case f:q&&(g&&(r=Eu(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,r,!1)),g={data:[],size:0}),g&&(g.data.push(e.subarray(z,N+Ji)),g.size+=N+Ji-z);break;case m:if(q){if(_&&(r=Eu(_,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}_={data:[],size:0}}_&&(_.data.push(e.subarray(z,N+Ji)),_.size+=N+Ji-z);break;case v:q&&(b&&(r=Eu(b,this.logger))&&this.parseID3PES(c,r),b={data:[],size:0}),b&&(b.data.push(e.subarray(z,N+Ji)),b.size+=N+Ji-z);break;case 0:q&&(z+=e[z]+1),L=this._pmtId=vU(e,z);break;case L:{q&&(z+=e[z]+1);const ee=TU(e,z,this.typeSupported,i,this.observer,this.logger);f=ee.videoPid,f>0&&(o.pid=f,o.segmentCodec=ee.segmentVideoCodec),m=ee.audioPid,m>0&&(u.pid=m,u.segmentCodec=ee.segmentAudioCodec),v=ee.id3Pid,v>0&&(c.pid=v),E!==null&&!w&&(this.logger.warn(`MPEG-TS PMT found at ${N} after unknown PID '${E}'. Backtracking to sync byte @${F} to parse all TS packets.`),E=null,N=F-188),w=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=R;break}}else B++;B>0&&Gv(this.observer,new Error(`Found ${B} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=g,u.pesData=_,c.pesData=b;const V={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples(V),V}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,o=i.pesData,u=t.pesData,c=n.pesData;let d;if(o&&(d=Eu(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=o,u&&(d=Eu(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=Eu(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 gU(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new mU:e==="hevc"&&(this.videoParser=new yU))}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 g=n.missing,m=n.sample.unit.byteLength;if(g===-1)r=Pn(n.sample.unit,r);else{const v=m-g;n.sample.unit.set(r.subarray(0,g),v),e.samples.push(n.sample),i=n.missing}}let o,u;for(o=i,u=r.length;o0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Zt({},t,{type:this._videoTrack?gn.emsg:gn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Hv(s,e){return((s[e+1]&31)<<8)+s[e+2]}function vU(s,e){return(s[e+10]&31)<<8|s[e+11]}function TU(s,e,t,i,n,r){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(s[e+1]&15)<<8|s[e+2],c=e+3+u-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e0){let m=e+5,v=g;for(;v>2;){s[m]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=f,o.segmentAudioCodec="ac3"));const b=s[m+1]+2;m+=b,v-=b}}break;case 194:case 135:return Gv(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),o;case 36:o.videoPid===-1&&(o.videoPid=f,o.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=g+5}return o}function Gv(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(M.ERROR,M.ERROR,{type:Ye.MEDIA_ERROR,details:me.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Py(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Eu(s,e){let t=0,i,n,r,o,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Pn(c[0],c[1]),c.splice(1,1);if(i=c[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(n=(i[4]<<8)+i[5],n&&n>s.size-6)return null;const f=i[7];f&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,f&64?(u=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-u>60*9e4&&(e.warn(`${Math.round((o-u)/9e4)}s delta between PTS and DTS, align them`),o=u)):u=o),r=i[8];let g=r+9;if(s.size<=g)return null;s.size-=g;const m=new Uint8Array(s.size);for(let v=0,_=c.length;v<_;v++){i=c[v];let b=i.byteLength;if(g)if(g>b){g-=b;continue}else i=i.subarray(g),b-=g,g=0;m.set(i,t),t+=b}return n&&(n-=r+3),{data:m,pts:o,dts:u,len:n}}return null}class _U{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 ao=Math.pow(2,32)-1;class ge{static init(){ge.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in ge.types)ge.types.hasOwnProperty(e)&&(ge.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);ge.HDLR_TYPES={video:t,audio:i};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);ge.STTS=ge.STSC=ge.STCO=r,ge.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ge.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ge.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ge.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);ge.FTYP=ge.box(ge.types.ftyp,o,c,o,u),ge.DINF=ge.box(ge.types.dinf,ge.box(ge.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),n=0,i=8;n>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return ge.box(ge.types.mdia,ge.mdhd(e.timescale||0,e.duration||0),ge.hdlr(e.type),ge.minf(e))}static mfhd(e){return ge.box(ge.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?ge.box(ge.types.minf,ge.box(ge.types.smhd,ge.SMHD),ge.DINF,ge.stbl(e)):ge.box(ge.types.minf,ge.box(ge.types.vmhd,ge.VMHD),ge.DINF,ge.stbl(e))}static moof(e,t,i){return ge.box(ge.types.moof,ge.mfhd(e),ge.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=ge.trak(e[t]);return ge.box.apply(null,[ge.types.moov,ge.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(ge.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=ge.trex(e[t]);return ge.box.apply(null,[ge.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(ao+1)),n=Math.floor(t%(ao+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return ge.box(ge.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(r));const u=ge.box(ge.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),c=e.width,d=e.height,f=e.pixelRatio[0],g=e.pixelRatio[1];return ge.box(ge.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,ge.box(ge.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ge.box(ge.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,g>>24,g>>16&255,g>>8&255,g&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return ge.box(ge.types.mp4a,ge.audioStsd(e),ge.box(ge.types.esds,ge.esds(e)))}static mp3(e){return ge.box(ge.types[".mp3"],ge.audioStsd(e))}static ac3(e){return ge.box(ge.types["ac-3"],ge.audioStsd(e),ge.box(ge.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return ge.box(ge.types.stsd,ge.STSD,ge.mp4a(e));if(t==="ac3"&&e.config)return ge.box(ge.types.stsd,ge.STSD,ge.ac3(e));if(t==="mp3"&&e.codec==="mp3")return ge.box(ge.types.stsd,ge.STSD,ge.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return ge.box(ge.types.stsd,ge.STSD,ge.avc1(e));if(t==="hevc"&&e.vps)return ge.box(ge.types.stsd,ge.STSD,ge.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),n=e.width||0,r=e.height||0,o=Math.floor(i/(ao+1)),u=Math.floor(i%(ao+1));return ge.box(ge.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,u>>24,u>>16&255,u>>8&255,u&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=ge.sdtp(e),n=e.id,r=Math.floor(t/(ao+1)),o=Math.floor(t%(ao+1));return ge.box(ge.types.traf,ge.box(ge.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),ge.box(ge.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255])),ge.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,ge.box(ge.types.trak,ge.tkhd(e),ge.mdia(e))}static trex(e){const t=e.id;return ge.box(ge.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,o=new Uint8Array(r);let u,c,d,f,g,m;for(t+=8+r,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),u=0;u>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,g.isLeading<<2|g.dependsOn,g.isDependedOn<<6|g.hasRedundancy<<4|g.paddingValue<<1|g.isNonSync,g.degradPrio&61440,g.degradPrio&15,m>>>24&255,m>>>16&255,m>>>8&255,m&255],12+16*u);return ge.box(ge.types.trun,o)}static initSegment(e){ge.types||ge.init();const t=ge.moov(e);return Pn(ge.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],n=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let o=r.length;for(let _=0;_>8,i[_][b].length&255]),o),o+=2,u.set(i[_][b],o),o+=i[_][b].length}const d=ge.box(ge.types.hvcC,u),f=e.width,g=e.height,m=e.pixelRatio[0],v=e.pixelRatio[1];return ge.box(ge.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&255,g>>8&255,g&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,ge.box(ge.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ge.box(ge.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,v>>24,v>>16&255,v>>8&255,v&255])))}}ge.types=void 0;ge.HDLR_TYPES=void 0;ge.STTS=void 0;ge.STSC=void 0;ge.STCO=void 0;ge.STSZ=void 0;ge.VMHD=void 0;ge.SMHD=void 0;ge.STSD=void 0;ge.FTYP=void 0;ge.DINF=void 0;const eL=9e4;function a_(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function bU(s,e,t=1,i=!1){return a_(s,e,1/t,i)}function Td(s,e=!1){return a_(s,1e3,1/eL,e)}function SU(s,e=1){return a_(s,eL,1/e)}function t2(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const xU=10*1e3,EU=1024,AU=1152,CU=1536;let Au=null,My=null;function i2(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 pp extends Bn{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,Au===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Au=o?parseInt(o[1]):0}if(My===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);My=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&&t2(t)} > ${e&&t2(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,n=e.reduce((r,o)=>{let u=o.pts,c=u-r;return c<-4294967296&&(t=!0,u=pn(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,o,u,c){let d,f,g,m,v,_,b=r,E=r;const w=e.pid>-1,L=t.pid>-1,I=t.samples.length,F=e.samples.length>0,B=u&&I>0||I>1;if((!w||F)&&(!L||B)||this.ISGenerated||u){if(this.ISGenerated){var N,q,R,P;const Q=this.videoTrackConfig;(Q&&(t.width!==Q.width||t.height!==Q.height||((N=t.pixelRatio)==null?void 0:N[0])!==((q=Q.pixelRatio)==null?void 0:q[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((P=Q.pixelRatio)==null?void 0:P[1]))||!Q&&B||this.nextAudioTs===null&&F)&&this.resetInitSegment()}this.ISGenerated||(g=this.generateIS(e,t,r,o));const z=this.isVideoContiguous;let ee=-1,ie;if(B&&(ee=DU(t.samples),!z&&this.config.forceKeyFrameOnDiscontinuity))if(_=!0,ee>0){this.warn(`Dropped ${ee} out of ${I} video samples due to a missing keyframe`);const Q=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(ee),t.dropped+=ee,E+=(t.samples[0].pts-Q)/t.inputTimeScale,ie=E}else ee===-1&&(this.warn(`No keyframe found out of ${I} video samples`),_=!1);if(this.ISGenerated){if(F&&B){const Q=this.getVideoStartPts(t.samples),H=(pn(e.samples[0].pts,Q)-Q)/t.inputTimeScale;b+=Math.max(0,H),E+=Math.max(0,-H)}if(F){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),g=this.generateIS(e,t,r,o)),f=this.remuxAudio(e,b,this.isAudioContiguous,o,L||B||c===qe.AUDIO?E:void 0),B){const Q=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),g=this.generateIS(e,t,r,o)),d=this.remuxVideo(t,E,z,Q)}}else B&&(d=this.remuxVideo(t,E,z,0));d&&(d.firstKeyFrame=ee,d.independent=ee!==-1,d.firstKeyFramePTS=ie)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=tL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(m=iL(n,r,this._initPTS))),{audio:f,video:d,initSegment:g,independent:_,text:m,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let o=pn(e,r);if(o0?$-1:$].dts&&(L=!0)}L&&o.sort(function($,se){const he=$.dts-se.dts,Se=$.pts-se.pts;return he||Se}),_=o[0].dts,b=o[o.length-1].dts;const F=b-_,B=F?Math.round(F/(c-1)):v||e.inputTimeScale/30;if(i){const $=_-I,se=$>B,he=$<-1;if((se||he)&&(se?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Td($,!0)} ms (${$}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Td(-$,!0)} ms (${$}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!he||I>=o[0].pts||Au)){_=I;const Se=o[0].pts-$;if(se)o[0].dts=_,o[0].pts=Se;else{let be=!0;for(let Pe=0;PeSe&&be);Pe++){const Ae=o[Pe].pts;if(o[Pe].dts-=$,o[Pe].pts-=$,Pe0?se.dts-o[$-1].dts:B;if(be=$>0?se.pts-o[$-1].pts:B,Ae.stretchShortVideoTrack&&this.nextAudioTs!==null){const $e=Math.floor(Ae.maxBufferHole*r),Je=(n?E+n*r:this.nextAudioTs+f)-se.pts;Je>$e?(v=Je-Be,v<0?v=Be:ee=!0,this.log(`It is approximately ${Je/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=Be}else v=Be}const Pe=Math.round(se.pts-se.dts);ie=Math.min(ie,v),oe=Math.max(oe,v),Q=Math.min(Q,be),H=Math.max(H,be),u.push(i2(se.key,v,Se,Pe))}if(u.length){if(Au){if(Au<70){const $=u[0].flags;$.dependsOn=2,$.isNonSync=0}}else if(My&&H-Q0&&(n&&Math.abs(I-(w+L))<9e3||Math.abs(pn(b[0].pts,I)-(w+L))<20*f),b.forEach(function(H){H.pts=pn(H.pts,I)}),!i||w<0){const H=b.length;if(b=b.filter(X=>X.pts>=0),H!==b.length&&this.warn(`Removed ${b.length-H} of ${H} samples (initPTS ${L} / ${o})`),!b.length)return;r===0?w=0:n&&!_?w=Math.max(0,I-L):w=b[0].pts-L}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let X=0,te=w+L;X=H*f&&se0){N+=E;try{V=new Uint8Array(N)}catch(se){this.observer.emit(M.ERROR,M.ERROR,{type:Ye.MUX_ERROR,details:me.REMUX_ALLOC_ERROR,fatal:!1,error:se,bytes:N,reason:`fail allocating audio mdat ${N}`});return}m||(new DataView(V.buffer).setUint32(0,N),V.set(ge.types.mdat,4))}else return;V.set(ae,E);const $=ae.byteLength;E+=$,v.push(i2(!0,d,$,0)),B=ce}const R=v.length;if(!R)return;const P=v[v.length-1];w=B-L,this.nextAudioTs=w+c*P.duration;const z=m?new Uint8Array(0):ge.moof(e.sequenceNumber++,F/c,Zt({},e,{samples:v}));e.samples=[];const ee=(F-L)/o,ie=this.nextAudioTs/o,oe={data1:z,data2:V,startPTS:ee,endPTS:ie,startDTS:ee,endDTS:ie,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,oe}}function pn(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function DU(s){for(let e=0;eo.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class wU extends Bn{constructor(e,t,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:o}=this.initData=lw(e);if(t)gF(e,t);else{const c=r||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=s2(r,ni.AUDIO,this)),o&&(n=s2(o,ni.VIDEO,this));const u={};r&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,o){var u,c;let{initPTS:d,lastEndTime:f}=this;const g={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};He(f)||(f=this.lastEndTime=r||0);const m=t.samples;if(!m.length)return g;const v={initPTS:void 0,timescale:void 0,trackId:void 0};let _=this.initData;if((u=_)!=null&&u.length||(this.generateInitSegment(m),_=this.initData),!((c=_)!=null&&c.length))return this.warn("Failed to generate initSegment."),g;this.emitInitSegment&&(v.tracks=this.initTracks,this.emitInitSegment=!1);const b=yF(m,_,this),E=_.audio?b[_.audio.id]:null,w=_.video?b[_.video.id]:null,L=Wf(w,1/0),I=Wf(E,1/0),F=Wf(w,0,!0),B=Wf(E,0,!0);let V=r,N=0;const q=E&&(!w||!d&&I0?this.lastEndTime=z:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const ee=!!_.audio,ie=!!_.video;let Q="";ee&&(Q+="audio"),ie&&(Q+="video");const oe=(_.audio?_.audio.encrypted:!1)||(_.video?_.video.encrypted:!1),H={data1:m,startPTS:P,startDTS:P,endPTS:z,endDTS:z,type:Q,hasAudio:ee,hasVideo:ie,nb:1,dropped:0,encrypted:oe};g.audio=ee&&!ie?H:void 0,g.video=ie?H:void 0;const X=w?.sampleCount;if(X){const te=w.keyFrameIndex,ae=te!==-1;H.nb=X,H.dropped=te===0||this.isVideoContiguous?0:ae?te:X,H.independent=ae,H.firstKeyFrame=te,ae&&w.keyFrameStart&&(H.firstKeyFramePTS=(w.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(g.independent=ae),this.isVideoContiguous||(this.isVideoContiguous=ae),H.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${te}/${X} dropped: ${H.dropped} start: ${H.firstKeyFramePTS||"NA"}`)}return g.initSegment=v,g.id3=tL(i,r,d,d),n.samples.length&&(g.text=iL(n,r,d)),g}}function Wf(s,e,t=!1){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function LU(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 s2(s,e,t){const i=s.codec;return i&&i.length>4?i:e===ni.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Vp(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 ca;try{ca=self.performance.now.bind(self.performance)}catch{ca=Date.now}const gp=[{demux:pU,remux:wU},{demux:po,remux:pp},{demux:cU,remux:pp},{demux:hU,remux:pp}];gp.splice(2,0,{demux:dU,remux:pp});class n2{constructor(e,t,i,n,r,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=ca();let o=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:g,accurateTimeOffset:m,timeOffset:v,initSegmentChange:_}=n||u,{audioCodec:b,videoCodec:E,defaultInitPts:w,duration:L,initSegmentData:I}=c,F=IU(o,t);if(F&&Gu(F.method)){const q=this.getDecrypter(),R=QT(F.method);if(q.isSync()){let P=q.softwareDecrypt(o,F.key.buffer,F.iv.buffer,R);if(i.part>-1){const ee=q.flush();P=ee&&ee.buffer}if(!P)return r.executeEnd=ca(),Ny(i);o=new Uint8Array(P)}else return this.asyncResult=!0,this.decryptionPromise=q.webCryptoDecrypt(o,F.key.buffer,F.iv.buffer,R).then(P=>{const z=this.push(P,null,i);return this.decryptionPromise=null,z}),this.decryptionPromise}const B=this.needsProbing(f,g);if(B){const q=this.configureTransmuxer(o);if(q)return this.logger.warn(`[transmuxer] ${q.message}`),this.observer.emit(M.ERROR,M.ERROR,{type:Ye.MEDIA_ERROR,details:me.FRAG_PARSING_ERROR,fatal:!1,error:q,reason:q.message}),r.executeEnd=ca(),Ny(i)}(f||g||_||B)&&this.resetInitSegment(I,b,E,L,t),(f||_||B)&&this.resetInitialTimestamp(w),d||this.resetContiguity();const V=this.transmux(o,F,v,m,i);this.asyncResult=Wd(V);const N=this.currentTransmuxState;return N.contiguous=!0,N.discontinuity=!1,N.trackSwitch=!1,r.executeEnd=ca(),V}flush(e){const t=e.transmuxing;t.executeStart=ca();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const o=[],{timeOffset:u}=n;if(i){const g=i.flush();g&&o.push(this.push(g.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=ca();const g=[Ny(e)];return this.asyncResult?Promise.resolve(g):g}const f=c.flush(u);return Wd(f)?(this.asyncResult=!0,f.then(g=>(this.flushRemux(o,g,e),o))):(this.flushRemux(o,f,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:o,textTrack:u}=t,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===qe.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,o,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=ca()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:o,remuxer:u}=this;!o||!u||(o.resetInitSegment(e,t,i,n),u.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,n,r):o=this.transmuxUnencrypted(e,i,n,r),o}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:o,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,o,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let g=0,m=gp.length;g0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ny=s=>({remuxResult:{},chunkMeta:s});function Wd(s){return"then"in s&&s.then instanceof Function}class RU{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class kU{constructor(e,t,i,n,r,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=o}}let r2=0;class sL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=r2++,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 g;const m=(g=this.workerContext)==null?void 0:g.objectURL;m&&self.URL.revokeObjectURL(m);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(M.ERROR,{type:Ye.OTHER_ERROR,details:me.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const o=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===M.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new e_,this.observer.on(M.FRAG_DECRYPTED,o),this.observer.on(M.ERROR,o);const u=_1(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||N5()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=F5(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=B5());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:ai(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new n2(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new n2(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=r2++;const t=this.hls.config,i=_1(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ai(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),U5(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,n,r,o,u,c,d,f){var g,m;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:_}=this,b=o?o.start:r.start,E=r.decryptdata,w=this.frag,L=!(w&&r.cc===w.cc),I=!(w&&d.level===w.level),F=w?d.sn-w.sn:-1,B=this.part?d.part-this.part.index:-1,V=F===0&&d.id>1&&d.id===w?.stats.chunkCount,N=!I&&(F===1||F===0&&(B===1||V&&B<=0)),q=self.performance.now();(I||F||r.stats.parsing.start===0)&&(r.stats.parsing.start=q),o&&(B||!N)&&(o.stats.parsing.start=q);const R=!(w&&((g=r.initSegment)==null?void 0:g.url)===((m=w.initSegment)==null?void 0:m.url)),P=new kU(L,N,c,I,b,R);if(!N||L||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===qe.MAIN?"level":"track"}: ${d.level} id: ${d.id} + discontinuity: ${L} + trackSwitch: ${I} + contiguous: ${N} + accurateTimeOffset: ${c} + timeOffset: ${b} + initSegmentChange: ${R}`);const z=new RU(i,n,t,u,f);this.configureTransmuxer(z)}if(this.frag=r,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:P},e instanceof ArrayBuffer?[e]:[]);else if(_){const z=_.push(e,E,d,P);Wd(z)?z.then(ee=>{this.handleTransmuxComplete(ee)}).catch(ee=>{this.transmuxerError(ee,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(z)}}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);Wd(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(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.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 a2=100;class OU extends JT{constructor(e,t,i){super(e,t,i,"audio-stream-controller",qe.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(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(M.BUFFER_RESET,this.onBufferReset,this),e.on(M.BUFFER_CREATED,this.onBufferCreated,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(M.FRAG_LOADING,this.onFragLoading,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(M.BUFFER_RESET,this.onBufferReset,this),e.off(M.BUFFER_CREATED,this.onBufferCreated,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(M.FRAG_LOADING,this.onFragLoading,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){if(i===qe.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:o},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${o}`),this.mainAnchor=t,this.state===Ie.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===Ie.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const n=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&n?.cc===t.cc)return;const r=(n||e).cc,o=this.getLevelDetails(),u=this.getLoadPosition(),c=Tw(o,r,u);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===Ie.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Ie.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(a2),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Ie.IDLE):this.state=Ie.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Ie.IDLE:this.doTickIdle();break;case Ie.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=Ie.WAITING_INIT_PTS}break}case Ie.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Ie.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Ie.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=Ie.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:n,trackId:r}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=Ie.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,ni.AUDIO,qe.AUDIO));const f=this.getFwdBufferInfo(d,qe.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(M.BUFFER_EOS,{type:"audio"}),this.state=Ie.ENDED;return}const g=f.len,m=t.maxBufferLength,v=c.fragments,_=v[0].start,b=this.getLoadPosition(),E=this.flushing?b:f.end;if(this.switchingTrack&&n){const I=b;c.PTSKnown&&I<_&&(f.end>_||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=_+.05)}if(g>=m&&!this.switchingTrack&&EL.end){const F=this.fragmentTracker.getFragAtPos(E,qe.MAIN);F&&F.end>L.end&&(L=F,this.mainFragLoading={frag:F,targetBufferTime:null})}if(w.start>L.end)return}this.loadFragment(w,u,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new zd(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Ie.STOPPED&&(this.setInterval(a2),this.state=Ie.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(M.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:o,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==Ie.STOPPED&&(this.state=Ie.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[o];let g=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var m;g=this.alignPlaylists(r,f.details,(m=this.levelLastLoaded)==null?void 0:m.details)}r.alignedSliding||(Bw(r,d),r.alignedSliding||Qp(r,d),g=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,g),this.hls.trigger(M.AUDIO_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.state===Ie.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=Ie.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:o,trackId:u,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const d=c[u];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const f=d.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const g=o.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let m=this.transmuxer;m||(m=this.transmuxer=new sL(this.hls,qe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const v=this.initPTS[i.cc],_=(t=i.initSegment)==null?void 0:t.data;if(v!==void 0){const E=n?n.index:-1,w=E!==-1,L=new XT(i.level,i.sn,i.stats.chunkCount,r.byteLength,E,w);m.push(r,_,g,"",i,n,f.totalduration,!1,L,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:b}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Fw,complete:!1};b.push(new Uint8Array(r)),this.state!==Ie.STOPPED&&(this.state=Ie.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===qe.MAIN&&Pi(t.frag)&&(this.mainFragLoading=t,this.state===Ie.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==qe.AUDIO){!this.audioOnly&&i.type===qe.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(Pi(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(M.AUDIO_TRACK_SWITCHED,qt({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=Ie.ERROR;return}switch(t.details){case me.FRAG_GAP:case me.FRAG_PARSING_ERROR:case me.FRAG_DECRYPT_ERROR:case me.FRAG_LOAD_ERROR:case me.FRAG_LOAD_TIMEOUT:case me.KEY_LOAD_ERROR:case me.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(qe.AUDIO,t);break;case me.AUDIO_TRACK_LOAD_ERROR:case me.AUDIO_TRACK_LOAD_TIMEOUT:case me.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ie.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===bt.AUDIO_TRACK&&(this.state=Ie.IDLE);break;case me.BUFFER_ADD_CODEC_ERROR:case me.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case me.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case me.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ni.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ni.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Ie.ENDED&&(this.state=Ie.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,qe.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:o}=e,u=this.getCurrentContext(o);if(!u){this.resetWhenMissingContext(o);return}const{frag:c,part:d,level:f}=u,{details:g}=f,{audio:m,text:v,id3:_,initSegment:b}=r;if(this.fragContextChanged(c)||!g){this.fragmentTracker.removeFragment(c);return}if(this.state=Ie.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),b!=null&&b.tracks){const E=c.initSegment||c;if(this.unhandledEncryptionError(b,c))return;this._bufferInitSegment(f,b.tracks,E,o),n.trigger(M.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:b.tracks})}if(m){const{startPTS:E,endPTS:w,startDTS:L,endDTS:I}=m;d&&(d.elementaryStreams[ni.AUDIO]={startPTS:E,endPTS:w,startDTS:L,endDTS:I}),c.setElementaryStreamInfo(ni.AUDIO,E,w,L,I),this.bufferFragmentData(m,c,d,o)}if(_!=null&&(t=_.samples)!=null&&t.length){const E=Zt({id:i,frag:c,details:g},_);n.trigger(M.FRAG_PARSING_METADATA,E)}if(v){const E=Zt({id:i,frag:c,details:g},v);n.trigger(M.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,i,n){if(this.state!==Ie.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=qe.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${o}/${r.codec}]`),o&&o.split(",").length===1&&(r.levelCodec=o),this.hls.trigger(M.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(M.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===Ki.NOT_LOADED||n===Ki.PARTIAL){var r;if(!Pi(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=Ie.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&Qp(t.details,o)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u}=this.bufferedTrack;_l({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:o,channels:u},e,ul)||(zp(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(M.AUDIO_TRACK_SWITCHED,qt({},e))}}class o_ extends Bn{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const n=t?.renditionReports;if(n){let r=-1;for(let o=0;o=0&&f>t.partTarget&&(c+=1)}const d=i&&b1(i);return new S1(u,c>=0?c:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:n,stats:r}=t,o=self.performance.now(),u=r.loading.first?Math.max(0,o-r.loading.first):0;n.advancedDateTime=Date.now()-u;const c=this.hls.config.timelineOffset;if(c!==n.appliedTimelineOffset){const f=Math.max(c||0,0);n.appliedTimelineOffset=f,n.fragments.forEach(g=>{g.setStart(g.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){A5(i,n,this);const L=n.playlistParsingError;if(L){this.warn(L);const I=this.hls;if(!I.config.ignorePlaylistParsingErrors){var d;const{networkDetails:F}=t;I.trigger(M.ERROR,{type:Ye.NETWORK_ERROR,details:me.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:L,reason:L.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:F,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,v=(n.edge-m)*1e3,_=kw(n,v);if(n.requestScheduled+_0){if(R>n.targetduration*3)this.log(`Playlist last advanced ${q.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,w=void 0;else if(i!=null&&i.tuneInGoal&&R-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${P} with playlist age: ${n.age}`),P=0;else{const z=Math.floor(P/n.targetduration);if(E+=z,w!==void 0){const ee=Math.round(P%n.targetduration/n.partTarget);w+=ee}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${q.toFixed(2)}s goal: ${P} skip sn ${z} to part ${w}`)}n.tuneInGoal=P}if(b=this.getDeliveryDirectives(n,t.deliveryDirectives,E,w),L||!N){n.requestScheduled=o,this.loadingPlaylist(f,b);return}}else(n.canBlockReload||n.canSkipUntil)&&(b=this.getDeliveryDirectives(n,t.deliveryDirectives,E,w));b&&E!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(_-u*2,_/2)),this.scheduleLoading(f,b,n)}else this.clearTimer()}scheduleLoading(e,t,i){const n=i||e.details;if(!n){this.loadingPlaylist(e,t);return}const r=self.performance.now(),o=n.requestScheduled;if(r>=o){this.loadingPlaylist(e,t);return}const u=o-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(u)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),u)}getDeliveryDirectives(e,t,i,n){let r=b1(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=hp.No),new S1(i,n,r)}checkRetry(e){const t=e.details,i=Kp(e),n=e.errorAction,{action:r,retryCount:o=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===us.RetryRequest||!n.resolved&&r===us.SendAlternateToPenaltyBox);if(c){var d;if(o>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=YT(u,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${o+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function nL(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function Vv(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class PU extends o_{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(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(M.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(u=>n?.indexOf(u)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const u=this.tracks.filter(m=>!i||i.indexOf(m.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(m=>m.default)&&(this.selectDefaultTrack=!1),u.forEach((m,v)=>{m.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const m=Lr(c,u,ul);if(m>-1)r=u[m];else{const v=Lr(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(M.AUDIO_TRACKS_UPDATED,f);const g=this.trackId;if(d!==-1&&g===-1)this.setAudioTrack(d);else if(u.length&&g===-1){var o;const m=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${u.length}`);this.warn(m.message),this.hls.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(e,t){t.fatal||!t.context||t.context.type===bt.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&&_l(e,n,ul))return n;const r=Lr(e,this.tracksInGroup,ul);if(r>-1){const o=this.tracksInGroup[r];return this.setAudioTrack(r),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const u=zF(e,t.levels,i,o,ul);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const o=Lr(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,n=t[e],r=n.details&&!n.details.live;if(e===this.trackId&&n===i&&r||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(M.AUDIO_TRACK_SWITCHING,qt({},n)),r))return;const o=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(r){var i;if(n.onError(r),this.queues===null||this.tracks===null)return;const o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"":` +${this.list("video")} +${this.list("audio")} +${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],n=i?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const o2=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rL="HlsJsTrackRemovedError";class NU extends Error{constructor(e){super(e),this.name=rL}}class BU extends Bn{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(M.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=rF(So(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(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.BUFFER_RESET,this.onBufferReset,this),e.on(M.BUFFER_APPENDING,this.onBufferAppending,this),e.on(M.BUFFER_CODECS,this.onBufferCodecs,this),e.on(M.BUFFER_EOS,this.onBufferEos,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.FRAG_PARSED,this.onFragParsed,this),e.on(M.FRAG_CHANGED,this.onFragChanged,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.BUFFER_RESET,this.onBufferReset,this),e.off(M.BUFFER_APPENDING,this.onBufferAppending,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.BUFFER_EOS,this.onBufferEos,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.FRAG_PARSED,this.onFragParsed,this),e.off(M.FRAG_CHANGED,this.onFragChanged,this),e.off(M.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const o=this.isQueued();(r||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?Zt(i,n.tracks):this.sourceBuffers.forEach(r=>{const[o]=r;o&&(i[o]=Zt({},this.tracks[o]),this.removeBuffer(o)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const n=So(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&o instanceof c,l2(i),FU(i,u),i.load()}catch{i.src=u}else i.src=u}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,n=t.tracks,r=n?Object.keys(n):null,o=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) +required tracks: ${ai(i,(c,d)=>c==="initSegment"?void 0:d)}; +transfer tracks: ${ai(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!tw(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(M.MEDIA_DETACHING,{}),this.onMediaAttaching(M.MEDIA_ATTACHING,t),e.currentTime=f;return}this.transferData=void 0,r.forEach(c=>{const d=c,f=n[d];if(f){const g=f.buffer;if(g){const m=this.fragmentTracker,v=f.id;if(m.hasFragments(v)||m.hasParts(v)){const E=ut.getBuffered(g);m.detectEvictedFragments(d,E,v,null,!0)}const _=By(d),b=[d,g];this.sourceBuffers[_]=b,g.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,f)}}}),u(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),u()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:o}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([u])=>{u&&this.removeBuffer(u)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const u=r.readyState==="open";try{const c=r.sourceBuffers;for(let d=c.length;d--;)u&&c[d].abort(),r.removeSourceBuffer(c[d]);u&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&l2(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(M.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[By(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new MU(this.tracks)}onBufferCodecs(e,t){var i;const n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!o&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(o||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const g=t[c],{id:m,codec:v,levelCodec:_,container:b,metadata:E,supplemental:w}=g;let L=n[c];const I=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],F=I!=null&&I.buffer?I:L,B=F?.pendingCodec||F?.codec,V=F?.levelCodec;L||(L=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:w,container:b,levelCodec:_,metadata:E,id:m});const N=dp(B,V),q=N?.replace(o2,"$1");let R=dp(v,_);const P=(f=R)==null?void 0:f.replace(o2,"$1");R&&N&&q!==P&&(c.slice(0,5)==="audio"&&(R=Vp(R,this.appendSource)),this.log(`switching codec ${B} to ${R}`),R!==(L.pendingCodec||L.codec)&&(L.pendingCodec=R),L.container=b,this.appendChangeType(c,b,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const n=`${t};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const u=o.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),o.codec=i,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,n=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,qe.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&ut.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,qe.MAIN))==null?void 0:u.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:u=>{this.warn("Error executing block-audio operation",u)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:n,type:r,parent:o,frag:u,part:c,chunkMeta:d,offset:f}=t,g=d.buffering[r],{sn:m,cc:v}=u,_=self.performance.now();g.start=_;const b=u.stats.buffering,E=c?c.stats.buffering:null;b.start===0&&(b.start=_),E&&E.start===0&&(E.start=_);const w=i.audio;let L=!1;r==="audio"&&w?.container==="audio/mpeg"&&(L=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const I=i.video,F=I?.buffer;if(F&&m!=="initSegment"){const N=c||u,q=this.blockedAudioAppend;if(r==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(I.ending||I.ended)){const P=N.start+N.duration*.05,z=F.buffered,ee=this.currentOp("video");!z.length&&!ee?this.blockAudio(N):!ee&&!ut.isBuffered(F,P)&&this.lastVideoAppendEndP||R{var N;g.executeStart=self.performance.now();const q=(N=this.tracks[r])==null?void 0:N.buffer;q&&(L?this.updateTimestampOffset(q,B,.1,r,m,v):f!==void 0&&He(f)&&this.updateTimestampOffset(q,f,1e-6,r,m,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const N=self.performance.now();g.executeEnd=g.end=N,b.first===0&&(b.first=N),E&&E.first===0&&(E.first=N);const q={};this.sourceBuffers.forEach(([R,P])=>{R&&(q[R]=ut.getBuffered(P))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(M.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:q})},onError:N=>{var q;const R={type:Ye.MEDIA_ERROR,parent:u.type,details:me.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:N,err:N,fatal:!1},P=(q=this.media)==null?void 0:q.error;if(N.code===DOMException.QUOTA_EXCEEDED_ERR||N.name=="QuotaExceededError"||"quota"in N)R.details=me.BUFFER_FULL_ERROR;else if(N.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!P)R.errorAction=Hu(!0);else if(N.name===rL&&this.sourceBufferCount===0)R.errorAction=Hu(!0);else{const z=++this.appendErrors[r];this.warn(`Failed ${z}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${P||"no media error"})`),(z>=this.hls.config.appendErrorMaxRetry||P)&&(R.fatal=!0)}this.hls.trigger(M.ERROR,R)}};this.log(`queuing "${r}" append sn: ${m}${c?" p: "+c.index:""} of ${u.type===qe.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append(V,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(M.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:i,startOffset:n,endOffset:r}=t;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,r),o)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],o=n?n.elementaryStreams:i.elementaryStreams;o[ni.AUDIOVIDEO]?r.push("audiovideo"):(o[ni.AUDIO]&&r.push("audio"),o[ni.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(M.FRAG_BUFFERED,{frag:i,part:n,stats:d,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(u,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){const u=this.tracks[o];(!t.type||t.type===o)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var u;return o&&!((u=this.tracks[o])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(M.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(M.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===me.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;He(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const n=e.config,r=i.currentTime,o=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(He(u)&&u>=0){const d=Math.max(u,o),f=Math.floor(r/o)*o-d;this.flushBackBuffer(r,o,f)}const c=n.frontBufferFlushThreshold;if(He(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,o),g=Math.floor(r/o)*o+f;this.flushFrontBuffer(r,o,g)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=ut.getBuffered(r);if(u.length>0&&i>u.start(0)){var o;this.hls.trigger(M.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(M.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(M.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const o=ut.getBuffered(r),u=o.length;if(u<2)return;const c=o.start(u-1),d=o.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(M.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 He(r)?{duration:r}:null;const o=this.media.duration,u=He(i.duration)?i.duration:0;return n>u&&n>o||!He(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(He(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}) ${ai(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(M.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(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const o=r,u=e[o];if(this.isPending(u)){const c=this.getTrackCodec(u,o),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(o)?" Queued":""} ${ai(u)}`);try{const f=i.addSourceBuffer(d),g=By(o),m=[o,f];t[g]=m,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:o,mimeType:d,parent:u.id});return}this.trackSourceBuffer(o,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Vd(i,"video")&&(n=DF(n,i));const r=dp(n,e.levelCodec);return r?t.slice(0,5)==="audio"?Vp(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,o)=>{const u=o.removedRanges;u!=null&&u.length&&this.hls.trigger(M.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(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,o){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,o=this.tracks[e],u=o?.buffer;if(!n||!r||!u){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=He(n.duration)?n.duration:1/0,d=He(r.duration)?r.duration:1/0,f=Math.max(0,t),g=Math.min(i,c,d);g>f&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${f},${g}] from the ${e} SourceBuffer`),u.remove(f,g)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],n=i?.buffer;if(!n)throw new NU(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const n=(i=this.tracks[t])==null?void 0:i.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const n=this.tracks[e];if(!n)return;const r=n.buffer;if(!r)return;const o=i.bind(this,e);n.listeners.push({event:t,listener:o}),r.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(n=>{i.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function l2(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function FU(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function By(s){return s==="audio"?1:0}class l_{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(M.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.BUFFER_CODECS,this.onBufferCodecs,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(M.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.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&&He(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,l_.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(u,c)=>c?u.width!==c.width||u.height!==c.height:!0;let r=e.length-1;const o=Math.max(t,i);for(let u=0;u=o||c.height>=o)&&n(c,e[u+1])){r=u;break}}return r}}const UU={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},zs=UU,$U={HLS:"h"},jU=$U;class Mr{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Mr?i:new Mr(i))),this.value=e,this.params=t}}const HU="Dict";function GU(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function VU(s,e,t,i){return new Error(`failed to ${s} "${GU(e)}" as ${t}`,{cause:i})}function Nr(s,e,t){return VU("serialize",s,e,t)}class aL{constructor(e){this.description=e}}const u2="Bare Item",qU="Boolean";function zU(s){if(typeof s!="boolean")throw Nr(s,qU);return s?"?1":"?0"}function KU(s){return btoa(String.fromCharCode(...s))}const YU="Byte Sequence";function WU(s){if(ArrayBuffer.isView(s)===!1)throw Nr(s,YU);return`:${KU(s)}:`}const XU="Integer";function QU(s){return s<-999999999999999||99999999999999912)throw Nr(s,JU);const t=e.toString();return t.includes(".")?t:`${t}.0`}const t8="String",i8=/[\x00-\x1f\x7f]+/;function s8(s){if(i8.test(s))throw Nr(s,t8);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function n8(s){return s.description||s.toString().slice(7,-1)}const r8="Token";function c2(s){const e=n8(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Nr(e,r8);return e}function qv(s){switch(typeof s){case"number":if(!He(s))throw Nr(s,u2);return Number.isInteger(s)?oL(s):e8(s);case"string":return s8(s);case"symbol":return c2(s);case"boolean":return zU(s);case"object":if(s instanceof Date)return ZU(s);if(s instanceof Uint8Array)return WU(s);if(s instanceof aL)return c2(s);default:throw Nr(s,u2)}}const a8="Key";function zv(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Nr(s,a8);return s}function u_(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${zv(e)}`:`;${zv(e)}=${qv(t)}`).join("")}function uL(s){return s instanceof Mr?`${qv(s.value)}${u_(s.params)}`:qv(s)}function o8(s){return`(${s.value.map(uL).join(" ")})${u_(s.params)}`}function l8(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Nr(s,HU);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Mr||(r=new Mr(r));let o=zv(n);return r.value===!0?o+=u_(r.params):(o+="=",Array.isArray(r.value)?o+=o8(r):o+=uL(r)),o}).join(`,${i}`)}function cL(s,e){return l8(s,e)}const Tr="CMCD-Object",Di="CMCD-Request",rl="CMCD-Session",oo="CMCD-Status",u8={br:Tr,ab:Tr,d:Tr,ot:Tr,tb:Tr,tpb:Tr,lb:Tr,tab:Tr,lab:Tr,url:Tr,pb:Di,bl:Di,tbl:Di,dl:Di,ltc:Di,mtp:Di,nor:Di,nrr:Di,rc:Di,sn:Di,sta:Di,su:Di,ttfb:Di,ttfbb:Di,ttlb:Di,cmsdd:Di,cmsds:Di,smrt:Di,df:Di,cs:Di,ts:Di,cid:rl,pr:rl,sf:rl,sid:rl,st:rl,v:rl,msd:rl,bs:oo,bsd:oo,cdn:oo,rtp:oo,bg:oo,pt:oo,ec:oo,e:oo},c8={REQUEST:Di};function d8(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 h8(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?d8(e):{};return i.reduce((r,o)=>{var u;const c=u8[o]||n[o]||c8.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[o]=s[o],r},t)}function f8(s){return["ot","sf","st","e","sta"].includes(s)}function p8(s){return typeof s=="number"?He(s):s!=null&&s!==""&&s!==!1}const dL="event";function g8(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 mp=s=>Math.round(s),Kv=(s,e)=>Array.isArray(s)?s.map(t=>Kv(t,e)):s instanceof Mr&&typeof s.value=="string"?new Mr(Kv(s.value,e),s.params):(e.baseUrl&&(s=g8(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Xf=s=>mp(s/100)*100,m8=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Mr&&typeof s.value=="string"?t=new Mr([s]):typeof s=="string"&&(t=[s])),Kv(t,e)},y8={br:mp,d:mp,bl:Xf,dl:Xf,mtp:Xf,nor:m8,rtp:Xf,tb:mp},hL="request",fL="response",c_=["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"],v8=["e"],T8=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ng(s){return T8.test(s)}function _8(s){return c_.includes(s)||v8.includes(s)||Ng(s)}const pL=["d","dl","nor","ot","rtp","su"];function b8(s){return c_.includes(s)||pL.includes(s)||Ng(s)}const S8=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function x8(s){return c_.includes(s)||pL.includes(s)||S8.includes(s)||Ng(s)}const E8=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function A8(s){return E8.includes(s)||Ng(s)}const C8={[fL]:x8,[dL]:_8,[hL]:b8};function gL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||hL,r=i===1?A8:C8[n];let o=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(o=o.filter(u));const c=n===fL||n===dL;c&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");const d=Zt({},y8,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(g=>{let m=s[g];const v=d[g];if(typeof v=="function"&&(m=v(m,f)),g==="v"){if(i===1)return;m=i}g=="pr"&&m===1||(c&&g==="ts"&&!He(m)&&(m=Date.now()),p8(m)&&(f8(g)&&typeof m=="string"&&(m=new aL(m)),t[g]=m))}),t}function D8(s,e={}){const t={};if(!s)return t;const i=gL(s,e),n=h8(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[o,u])=>{const c=cL(u,{whitespace:!1});return c&&(r[o]=c),r},t)}function w8(s,e,t){return Zt(s,D8(e,t))}const L8="CMCD";function I8(s,e={}){return s?cL(gL(s,e),{whitespace:!1}):""}function R8(s,e={}){if(!s)return"";const t=I8(s,e);return encodeURIComponent(t)}function k8(s,e={}){if(!s)return"";const t=R8(s,e);return`${L8}=${t}`}const d2=/CMCD=[^&#]+/;function O8(s,e,t){const i=k8(e,t);if(!i)return s;if(d2.test(s))return s.replace(d2,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class P8{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:zs.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const{frag:r,part:o}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(o||r).duration*1e3,ot:c};(c===zs.VIDEO||c===zs.AUDIO||c==zs.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=o?this.getNextPart(o):this.getNextFrag(r);f!=null&&f.url&&f.url!==r.url&&(d.nor=f.url),this.apply(n,d)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHED,this.onMediaDetached,this),e.on(M.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHED,this.onMediaDetached,this),e.off(M.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:jU.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Zt(t,this.createData());const i=t.ot===zs.INIT||t.ot===zs.VIDEO||t.ot===zs.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,u)=>(n.includes(u)&&(o[u]=t[u]),o),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),w8(e.headers,t,r)):e.url=O8(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const n=e.sn-i.startSN;return i.fragments[n+1]}}getNextPart(e){var t;const{index:i,fragment:n}=e,r=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:o}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===o)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return zs.TIMED_TEXT;if(e.sn==="initSegment")return zs.INIT;if(t==="audio")return zs.AUDIO;if(t==="main")return this.hls.audioTracks.length?zs.VIDEO:zs.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===zs.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,o=r>-1?r+1:n.levels.length;i=n.levels.slice(0,o)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===zs.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ut.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,u){t(r),this.loader.load(r,o,u)}}}}const M8=3e5;class N8 extends Bn{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(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.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===us.SendAlternateToPenaltyBox&&i.flags===fn.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?o=this.getPathwayForGroupId(u,d,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==o),t.details===me.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${ai(r)} penalized: ${ai(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]>M8&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Mw(t),this.hls.trigger(M.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[u];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=u);break}}}getPathwayForGroupId(e,t,i){const n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r{const{ID:o,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===o))return;const d=this.getLevelsForPathway(u).map(f=>{const g=new Ti(f.attrs);g["PATHWAY-ID"]=o;const m=g.AUDIO&&`${g.AUDIO}_clone_${o}`,v=g.SUBTITLES&&`${g.SUBTITLES}_clone_${o}`;m&&(i[g.AUDIO]=m,g.AUDIO=m),v&&(n[g.SUBTITLES]=v,g.SUBTITLES=v);const _=mL(f.uri,g["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),b=new zd({attrs:g,audioCodec:f.audioCodec,bitrate:f.bitrate,height:f.height,name:f.name,url:_,videoCodec:f.videoCodec,width:f.width});if(f.audioGroups)for(let E=1;E{this.log(`Loaded steering manifest: "${n}"`);const _=f.data;if(_?.VERSION!==1){this.log(`Steering VERSION ${_.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=_.TTL;const{"RELOAD-URI":b,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":w}=_;if(b)try{this.uri=new self.URL(b,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${b}`);return}this.scheduleRefresh(this.uri||m.url),E&&this.clonePathways(E);const L={steeringManifest:_,url:n.toString()};this.hls.trigger(M.STEERING_MANIFEST_LOADED,L),w&&this.updatePathwayPriority(w)},onError:(f,g,m,v)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${g.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${g.url} no longer available`);return}let _=this.timeToLoad*1e3;if(f.code===429){const b=this.loader;if(typeof b?.getResponseHeader=="function"){const E=b.getResponseHeader("Retry-After");E&&(_=parseFloat(E)*1e3)}this.log(`Steering manifest ${g.url} rate limited`);return}this.scheduleRefresh(this.uri||g.url,_)},onTimeout:(f,g,m)=>{this.log(`Timeout loading steering manifest (${g.url})`),this.scheduleRefresh(this.uri||g.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 h2(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(o=>o.groupId===n).map(o=>{const u=Zt({},o);return u.details=void 0,u.attrs=new Ti(u.attrs),u.url=u.attrs.URI=mL(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),u.groupId=u.attrs["GROUP-ID"]=e[n],u.attrs["PATHWAY-ID"]=i,u});s.push(...r)})}function mL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:o}=i;let u;e&&(u=o?.[e],u&&(s=u));const c=new self.URL(s);return n&&!u&&(c.host=n),r&&Object.keys(r).sort().forEach(d=>{d&&c.searchParams.set(d,r[d])}),c.href}class Vu extends Bn{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=Vu.CDMCleanupPromise?[Vu.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:i,initData:n}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Cd(this.config));const u=o.map(Ly).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(o=>{const u=fp(o);if(i!=="sinf"||u!==_i.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const v=zi(new Uint8Array(n)),_=ZT(JSON.parse(v).sinf),b=cw(_);if(!b)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(b.subarray(8,24))}catch(v){this.warn(`${r} Failed to parse sinf: ${v}`);return}const d=ds(c),{keyIdToKeySessionPromise:f,mediaKeySessions:g}=this;let m=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(_,i,n,"encrypted-event-key-match")),m.catch(w=>this.handleError(w));break}}m||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${g.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(M.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(M.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(M.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(M.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(M.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(M.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===_i.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(o,u,c)=>!!o&&c.indexOf(o)===u,n=t.map(o=>o.audioCodec).filter(i),r=t.map(o=>o.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((o,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(g=>o({keySystem:f,mediaKeys:g})).catch(g=>{d.length?c(d):g instanceof hn?u(g):u(new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_NO_ACCESS,error:g,fatal:!0},g.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 Dw===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=m5(e,t,i,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],u=(n=o)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ai(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=o=this.keySystemAccessPromises[e]={keySystemAccess:u};return u.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),u.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const f=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const g=c.mediaKeys=d.createMediaKeys().then(m=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(m,e,v):m)));return g.catch(m=>{this.error(`Failed to create media-keys for "${e}"}: ${m}`)}),g})}return u.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ds(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=Qf(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 ${ds(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})=>Ly(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=Ly(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=Cd(this.config),i=e.map(fp).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:t}))))).then(c=>{const d="cenc",f=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,f,"playlist-key")});return u.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[i]=u,u}return o.catch(u=>{if(u instanceof hn){const c=qt({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new hn(c,u.message);this.handleError(d,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof hn){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${ds(i.keyId||[])})`:""}`),this.hls.trigger(M.ERROR,e.data)}else this.error(e.message),this.hls.trigger(M.ERROR,{type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Qf(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=fp(e.keyFormat),r=n?[n]:Cd(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Cd(this.config)),e.length===0)throw new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ai({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(o)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r;const o=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(o)try{const _=o.call(this.hls,t,i,e);if(!_)throw new Error("Invalid response from configured generateRequest filter");t=_.initDataType,i=_.initData?_.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(_){if(this.warn(_.message),this.hls&&this.hls.config.debug)throw _}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const u=Qf(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 e_,f=e._onmessage=_=>{const b=e.mediaKeysSession;if(!b){d.emit("error",new Error("invalid state"));return}const{messageType:E,message:w}=_;this.log(`"${E}" message event for session "${b.sessionId}" message size: ${w.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,w).catch(L=>{d.eventNames().length?d.emit("error",L):this.handleError(L)}):E==="license-release"?e.keySystem===_i.FAIRPLAY&&this.updateKeySession(e,Uv("acknowledged")).then(()=>this.removeSession(e)).catch(L=>this.handleError(L)):this.warn(`unhandled media key message type "${E}"`)},g=(_,b)=>{b.keyStatus=_;let E;_.startsWith("usable")?d.emit("resolved"):_==="internal-error"||_==="output-restricted"||_==="output-downscaled"?E=f2(_,b.decryptdata):_==="expired"?E=new Error(`key expired (keyId: ${u})`):_==="released"?E=new Error("key released"):_==="status-pending"||this.warn(`unhandled key status change "${_}" (keyId: ${u})`),E&&(d.eventNames().length?d.emit("error",E):this.handleError(E))},m=e._onkeystatuseschange=_=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const E=this.getKeyStatuses(e);if(!Object.keys(E).some(F=>E[F]!=="status-pending"))return;if(E[u]==="expired"){this.log(`Expired key ${ai(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let L=E[u];if(L)g(L,e);else{var I;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(I=e.keyStatusTimeouts)[u]||(I[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.`),g(B,e);this.log(`key status for ${u} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),L="internal-error",g(L,e)},1e3)),this.log(`No status for keyId ${u} (${ai(E)}).`)}};ks(e.mediaKeysSession,"message",f),ks(e.mediaKeysSession,"keystatuseschange",m);const v=new Promise((_,b)=>{d.on("error",b),d.on("resolved",_)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${u} URI: ${c}`)}).catch(_=>{throw new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_NO_SESSION,error:_,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${_}`)}).then(()=>v).catch(_=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw _}))).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===_i.PLAYREADY&&r.length===16){const u=ds(r);t[u]=i,Aw(r)}const o=ds(r);i==="internal-error"&&(this.bannedKeyIds[o]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=i}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,u)=>{const c={responseType:"arraybuffer",url:r},d=t.certLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,v,_,b)=>{o(m.data)},onError:(m,v,_,b)=>{u(new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:_,response:qt({url:c.url,data:void 0},m)},`"${e}" certificate request failed (${r}). Status: ${m.code} (${m.text})`))},onTimeout:(m,v,_)=>{u(new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:_,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(m,v,_)=>{u(new Error("aborted"))}};n.load(c,f,g)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(o=>{r(new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.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 g=0,m=r.length;g in key message");return Uv(atob(d))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(u.readyState===4)if(u.status===200){this._requestLicenseFailureCount=0;let c=u.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,u,o,e)}catch(f){this.error(f)}n(c)}else{const c=i.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||u.status>=400&&u.status<500)r(new hn({type:Ye.KEY_SYSTEM_ERROR,details:me.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:o,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${o}). Status: ${u.status} (${u.statusText})`));else{const f=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${f} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=u,this.setupLicenseXHR(u,o,e,t).then(({xhr:c,licenseChallenge:d})=>{e.keySystem==_i.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,ks(i,"encrypted",this.onMediaEncrypted),ks(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Xs(e,"encrypted",this.onMediaEncrypted),Xs(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,To.clearKeyUriToKeyIdMap();const r=n.length;Vu.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(M.ERROR,{type:Ye.OTHER_ERROR,details:me.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(M.ERROR,{type:Ye.OTHER_ERROR,details:me.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ds(n?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(d=>self.clearTimeout(o[d]));const{drmSystemOptions:u}=this.config;return(v5(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(M.ERROR,{type:Ye.OTHER_ERROR,details:me.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(M.ERROR,{type:Ye.OTHER_ERROR,details:me.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}Vu.CDMCleanupPromise=void 0;function Qf(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return ds(s.keyId)}function B8(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 hn 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 f2(s,e){const t=s==="output-restricted",i=t?me.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:me.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new hn({type:Ye.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class F8{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(M.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(M.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(M.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,o=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*o/r,d=this.hls;if(d.trigger(M.FPS_DROP,{currentDropped:o,currentDecoded:u,totalDroppedFrames:i}),c>0&&o>d.config.fpsDroppedMonitoringThreshold*u){let f=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=f)&&(f=f-1,d.trigger(M.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 yL(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 vL(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){zt.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){zt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Ru(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 Yv(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=$8(s.cues,e,t);for(let o=0;os[t].endTime)return-1;let i=0,n=t,r;for(;i<=n;)if(r=Math.floor((n+i)/2),es[r].startTime&&i-1)for(let r=n,o=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function yp(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=yp(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(M.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(M.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;yp(i.textTracks).forEach(o=>{Ru(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${o?.groupId}`);return}const u=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,u)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,n=this.groupIds;let r=this.currentTrack;if(!i||n?.length!==i?.length||i!=null&&i.some(o=>n?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,g)=>{f.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=Lr(u,o);if(f>-1)r=o[f];else{const g=Lr(u,this.tracks);r=this.tracks[g]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(M.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=Lr(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,n=e.groupId,r=this.getUrlWithDirectives(e.url,t),o=e.details,u=o?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(M.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=yp(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Vv(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||!He(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(M.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!n.details&&!n.details.live;if(e===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(M.SUBTITLE_TRACK_SWITCH,{id:o,groupId:u,name:c,type:d,url:f});const g=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(g)}}function H8(){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 Fd(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const qu=.025;let Jp=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function G8(s,e,t){return`${s.identifier}-${t+1}-${Fd(e)}`}class V8{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 Fy(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=Fy(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=He(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 Fy(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 q8(this)}}function Fy(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Du(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class z8{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(M.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const o=()=>{this.hasDetails=!0};r.once(M.LEVEL_LOADED,o),r.once(M.AUDIO_TRACK_LOADED,o),r.once(M.SUBTITLE_TRACK_LOADED,o),r.on(M.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(M.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(M.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=TL(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=ut.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=ut.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: ${Du(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const p2=.033;class K8 extends Bn{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=n[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let n=0;nr.start&&e1)for(let r=0;ru&&(t!u.includes(d.identifier)):[];o.length&&o.sort((d,f)=>{const g=d.cue.pre,m=d.cue.post,v=f.cue.pre,_=f.cue.post;if(g&&!v)return-1;if(v&&!g||m&&!_)return 1;if(_&&!m)return-1;if(!g&&!v&&!m&&!_){const b=d.startTime,E=f.startTime;if(b!==E)return b-E}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=o,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],i=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const r=this.items,o=this.parseSchedule(n,e);(i||t.length||r?.length!==o.length||o.some((c,d)=>Math.abs(c.playout.start-r[d].playout.start)>.005||Math.abs(c.playout.end-r[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let o=0;o!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,g)=>{const m=f.cue.pre,v=f.cue.post,_=e[g-1]||null,b=f.appendInPlace,E=v?r:f.startOffset,w=f.duration,L=f.timelineOccupancy===Jp.Range?w:0,I=f.resumptionOffset,F=_?.startTime===E,B=E+f.cumulativeDuration;let V=b?B+w:E+I;if(m||!v&&E<=0){const q=d;d+=L,f.timelineStart=B;const R=o;o+=w,i.push({event:f,start:B,end:V,playout:{start:R,end:o},integrated:{start:q,end:d}})}else if(E<=r){if(!F){const P=E-c;if(P>p2){const z=c,ee=d;d+=P;const ie=o;o+=P;const Q={previousEvent:e[g-1]||null,nextEvent:f,start:z,end:z+P,playout:{start:ie,end:o},integrated:{start:ee,end:d}};i.push(Q)}else P>0&&_&&(_.cumulativeDuration+=P,i[i.length-1].end=E)}v&&(V=B),f.timelineStart=B;const q=d;d+=L;const R=o;o+=w,i.push({event:f,start:B,end:V,playout:{start:R,end:o},integrated:{start:q,end:d}})}else return;const N=f.resumeTime;v||N>r?c=r:c=N}),c{const d=u.cue.pre,f=u.cue.post,g=d?0:f?n:u.startTime;this.updateAssetDurations(u),o===g?u.cumulativeDuration=r:(r=0,o=g),!f&&u.snapOptions.in&&(u.resumeAnchor=El(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+1qu?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const u=t[o].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${c}`),!1;const d=El(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=o==="audio"?.175:0;return Math.abs(d.start-i){const E=m.data,w=E?.ASSETS;if(!Array.isArray(w)){const L=this.assignAssetListError(e,me.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),_.url,v,b);this.hls.trigger(M.ERROR,L);return}e.assetListResponse=E,this.hls.trigger(M.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:b})},onError:(m,v,_,b)=>{const E=this.assignAssetListError(e,me.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${v.url})`),v.url,b,_);this.hls.trigger(M.ERROR,E)},onTimeout:(m,v,_)=>{const b=this.assignAssetListError(e,me.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,m,_);this.hls.trigger(M.ERROR,b)}};return u.load(c,f,g),this.hls.trigger(M.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,o){return e.error=i,{type:Ye.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:o,stats:r}}}function g2(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Zf(s,e){return`[${s}] Advancing timeline position to ${e}`}class W8 extends Bn{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const n=i-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&i=u.end){var c;const v=this.findItemIndex(u);let _=this.schedule.findItemIndexAtTime(i);if(_===-1&&(_=v+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${i} (resolving from ${v} to ${_})`)),!this.isInterstitial(u)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!o&&_>v){const b=this.schedule.findJumpRestrictedIndex(v+1,_);if(b>v){this.setSchedulePosition(b);return}}this.setSchedulePosition(_);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,g=d.duration||0;if(o&&i=f+g){var m;(m=u.event)!=null&&m.appendInPlace&&(this.clearAssetPlayers(u.event,u),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(i>=n.end){this.timelinePos=n.end;const u=this.findItemIndex(n);this.setSchedulePosition(u+1)}const r=this.playingAsset;if(!r)return;const o=r.timelineStart+(r.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const o=this.playingItem,u=r.events||[],c=r.items||[],d=r.durations,f=i.map(b=>b.identifier),g=!!(u.length||f.length);(g||n)&&this.log(`INTERSTITIALS_UPDATED (${u.length}): ${u} +Schedule: ${c.map(b=>Yn(b))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let m=null,v=null;o&&(m=this.updateItem(o,this.timelinePos),this.itemsMatch(o,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const _=this.bufferingItem;if(_&&(v=this.updateItem(_,this.bufferedPos),this.itemsMatch(_,v)?this.bufferingItem=v:_.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(_.event,null))),i.forEach(b=>{b.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(b=>{if(b.interstitial.appendInPlace){const E=b.assetItem.timelineStart,w=b.timelineOffset-E;if(w)try{b.timelineOffset=E}catch(L){Math.abs(w)>qu&&this.warn(`${L} ("${b.assetId}" ${b.timelineOffset}->${E})`)}}}),g||n){if(this.hls.trigger(M.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(o)&&f.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(m,o),_&&v!==m&&this.trimInPlace(v,_),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Y8(e),this.schedule=new K8(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(M.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(M.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(M.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(M.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(M.BUFFER_APPENDED,this.onBufferAppended,this),e.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(M.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(M.MEDIA_ENDED,this.onMediaEnded,this),e.on(M.ERROR,this.onError,this),e.on(M.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(M.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(M.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(M.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(M.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(M.BUFFER_CODECS,this.onBufferCodecs,this),e.off(M.BUFFER_APPENDED,this.onBufferAppended,this),e.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(M.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(M.MEDIA_ENDED,this.onMediaEnded,this),e.off(M.ERROR,this.onError,this),e.off(M.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){Xs(e,"play",this.onPlay),Xs(e,"pause",this.onPause),Xs(e,"seeking",this.onSeeking),Xs(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;ks(i,"seeking",this.onSeeking),ks(i,"timeupdate",this.onTimeupdate),ks(i,"play",this.onPlay),ks(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=g=>g&&e.getAssetPlayer(g.identifier),n=(g,m,v,_,b)=>{if(g){let E=g[m].start;const w=g.event;if(w){if(m==="playout"||w.timelineOccupancy!==Jp.Point){const L=i(v);L?.interstitial===w&&(E+=L.assetItem.startOffset+L[b])}}else{const L=_==="bufferedPos"?o():e[_];E+=L-g.start}return E}return 0},r=(g,m)=>{var v;if(g!==0&&m!=="primary"&&(v=e.schedule)!=null&&v.length){var _;const b=e.schedule.findItemIndexAtTime(g),E=(_=e.schedule.items)==null?void 0:_[b];if(E){const w=E[m].start-E.start;return g+w}}return g},o=()=>{const g=e.bufferedPos;return g===Number.MAX_VALUE?u("primary"):Math.max(g,0)},u=g=>{var m,v;return(m=e.primaryDetails)!=null&&m.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[g])||0},c=(g,m)=>{var v,_;const b=e.effectivePlayingItem;if(b!=null&&(v=b.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${g} "${m}"`);const E=e.effectivePlayingItem,w=e.schedule.findItemIndexAtTime(g,m),L=(_=e.schedule.items)==null?void 0:_[w],I=e.getBufferingPlayer(),F=I?.interstitial,B=F?.appendInPlace,V=E&&e.itemsMatch(E,L);if(E&&(B||V)){const N=i(e.playingAsset),q=N?.media||e.primaryMedia;if(q){const R=m==="primary"?q.currentTime:n(E,m,e.playingAsset,"timelinePos","currentTime"),P=g-R,z=(B?R:q.currentTime)+P;if(z>=0&&(!N||B||z<=N.duration)){q.currentTime=z;return}}}if(L){let N=g;if(m!=="primary"){const R=L[m].start,P=g-R;N=L.start+P}const q=!e.isInterstitial(L);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(q||L.event.appendInPlace)){const R=e.media||(B?I?.media:null);R&&(R.currentTime=N)}else if(E){const R=e.findItemIndex(E);if(w>R){const z=e.schedule.findJumpRestrictedIndex(R+1,w);if(z>R){e.setSchedulePosition(z);return}}let P=0;if(q)e.timelinePos=N,e.checkBuffer();else{const z=L.event.assetList,ee=g-(L[m]||L).start;for(let ie=z.length;ie--;){const Q=z[ie];if(Q.duration&&ee>=Q.startOffset&&ee{const g=e.effectivePlayingItem;if(e.isInterstitial(g))return g;const m=t();return e.isInterstitial(m)?m:null},f={get bufferedEnd(){const g=t(),m=e.bufferingItem;if(m&&m===g){var v;return n(m,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const g=d(),m=e.effectivePlayingItem;return m&&m===g?n(m,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(g){const m=d(),v=e.effectivePlayingItem;v&&v===m&&c(g+v.playout.start,"playout")},get duration(){const g=d();return g?g.playout.end-g.playout.start:0},get assetPlayers(){var g;const m=(g=d())==null?void 0:g.event.assetList;return m?m.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var g;const m=(g=d())==null?void 0:g.event;return m&&e.effectivePlayingAsset?m.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var g;return((g=e.schedule)==null||(g=g.events)==null?void 0:g.slice(0))||[]},get schedule(){var g;return((g=e.schedule)==null||(g=g.items)==null?void 0:g.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 g=t();return e.findItemIndex(g)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const g=e.effectivePlayingItem;return e.findItemIndex(g)},primary:{get bufferedEnd(){return o()},get currentTime(){const g=e.timelinePos;return g>0?g:0},set currentTime(g){c(g,"primary")},get duration(){return u("primary")},get seekableStart(){var g;return((g=e.primaryDetails)==null?void 0:g.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(g){c(g,"integrated")},get duration(){return u("integrated")},get seekableStart(){var g;return r(((g=e.primaryDetails)==null?void 0:g.fragmentStart)||0,"integrated")}},skip:()=>{const g=e.effectivePlayingItem,m=g?.event;if(m&&!m.restrictions.skip){const v=e.findItemIndex(g);if(m.appendInPlace){const _=g.playout.start+g.event.duration;c(_+.001,"playout")}else e.advanceAfterAssetEnded(m,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||!He(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} ${ai(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var i,n;if(e.media===t)return;let r=null;const o=this.hls,u=e!==o,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(o.media)c&&(r=o.transferMedia(),this.detachedData=r),f="Primary";else if(d){const _=this.getBufferingPlayer();_?(r=_.transferMedia(),f=`${_}`):f="detached MediaSource"}else f="detached media";if(!r){if(d)r=this.detachedData,this.log(`using detachedData: MediaSource ${ai(r)}`);else if(!this.detachedData||o.media===t){const _=this.playerQueue;_.length>1&&_.forEach(b=>{if(u&&b.interstitial.appendInPlace!==c){const E=b.interstitial;this.clearInterstitial(b.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 g=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",m=g&&r?r:t;this.log(`${g?"transfering MediaSource":"attaching media"} to ${u?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const v=this.schedule;if(m===r&&v){const _=u&&e.assetId===v.assetIdAtEnd;m.overrides={duration:v.duration,endOfStream:!u||_,cueRemoval:!u}}e.attachMedia(m)}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(Zf("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(r>=0||!this.primaryLive){const o=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(o);this.setSchedulePosition(u)}}else if(n&&!this.playingItem){const r=e.findItemIndex(n);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,n=i.findAssetIndex(t),r=Uy(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var o;const u=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=Uy(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const o=t+1,u=r.length;if(o>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Yn(r)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(o)){const f=o.event,g=this.playingAsset,m=g?.identifier,v=m?this.getAssetPlayer(m):null;if(v&&m&&(!this.eventItemsMatch(o,r)||t!==void 0&&m!==f.assetList[t].identifier)){var c;const _=f.findAssetIndex(g);if(this.log(`INTERSTITIAL_ASSET_ENDED ${_+1}/${f.assetList.length} ${Du(g)}`),this.endedAsset=g,this.playingAsset=null,this.hls.trigger(M.INTERSTITIAL_ASSET_ENDED,{asset:g,assetListIndex:_,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),_);return}this.retreiveMediaSource(m,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(o,r)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${Yn(o)}`),f.hasPlayed=!0,this.hls.trigger(M.INTERSTITIAL_ENDED,{event:f,schedule:n.slice(0),scheduleIndex:e}),f.cue.once)){var d;this.updateSchedule();const _=(d=this.schedule)==null?void 0:d.items;if(r&&_){const b=this.findItemIndex(r);this.advanceSchedule(b,_,t,o,u)}return}}this.advanceSchedule(e,n,t,o,u)}advanceSchedule(e,t,i,n,r){const o=this.schedule;if(!o)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const g=f.interstitial,m=o.findEventIndex(g.identifier);(me+1)&&this.clearInterstitial(g,u)}),this.isInterstitial(u)){this.timelinePos=Math.min(Math.max(this.timelinePos,u.start),u.end);const f=u.event;if(i===void 0){i=o.findAssetIndex(f,this.timelinePos);const _=Uy(f,i-1);if(f.isAssetPastPlayoutLimit(_)||f.appendInPlace&&this.timelinePos===u.end){this.advanceAfterAssetEnded(f,e,i);return}i=_}const g=this.waitingItem;this.assetsBuffered(u,c)||this.setBufferingItem(u);let m=this.preloadAssets(f,i);if(this.eventItemsMatch(u,g||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${Yn(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(M.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(m||(m=this.getAssetPlayer(v.identifier)),m===null||m.destroyed){const _=f.assetList.length;this.warn(`asset ${i+1}/${_} player destroyed ${f}`),m=this.createAssetPlayer(f,v,i),m.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(m,i,t,e,c),this.shouldPlay&&g2(m.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&g2(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var n,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Yn(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(Zf("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Yn(e)}`),this.hls.trigger(M.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(in.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ut.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(Zf("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(M.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(M.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const n=qt(qt({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=qt(qt({},this.altSelection),{},{audio:i});return}const r=qt(qt({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=qt(qt({},this.altSelection),{},{subtitles:i});return}const r=qt(qt({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=E1(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=E1(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((r,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=ut.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Yn(e)} (was ${Yn(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=ut.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,i,e)}updateBufferedPos(e,t,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const o=this.playingItem,u=this.findItemIndex(o);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=m.event)!=null&&d.appendInPlace&&e+.01>=m.start)&&(c=g),this.isInterstitial(r)){const v=r.event;if(g-u>1&&v.appendInPlace===!1||v.assetList.length===0&&v.assetListLoader)return}if(this.bufferedPos=e,c>f&&c>u)this.bufferedToItem(m);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&m.start{const r=this.getAssetPlayer(n.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:n,events:r}=i;if(!n||!r)return t;const o=this.isInterstitial(e),u=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=u?u.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Yn(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,g)=>{const m=this.getAssetPlayer(f.identifier);m&&(g===d&&m.loadSource(),m.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(M.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,n=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(n||!r){const o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(o,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,o=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const m=this.playingItem;!this.isInterstitial(m)&&(m==null||(u=m.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 m=f-c;m>0&&(d=Math.round(m*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 g=this.assetListLoader.loadAssetList(e,d);g&&(e.assetListLoader=g)}else if(!o&&n){for(let d=t;d{this.hls.trigger(M.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&&F{if(F.live){var B;const q=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:Ye.OTHER_ERROR,details:me.INTERSTITIAL_ASSET_ITEM_ERROR,error:q},P=((B=this.schedule)==null?void 0:B.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,P,i,q.message);return}const V=F.edge-F.fragmentStart,N=t.duration;(b||N===null||V>N)&&(b=!1,this.log(`Interstitial asset "${g}" duration change ${N} > ${V}`),t.duration=V,this.updateSchedule())};_.on(M.LEVEL_UPDATED,(F,{details:B})=>E(B)),_.on(M.LEVEL_PTS_UPDATED,(F,{details:B})=>E(B)),_.on(M.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const w=(F,B)=>{const V=this.getAssetPlayer(g);if(V&&B.tracks){V.off(M.BUFFER_CODECS,w),V.tracks=B.tracks;const N=this.primaryMedia;this.bufferingAsset===V.assetItem&&N&&!V.media&&this.bufferAssetPlayer(V,N)}};_.on(M.BUFFER_CODECS,w);const L=()=>{var F;const B=this.getAssetPlayer(g);if(this.log(`buffered to end of asset ${B}`),!B||!this.schedule)return;const V=this.schedule.findEventIndex(e.identifier),N=(F=this.schedule.items)==null?void 0:F[V];this.isInterstitial(N)&&this.advanceAssetBuffering(N,t)};_.on(M.BUFFERED_TO_END,L);const I=F=>()=>{if(!this.getAssetPlayer(g)||!this.schedule)return;this.shouldPlay=!0;const V=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,V,F)};return _.once(M.MEDIA_ENDED,I(i)),_.once(M.PLAYOUT_LIMIT_REACHED,I(1/0)),_.on(M.ERROR,(F,B)=>{if(!this.schedule)return;const V=this.getAssetPlayer(g);if(B.details===me.BUFFER_STALLED_ERROR){if(V!=null&&V.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}`)}),_.on(M.DESTROYING,()=>{if(!this.getAssetPlayer(g)||!this.schedule)return;const B=new Error(`Asset player destroyed unexpectedly ${g}`),V={fatal:!0,type:Ye.OTHER_ERROR,details:me.INTERSTITIAL_ASSET_ITEM_ERROR,error:B};this.handleAssetItemError(V,e,this.schedule.findEventIndex(e.identifier),i,B.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Du(t)}`),this.hls.trigger(M.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:_}),_}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&&Yn(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(i,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,n,r){const{interstitial:o,assetItem:u,assetId:c}=e,d=o.assetList.length,f=this.playingAsset;this.endedAsset=null,this.playingAsset=u,(!f||f.identifier!==c)&&(f&&(this.clearAssetPlayer(f.identifier,i[n]),delete f.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Du(u)}`),this.hls.trigger(M.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:o}=e,u=this.schedule.findEventIndex(r.identifier),c=(i=this.schedule.items)==null?void 0:i[u];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=o;const d=this.getBufferingPlayer();if(d===e)return;const f=r.appendInPlace;if(f&&d?.interstitial.appendInPlace===!1)return;const g=d?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(f&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(g&&!tw(g,e.tracks)){const m=new Error(`Asset ${Du(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(g)}')`),v={fatal:!0,type:Ye.OTHER_ERROR,details:me.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},_=r.findAssetIndex(o);this.handleAssetItemError(v,r,u,_,m.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const n=i.currentTime,r=t.findAssetIndex(e,n),o=e.assetList[r];if(o){const u=this.getAssetPlayer(o.identifier);if(u){const c=u.currentTime||n-o.timelineStart,d=u.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${u} ${e} (media.currentTime: ${n})`),c&&(d/i.playbackRate<.5||u.bufferedInPlaceToEnd(i))&&u.hls){const f=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,f,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime!b.error))t.error=_;else for(let b=n;b{const w=parseFloat(b.DURATION);this.createAsset(r,E,f,c+f,w,b.URI),f+=w}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const g=this.waitingItem,m=g?.event.identifier===o;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(m){var _;const b=this.schedule.findEventIndex(o),E=(_=this.schedule.items)==null?void 0:_[b];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==b){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(b)}else if(v?.identifier===o){const b=r.assetList[0];if(b){const E=this.getAssetPlayer(b.identifier);if(v.appendInPlace){const w=this.primaryMedia;E&&w&&this.bufferAssetPlayer(E,w)}else E&&E.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case me.ASSET_LIST_PARSING_ERROR:case me.ASSET_LIST_LOAD_ERROR:case me.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case me.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 m2=500;class X8 extends JT{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",qe.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(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(M.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(M.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(M.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(M.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Ie.IDLE,this.setInterval(m2),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)||(Pi(i)&&(this.fragPrevious=i),this.state=Ie.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){o=r[d];break}const c=i.start+i.duration;o?o.end=c:(o={start:u,end:c},r.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(o=>{for(let u=0;unew zd(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new zd(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,qe.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!==Ie.STOPPED&&this.setInterval(m2)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:o,id:u}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${u}`);return}const c=r[u];if(u>=r.length||!c)return;this.log(`Subtitle track ${u} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(o.live||(i=c.details)!=null&&i.live){if(o.deltaUpdateFailed)return;const g=this.mainDetails;if(!g){this.startFragRequested=!1;return}const m=g.fragments[0];if(!c.details)o.hasProgramDateTime&&g.hasProgramDateTime?(Qp(o,g),d=o.fragmentStart):m&&(d=m.start,jv(o,d));else{var f;d=this.alignPlaylists(o,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&m&&(d=m.start,jv(o,d))}g&&!this.startFragRequested&&this.setStartPosition(g,d)}c.details=o,this.levelLastLoaded=c,u===n&&(this.hls.trigger(M.SUBTITLE_TRACK_UPDATED,{details:o,id:u,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===Ie.IDLE&&(El(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&Gu(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,QT(n.method)).catch(u=>{throw r.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(M.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:o,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=Ie.IDLE})}}doTick(){if(!this.media){this.state=Ie.IDLE;return}if(this.state===Ie.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),o=ut.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=o,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const g=d.fragments,m=g.length,v=d.edge;let _=null;const b=this.fragPrevious;if(uv-L?0:L;_=El(b,g,Math.max(g[0].start,u),I),!_&&b&&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 Z8={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},_L=s=>String.fromCharCode(Z8[s]||s),Wn=15,la=100,J8={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},e6={17:2,18:4,21:6,22:8,23:10,19:13,20:15},t6={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},i6={25:2,26:4,29:6,30:8,31:10,27:13,28:15},s6=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class n6{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;zt.log(`${this.time} [${e}] ${i}`)}}}const al=function(e){const t=[];for(let i=0;ila&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=la)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=_L(e);if(this.pos>=la){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 = "+ai(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+ai(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 y2{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 $y(i),this.nonDisplayedMemory=new $y(i),this.lastOutputScreen=new $y(i),this.currRollUpRow=this.displayedMemory.rows[Wn-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[Wn-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: "+ai(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 v2{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=l6(),this.logger=void 0;const n=this.logger=new n6;this.channels=[null,new y2(e,t,n),new y2(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"["+al([t[i],t[i+1]])+"] -> ("+al([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(o6(n,r,c)){Jf(null,null,c),this.logger.log(3,()=>"Repeated command ("+al([n,r])+") is dropped");continue}Jf(n,r,this.cmdHistory),o=this.parseCmd(n,r),o||(o=this.parseMidrow(n,r)),o||(o=this.parsePAC(n,r)),o||(o=this.parseBackgroundAttributes(n,r))}else Jf(null,null,c);if(!o&&(u=this.parseChars(n,r),u)){const f=this.currentChannel;f&&f>0?this.channels[f].insertChars(u):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+al([n,r])+" orig: "+al([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(i||n))return!1;const r=e===20||e===21||e===23?1:2,o=this.channels[r];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+al([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(n||r))return!1;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?J8[e]:t6[e]:i=o===1?e6[e]:i6[e];const u=this.channels[o];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let o;r===17?o=t+80:r===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+_L(o)+"' in channel "+i),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+al(n).join(",")),n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const o={};e===16||e===24?(r=Math.floor((t-32)/2),o.background=s6[r],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(o),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");V=P,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},g,{get:function(){return N},set:function(P){const z=n(P);if(!z)throw new SyntaxError("An invalid or illegal string was specified.");N=z,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},g,{get:function(){return q},set:function(P){if(P<0||P>100)throw new Error("Size must be between 0 and 100.");q=P,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},g,{get:function(){return R},set:function(P){const z=n(P);if(!z)throw new SyntaxError("An invalid or illegal string was specified.");R=z,this.hasBeenReset=!0}})),f.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})();class u6{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function SL(s){function e(i,n,r,o){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(o||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class c6{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 xL(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const o=n[r].split(t);if(o.length!==2)continue;const u=o[0],c=o[1];e(u,c)}}const Wv=new d_(0,0,""),ep=Wv.align==="middle"?"middle":"center";function d6(s,e,t){const i=s;function n(){const u=SL(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 c6;xL(u,function(m,v){let _;switch(m){case"region":for(let b=t.length-1;b>=0;b--)if(t[b].id===v){d.set(m,t[b].region);break}break;case"vertical":d.alt(m,v,["rl","lr"]);break;case"line":_=v.split(","),d.integer(m,_[0]),d.percent(m,_[0])&&d.set("snapToLines",!1),d.alt(m,_[0],["auto"]),_.length===2&&d.alt("lineAlign",_[1],["start",ep,"end"]);break;case"position":_=v.split(","),d.percent(m,_[0]),_.length===2&&d.alt("positionAlign",_[1],["start",ep,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,v);break;case"align":d.alt(m,v,["start",ep,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&Wv.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",ep);let g=d.get("position","auto");g==="auto"&&Wv.position===50&&(g=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=g}function o(){s=s.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),o(),e.endTime=n(),o(),r(s,e)}function EL(s){return s.replace(//gi,` +`)}class h6{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new u6,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,o=0;for(r=EL(r);o")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{d6(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const u=r.indexOf("-->")!==-1;if(!r||u&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` +`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` + +`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const f6=/\r\n|\n\r|\n|\r/g,jy=function(e,t,i=0){return e.slice(i,i+t.length)===t},p6=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(!He(t)||!He(i)||!He(n)||!He(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function h_(s,e,t){return Fd(s.toString())+Fd(e.toString())+Fd(t)}const g6=function(e,t,i){let n=e[t],r=e[n.prevCC];if(!r||!r.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=r)!=null&&o.new;){var o;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function m6(s,e,t,i,n,r,o){const u=new h6,c=mn(new Uint8Array(s)).trim().replace(f6,` +`).split(` +`),d=[],f=e?SU(e.baseTime,e.timescale):0;let g="00:00.000",m=0,v=0,_,b=!0;u.oncue=function(E){const w=t[i];let L=t.ccOffset;const I=(m-f)/9e4;if(w!=null&&w.new&&(v!==void 0?L=t.ccOffset=w.start:g6(t,i,I)),I){if(!e){_=new Error("Missing initPTS for VTT MPEGTS");return}L=I-t.presentationOffset}const F=E.endTime-E.startTime,B=pn((E.startTime+L-v)*9e4,n*9e4)/9e4;E.startTime=Math.max(B,0),E.endTime=Math.max(B+F,0);const V=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(V)),E.id||(E.id=h_(E.startTime,E.endTime,V)),E.endTime>0&&d.push(E)},u.onparsingerror=function(E){_=E},u.onflush=function(){if(_){o(_);return}r(d)},c.forEach(E=>{if(b)if(jy(E,"X-TIMESTAMP-MAP=")){b=!1,E.slice(16).split(",").forEach(w=>{jy(w,"LOCAL:")?g=w.slice(6):jy(w,"MPEGTS:")&&(m=parseInt(w.slice(7)))});try{v=p6(g)/1e3}catch(w){_=w}return}else E===""&&(b=!1);u.parse(E+` +`)}),u.flush()}const Hy="stpp.ttml.im1t",AL=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,CL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,y6={left:"start",center:"center",right:"end",start:"start",end:"end"};function T2(s,e,t,i){const n=vt(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>mn(u)),o=bU(e.baseTime,1,e.timescale);try{r.forEach(u=>t(v6(u,o)))}catch(u){i(u)}}function v6(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(r).reduce((g,m)=>(g[m]=n.getAttribute(`ttp:${m}`)||r[m],g),{}),u=n.getAttribute("xml:space")!=="preserve",c=_2(Gy(n,"styling","style")),d=_2(Gy(n,"layout","region")),f=Gy(n,"body","[begin]");return[].map.call(f,g=>{const m=DL(g,u);if(!m||!g.hasAttribute("begin"))return null;const v=qy(g.getAttribute("begin"),o),_=qy(g.getAttribute("dur"),o);let b=qy(g.getAttribute("end"),o);if(v===null)throw b2(g);if(b===null){if(_===null)throw b2(g);b=v+_}const E=new d_(v-e,b-e,m);E.id=h_(E.startTime,E.endTime,E.text);const w=d[g.getAttribute("region")],L=c[g.getAttribute("style")],I=T6(w,L,c),{textAlign:F}=I;if(F){const B=y6[F];B&&(E.lineAlign=B),E.align=F}return Zt(E,I),E}).filter(g=>g!==null)}function Gy(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function _2(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function DL(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?DL(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function T6(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),r.reduce((u,c)=>{const d=Vy(e,i,c)||Vy(s,i,c)||Vy(n,i,c);return d&&(u[c]=d),u},{})}function Vy(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function b2(s){return new Error(`Could not parse ttml timestamp ${s}`)}function qy(s,e){if(!s)return null;let t=SL(s);return t===null&&(AL.test(s)?t=_6(s,e):CL.test(s)&&(t=b6(s,e))),t}function _6(s,e){const t=AL.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 b6(s,e){const t=CL.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 tp{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 S6{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=x2(),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(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(M.FRAG_LOADING,this.onFragLoading,this),e.on(M.FRAG_LOADED,this.onFragLoaded,this),e.on(M.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(M.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(M.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(M.FRAG_LOADING,this.onFragLoading,this),e.off(M.FRAG_LOADED,this.onFragLoaded,this),e.off(M.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(M.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(M.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(M.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new tp(this,"textTrack1"),t=new tp(this,"textTrack2"),i=new tp(this,"textTrack3"),n=new tp(this,"textTrack4");this.cea608Parser1=new v2(1,e,t),this.cea608Parser2=new v2(3,i,n)}addCues(e,t,i,n,r){let o=!1;for(let u=r.length;u--;){const c=r[u],d=x6(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),o=!0,d/(i-t)>.5))return}if(o||r.push([t,i]),this.config.renderTextTracksNatively){const u=this.captionsTracks[e];this.Cues.newCue(u,t,i,n)}else{const u=this.Cues.newCue(null,t,i,n);this.hls.trigger(M.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:o}){const{unparsedVttFrags:u}=this;i===qe.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:o}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(M.FRAG_LOADED,c):this.hls.trigger(M.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{Ru(n[r]),delete n[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=x2(),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===Hy);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(nL(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const o=this.media,u=o?yp(o.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let g=null;for(let m=0;md!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(M.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,o=this.captionsProperties[r];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===qe.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:o,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&o&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),o.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===qe.SUBTITLE)if(n.byteLength){const r=i.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){const u=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),u&&u.textCodec===Hy?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;T2(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:o}=this,u=r.length-1;if(!r[i.cc]&&u===-1){o.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?Pn(i.initSegment.data,new Uint8Array(n)).buffer:n;m6(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const g=f.message==="Missing initPTS for VTT MPEGTS";g?o.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(g&&u>i.cc)&&c.trigger(M.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||T2(t,this.initPTS[e.cc],()=>{i.textCodec=Hy,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=>vL(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(M.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===qe.SUBTITLE&&this.onFragLoaded(M.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===qe.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;rYv(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>Yv(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=EL(d.trim()),_=h_(e,t,v);s!=null&&(g=s.cues)!=null&&g.getCueById(_)||(o=new f(e,t,v),o.id=_,o.line=m+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((m,v)=>m.line==="auto"||v.line==="auto"?0:m.line>8&&v.line>8?v.line-m.line:m.line-v.line),n.forEach(m=>vL(s,m))),n}};function C6(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const D6=/(\d+)-(\d+)\/(\d+)/;class E2{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||R6,this.controller=new self.AbortController,this.stats=new VT}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=w6(e,this.controller.signal),o=e.responseType==="arraybuffer",u=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&He(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Wd(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(g=>{var m;this.response=this.loader=g;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)),!g.ok){const{status:b,statusText:E}=g;throw new k6(E||"fetch, bad network response",b,g)}n.loading.first=v,n.total=I6(g.headers)||n.total;const _=(m=this.callbacks)==null?void 0:m.onProgress;return _&&He(t.highWaterMark)?this.loadProgressively(g,n,e,t.highWaterMark,_):o?g.arrayBuffer():e.responseType==="json"?g.json():g.text()}).then(g=>{var m,v;const _=this.response;if(!_)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const b=g[u];b&&(n.loaded=n.total=b);const E={url:_.url,data:g,code:_.status},w=(m=this.callbacks)==null?void 0:m.onProgress;w&&!He(t.highWaterMark)&&w(n,e,g,_),(v=this.callbacks)==null||v.onSuccess(E,n,e,_)}).catch(g=>{var m;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=g&&g.code||0,_=g?g.message:null;(m=this.callbacks)==null||m.onError({code:v,text:_},e,g?g.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const o=new Fw,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return o.dataLength&&r(t,i,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,g=f.length;return t.loaded+=g,g=n&&r(t,i,o.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function w6(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Zt({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function L6(s){const e=D6.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function I6(s){const e=s.get("Content-Range");if(e){const i=L6(e);if(He(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function R6(s,e){return new self.Request(s.url,e)}class k6 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const O6=/^age:\s*[\d.]+\s*$/im;class LL{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 VT,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(o=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:o.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:o}=i.loadPolicy;if(n)for(const u in n)e.setRequestHeader(u,n[u]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&He(r)?r:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,f=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const _=f??t.response;if(_!=null){var o,u;i.loading.end=Math.max(self.performance.now(),i.loading.first);const b=t.responseType==="arraybuffer"?_.byteLength:_.length;i.loaded=i.total=b,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(o=this.callbacks)==null?void 0:o.onProgress;E&&E(i,e,_,t);const w={url:t.responseURL,data:_,code:d};(u=this.callbacks)==null||u.onSuccess(w,i,e,t);return}}const g=r.loadPolicy.errorRetry,m=i.retry,v={url:e.url,data:void 0,code:d};if(Yp(g,m,!1,v))this.retry(g);else{var c;zt.error(`${d} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:d,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Yp(e,t,!0))this.retry(e);else{var i;zt.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=YT(e,i.retry),i.retry++,zt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&O6.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 P6={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},M6=qt(qt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:LL,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:KF,bufferController:BU,capLevelController:l_,errorController:ZF,fpsController:F8,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:Dw,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:P6},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},N6()),{},{subtitleStreamController:X8,subtitleTrackController:j8,timelineController:S6,audioStreamController:OU,audioTrackController:PU,emeController:Vu,cmcdController:P8,contentSteeringController:N8,interstitialsController:W8});function N6(){return{cueHandler:A6,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 B6(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=Xv(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const u=`${o==="level"?"playlist":o}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const g=`${o}Loading${f}`,m=e[g];if(m!==void 0&&c){d.push(g);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=m,v.maxTimeToFirstByteMs=m;break;case"MaxRetry":v.errorRetry.maxNumRetry=m,v.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":v.errorRetry.retryDelayMs=m,v.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=m,v.timeoutRetry.maxRetryDelayMs=m;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${ai(e[u])}`)}),qt(qt({},i),e)}function Xv(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Xv):Object.keys(s).reduce((e,t)=>(e[t]=Xv(s[t]),e),{}):s}function F6(s,e){const t=s.loader;t!==E2&&t!==LL?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):C6()&&(s.loader=E2,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const vp=2,U6=.1,$6=.05,j6=100;class H6 extends Sw{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(M.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.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(j6),this.mediaSource=t.mediaSource;const i=this.media=t.media;ks(i,"playing",this.onMediaPlaying),ks(i,"waiting",this.onMediaWaiting),ks(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Xs(i,"playing",this.onMediaPlaying),Xs(i,"waiting",this.onMediaWaiting),Xs(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,n;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const o=this.media;if(!o)return;const{seeking:u}=o,c=this.seeking&&!u,d=!this.seeking&&u,f=o.paused&&!u||o.ended||o.playbackRate===0;if(this.seeking=u,e!==t){t&&(this.ended=0),this.moved=!0,u||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(M.MEDIA_ENDED,{stalled:!1}));return}if(!ut.getBuffered(o).length){this.nudgeRetry=0;return}const g=ut.bufferInfo(o,e,0),m=g.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const V=A2(this.hls.inFlightFragments,e),N=g.len>vp,q=!m||V||m-e>vp&&!v.getPartialFragment(e);if(N||q)return;this.moved=!1}const _=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&v){if(!(g.len>0)&&!m)return;const N=Math.max(m,g.start||0)-e,R=!!(_!=null&&_.live)?_.targetduration*2:vp,P=ip(e,v);if(N>0&&(N<=R||P)){o.paused||this._trySkipBufferHole(P);return}}const b=r.detectStallWithCurrentTimeMs,E=self.performance.now(),w=this.waiting;let L=this.stalled;if(L===null)if(w>0&&E-w=b||w)&&this.hls){var F;if(((F=this.mediaSource)==null?void 0:F.readyState)==="ended"&&!(_!=null&&_.live)&&Math.abs(e-(_?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(M.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(g),!this.media||!this.hls)return}const B=ut.bufferInfo(o,e,r.maxBufferHole);this._tryFixBufferStall(B,I,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(M.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=ut.bufferedInfo(ut.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const o=ut.timeRangesToArray(n),u=ut.bufferedInfo(o,t,0).bufferedIndex;if(u>-1&&uu)&&f-d<1&&e-d<2){const g=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${f} buffered index: ${c}`);this.warn(g.message),this.media.currentTime+=1e-6;let m=ip(e,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const v=ut.bufferInfo(this.media,e,0);this.hls.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,frag:m,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:o,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!o||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=ip(i,o);if((f||d!=null&&d.live&&i1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-ic.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,n=e.nextStart;if(i&&n){const r=i.getFragAtPos(t,qe.MAIN),o=i.getFragAtPos(n,qe.MAIN);if(r&&o)return o.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:n,stalled:r}=this;if(!n&&r!==null&&i&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ai(e)})`);this.warn(o.message),t.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:n}=this,r=(t=this.hls)==null?void 0:t.config;if(!n||!i||!r)return 0;const o=n.currentTime,u=ut.bufferInfo(n,o,0),c=o0&&u.len<1&&n.readyState<3,m=c-o;if(m>0&&(f||g)){if(m>r.maxBufferHole){let _=!1;if(o===0){const b=i.getAppendedFrag(0,qe.MAIN);b&&c"u"))return self.VTTCue||self.TextTrackCue}function zy(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,ai(n?qt({type:n},i):i))}return r}const sp=(()=>{const s=Qv();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class V6{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(M.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(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(M.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(M.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.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&&Ru(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;tsp&&(g=sp),g-f<=0&&(g=f+G6);for(let v=0;vf.type===gn.audioId3&&c:n==="video"?d=f=>f.type===gn.emsg&&u:d=f=>f.type===gn.audioId3&&c||f.type===gn.emsg&&u,Yv(r,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:o}=this.hls.config;if(!r)return;const u=Qv();if(i&&n&&!o){const{fragmentStart:b,fragmentEnd:E}=e;let w=this.assetCue;w?(w.startTime=b,w.endTime=E):u&&(w=this.assetCue=zy(u,b,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),w&&(w.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(w),w.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=e,f=Object.keys(d);let g=this.dateRangeCuesAppended;if(c&&t){var m;if((m=c.cues)!=null&&m.length){const b=Object.keys(g).filter(E=>!f.includes(E));for(let E=b.length;E--;){var v;const w=b[E],L=(v=g[w])==null?void 0:v.cues;delete g[w],L&&Object.keys(L).forEach(I=>{const F=L[I];if(F){F.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(F)}catch{}}})}}else g=this.dateRangeCuesAppended={}}const _=e.fragments[e.fragments.length-1];if(!(f.length===0||!He(_?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let b=0;b{if(ee!==w.id){const ie=d[ee];if(ie.class===w.class&&ie.startDate>w.startDate&&(!z||w.startDate.01&&(ee.startTime=L,ee.endTime=V);else if(u){let ie=w.attr[z];h5(z)&&(ie=iw(ie));const oe=zy(u,L,V,{key:z,data:ie},gn.dateRange);oe&&(oe.id=E,this.id3Track.addCue(oe),F[z]=oe,o&&(z==="X-ASSET-LIST"||z==="X-ASSET-URL")&&oe.addEventListener("enter",this.onEventCueEnter))}}g[E]={cues:F,dateRange:w,durationKnown:B}}}}}class q6{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:o}=this.config;if(!r||o===1||!i.live)return;const u=this.targetLatency;if(u===null)return;const c=n-u,d=Math.min(this.maxLatency,u+i.targetduration);if(c.05&&this.forwardBufferLength>1){const g=Math.min(2,Math.max(1,o)),m=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(t,v)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:u}=this.config,c=this.hls.userConfig;let d=u&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=r!==void 0?r:o*n);const f=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,o=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,r),u)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(M.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(M.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(M.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(M.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===me.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 z6 extends o_{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(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this),e.on(M.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.FRAG_BUFFERED,this.onFragBuffered,this),e.off(M.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,n=[],r={},o={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const g=f.attrs;let{audioCodec:m,videoCodec:v}=f;m&&(f.audioCodec=m=Vp(m,i)||void 0),v&&(v=f.videoCodec=wF(v));const{width:_,height:b,unknownCodecs:E}=f,w=E?.length||0;if(u||(u=!!(_&&b)),c||(c=!!v),d||(d=!!m),w||m&&!this.isAudioSupported(m)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${g.CODECS}"`);return}const{CODECS:L,"FRAME-RATE":I,"HDCP-LEVEL":F,"PATHWAY-ID":B,RESOLUTION:V,"VIDEO-RANGE":N}=g,R=`${`${B||"."}-`}${f.bitrate}-${V}-${I}-${L}-${N}-${F}`;if(r[R])if(r[R].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const P=o[R]+=1;f.attrs["PATHWAY-ID"]=new Array(P+1).join(".");const z=this.createLevel(f);r[R]=z,n.push(z)}else r[R].addGroupId("audio",g.AUDIO),r[R].addGroupId("text",g.SUBTITLES);else{const P=this.createLevel(f);r[R]=P,o[R]=1,n.push(P)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new zd(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(n.message),t.supportedResult=pw(n,[])}return t}isAudioSupported(e){return Vd(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Vd(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var o;let u=[],c=[],d=e;const f=((o=t.stats)==null?void 0:o.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:L,videoRange:I,width:F,height:B})=>(!!L||!!(F&&B))&&FF(I))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let L="no level with compatible codecs found in manifest",I=L;t.levels.length&&(I=`one or more CODECS in variant not supported: ${ai(t.levels.map(B=>B.attrs.CODECS).filter((B,V,N)=>N.indexOf(B)===V))}`,this.warn(I),L+=` (${I})`);const F=new Error(L);this.hls.trigger(M.ERROR,{type:Ye.MEDIA_ERROR,details:me.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:F,reason:I})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(L=>!L.audioCodec||this.isAudioSupported(L.audioCodec)),D2(u)),t.subtitles&&(c=t.subtitles,D2(c));const g=d.slice(0);d.sort((L,I)=>{if(L.attrs["HDCP-LEVEL"]!==I.attrs["HDCP-LEVEL"])return(L.attrs["HDCP-LEVEL"]||"")>(I.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&L.height!==I.height)return L.height-I.height;if(L.frameRate!==I.frameRate)return L.frameRate-I.frameRate;if(L.videoRange!==I.videoRange)return qp.indexOf(L.videoRange)-qp.indexOf(I.videoRange);if(L.videoCodec!==I.videoCodec){const F=v1(L.videoCodec),B=v1(I.videoCodec);if(F!==B)return B-F}if(L.uri===I.uri&&L.codecSet!==I.codecSet){const F=Gp(L.codecSet),B=Gp(I.codecSet);if(F!==B)return B-F}return L.averageBitrate!==I.averageBitrate?L.averageBitrate-I.averageBitrate:0});let m=g[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==g.length)){for(let L=0;LF&&F===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=B)}break}const _=r&&!n,b=this.hls.config,E=!!(b.audioStreamController&&b.audioTrackController),w={levels:d,audioTracks:u,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:E&&!_&&u.some(L=>!!L.url)};f.end=performance.now(),this.hls.trigger(M.MANIFEST_PARSED,w)}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"),g=e<0;if(this.hls.trigger(M.ERROR,{type:Ye.OTHER_ERROR,details:me.LEVEL_SWITCH_ERROR,level:e,fatal:g,error:f,reason:f.message}),g)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],u=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(M.LEVEL_SWITCHING,c);const d=o.details;if(!d||d.live){const f=this.switchParams(o.uri,n?.details,d);this.loadPlaylist(f)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===bt.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===qe.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var i;const{level:n,details:r}=t,o=t.levelInfo;if(!o){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],o=e.details,u=o?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&o.live?" age "+u.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(M.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(u=>u.level=-1)),!1));Mw(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(M.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(M.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function D2(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function IL(){return self.SourceBuffer||self.WebKitSourceBuffer}function RL(){if(!So())return!1;const e=IL();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function K6(){if(!RL())return!1;const s=So();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(qd(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(qd(e,"audio"))))}function Y6(){var s;const e=IL();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const W6=100;class X6 extends JT{constructor(e,t,i){super(e,t,i,"stream-controller",qe.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||!He(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const o=this.getFwdBufferInfoAtPos(n,r,qe.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(M.MANIFEST_PARSED,this.onManifestParsed,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.LEVEL_LOADED,this.onLevelLoaded,this),e.on(M.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(M.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(M.BUFFER_CREATED,this.onBufferCreated,this),e.on(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(M.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(M.MANIFEST_PARSED,this.onManifestParsed,this),e.off(M.LEVEL_LOADED,this.onLevelLoaded,this),e.off(M.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(M.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(M.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(M.BUFFER_CREATED,this.onBufferCreated,this),e.off(M.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(M.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(W6),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=Ie.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Ie.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ie.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=Ie.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Ie.IDLE;break}break}case Ie.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Ie.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const o=i[r],u=this.getMainFwdBufferInfo();if(u===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(u,c)){const b={};this.altAudio===2&&(b.type="video"),this.hls.trigger(M.BUFFER_EOS,b),this.state=Ie.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const d=o.details;if(!d||this.state===Ie.WAITING_LEVEL||this.waitForLive(o)){this.level=r,this.state=Ie.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,g=this.getMaxBufferLength(o.maxBitrate);if(f>=g)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const m=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(m,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&Pi(v)&&this.fragmentTracker.getState(v)!==Ki.OK){var _;const E=((_=this.backtrackFragment)!=null?_:v).sn-d.startSN,w=d.fragments[E-1];w&&v.cc===w.cc&&(v=w,this.fragmentTracker.removeFragment(w))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,m)){if(!v.gap){const E=this.audioOnly&&!this.altAudio?ni.AUDIO:ni.VIDEO,w=(E===ni.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;w&&this.afterBufferFlushed(w,E,qe.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,qe.MAIN,g)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,o,m))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===Ki.NOT_LOADED||n===Ki.PARTIAL?Pi(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,qe.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const u=this.getMainFwdBufferInfo();if(!u||u.len=o-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(M.AUDIO_TRACK_SWITCHED,t)}),i.trigger(M.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(M.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=zp(t.url,this.hls);if(i){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,o=!1;for(const u in i){const c=i[u];if(c.id==="main"){if(r=u,n=c,u==="video"){const d=i[u];d&&(this.videoBuffer=d.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t,r=i.type===qe.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===Ie.PARSED&&(this.state=Ie.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),Pi(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const o=this.media;o&&(!this._hasEnoughToStart&&ut.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=Ie.ERROR;return}switch(t.details){case me.FRAG_GAP:case me.FRAG_PARSING_ERROR:case me.FRAG_DECRYPT_ERROR:case me.FRAG_LOAD_ERROR:case me.FRAG_LOAD_TIMEOUT:case me.KEY_LOAD_ERROR:case me.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(qe.MAIN,t);break;case me.LEVEL_LOAD_ERROR:case me.LEVEL_LOAD_TIMEOUT:case me.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ie.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===bt.LEVEL&&(this.state=Ie.IDLE);break;case me.BUFFER_ADD_CODEC_ERROR:case me.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case me.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 me.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Ie.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ni.AUDIO||!this.altAudio){const i=(t===ni.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,qe.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=Ie.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=r.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(M.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===Ie.STOPPED||this.state===Ie.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=o,{video:f,text:g,id3:m,initSegment:v}=n,{details:_}=d,b=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=Ie.PARSING,v){const E=v.tracks;if(E){const F=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,E,F,r),i.trigger(M.FRAG_PARSING_INIT_SEGMENT,{frag:F,id:t,tracks:E})}const w=v.initPTS,L=v.timescale,I=this.initPTS[u.cc];if(He(w)&&(!I||I.baseTime!==w||I.timescale!==L)){const F=v.trackId;this.initPTS[u.cc]={baseTime:w,timescale:L,trackId:F},i.trigger(M.INIT_PTS_FOUND,{frag:u,id:t,initPTS:w,timescale:L,trackId:F})}}if(f&&_){b&&f.type==="audiovideo"&&this.logMuxedErr(u);const E=_.fragments[u.sn-1-_.startSN],w=u.sn===_.startSN,L=!E||u.cc>E.cc;if(n.independent!==!1){const{startPTS:I,endPTS:F,startDTS:B,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:I,endPTS:F,startDTS:B,endDTS:V};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!L&&(this.couldBacktrack=!0),f.dropped&&f.independent){const N=this.getMainFwdBufferInfo(),q=(N?N.end:this.getLoadPosition())+this.config.maxBufferHole,R=f.firstKeyFramePTS?f.firstKeyFramePTS:I;if(!w&&qvp&&(u.gap=!0);u.setElementaryStreamInfo(f.type,I,F,B,V),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(f,u,c,r,w||L)}else if(w||L)u.gap=!0;else{this.backtrack(u);return}}if(b){const{startPTS:E,endPTS:w,startDTS:L,endDTS:I}=b;c&&(c.elementaryStreams[ni.AUDIO]={startPTS:E,endPTS:w,startDTS:L,endDTS:I}),u.setElementaryStreamInfo(ni.AUDIO,E,w,L,I),this.bufferFragmentData(b,u,c,r)}if(_&&m!=null&&m.samples.length){const E={id:t,frag:u,details:_,samples:m.samples};i.trigger(M.FRAG_PARSING_METADATA,E)}if(_&&g){const E={id:t,frag:u,details:_,samples:g.samples};i.trigger(M.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${Pi(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==Ie.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:o,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=dp(r.codec,d);f==="mp4a"&&(f="mp4a.40.5");const g=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const m=r.metadata;m&&"channelCount"in m&&(m.channelCount||1)!==1&&g.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&g.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=qe.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=qe.MAIN;const d=o.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${o.codec!==d?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}u&&(this.log(`Init audiovideo buffer, container:${u.container}, codecs[level/parsed]=[${e.codecs}/${u.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(M.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const g=t[d].initSegment;g!=null&&g.byteLength&&this.hls.trigger(M.BUFFER_APPENDING,{type:d,data:g,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,qe.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=Ie.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ut.isBuffered(e,i)?t=this.getAppendedFrag(i):ut.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(M.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(M.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 He(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(He(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?El(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const o=r+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Q6 extends Bn{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=me.KEY_LOAD_ERROR,i,n,r){return new ua({type:Ye.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,r=t.length;n{if(!this.emeController)return;o.setKeyFormat(u);const c=fp(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=Cd(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,me.KEY_LOAD_ERROR,d))}const o=r.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,me.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const u=Ky(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:g}=f;return r.key=g.decryptdata.key,{frag:e,keyInfo:g}})}switch(this.log(`${this.keyIdToKeyInfo[u]?"Rel":"L"}oading${r.keyId?" keyId: "+ds(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,me.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=mF(t.initSegment.data);if(o.length){let u=o[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${ds(u)}`),To.setKeyIdForUri(e.decryptdata.uri,u)):(u=To.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ds(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!Pi(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(o=>(e.mediaKeySessionContext=o,i))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((o,u)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,v,_,b)=>{const{frag:E,keyInfo:w}=_,L=Ky(w.decryptdata);if(!E.decryptdata||w!==this.keyIdToKeyInfo[L])return u(this.createKeyLoadError(E,me.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),b));w.decryptdata.key=E.decryptdata.key=new Uint8Array(m.data),E.keyLoader=null,w.loader=null,o({frag:E,keyInfo:w})},onError:(m,v,_,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,me.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),_,qt({url:c.url,data:void 0},m)))},onTimeout:(m,v,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,me.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),_))},onAbort:(m,v,_)=>{this.resetLoader(v),u(this.createKeyLoadError(t,me.INTERNAL_ABORTED,new Error("key loading aborted"),_))}};r.load(c,f,g)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const o=Ky(i.decryptdata)||n;delete this.keyIdToKeyInfo[o],r&&r.destroy()}}function Ky(s){if(s.keyFormat!==hs.FAIRPLAY){const e=s.keyId;if(e)return ds(e)}return s.uri}function w2(s){const{type:e}=s;switch(e){case bt.AUDIO_TRACK:return qe.AUDIO;case bt.SUBTITLE_TRACK:return qe.SUBTITLE;default:return qe.MAIN}}function Yy(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Z6{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(M.MANIFEST_LOADING,this.onManifestLoading,this),e.on(M.LEVEL_LOADING,this.onLevelLoading,this),e.on(M.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(M.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(M.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(M.MANIFEST_LOADING,this.onManifestLoading,this),e.off(M.LEVEL_LOADING,this.onLevelLoading,this),e.off(M.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(M.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(M.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,o=new r(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:bt.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:o,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:bt.LEVEL,url:o,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:bt.AUDIO_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:o,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:bt.SUBTITLE_TRACK,url:r,deliveryDirectives:o,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[bt.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[bt.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===bt.MANIFEST?r=i.manifestLoadPolicy.default:r=Zt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),He((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===bt.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===bt.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===bt.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,g=d.targetduration;if(f&&g){const m=Math.max(f*3,g*.8)*1e3;r=Zt({},r,{maxTimeToFirstByteMs:Math.min(m,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,r.maxTimeToFirstByteMs)})}}}const o=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(d,f,g,m)=>{const v=this.getInternalLoader(g);this.resetInternalLoader(g.type);const _=d.data;f.parsing.start=performance.now(),Ir.isMediaPlaylist(_)||g.type!==bt.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,g,m||null,v):this.handleMasterPlaylist(d,f,g,m)},onError:(d,f,g,m)=>{this.handleNetworkError(f,g,!1,d,m)},onTimeout:(d,f,g)=>{this.handleNetworkError(f,g,!0,void 0,d)}};n.load(e,u,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,n){const r=this.hls,o=e.data,u=Yy(e,i),c=Ir.parseMasterPlaylist(o,u);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,n,t);return}const{contentSteering:d,levels:f,sessionData:g,sessionKeys:m,startTimeOffset:v,variableList:_}=c;this.variableList=_,f.forEach(L=>{const{unknownCodecs:I}=L;if(I){const{preferManagedMediaSource:F}=this.hls.config;let{audioCodec:B,videoCodec:V}=L;for(let N=I.length;N--;){const q=I[N];Vd(q,"audio",F)?(L.audioCodec=B=B?`${B},${q}`:q,tc.audio[B.substring(0,4)]=2,I.splice(N,1)):Vd(q,"video",F)&&(L.videoCodec=V=V?`${V},${q}`:q,tc.video[V.substring(0,4)]=2,I.splice(N,1))}}});const{AUDIO:b=[],SUBTITLES:E,"CLOSED-CAPTIONS":w}=Ir.parseMasterPlaylistMedia(o,u,c);b.length&&!b.some(I=>!I.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"),b.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ti({}),bitrate:0,url:""})),r.trigger(M.MANIFEST_LOADED,{levels:f,audioTracks:b,subtitles:E,captions:w,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:g,sessionKeys:m,startTimeOffset:v,variableList:_})}handleTrackOrLevelPlaylist(e,t,i,n,r){const o=this.hls,{id:u,level:c,type:d}=i,f=Yy(e,i),g=He(c)?c:He(u)?u:0,m=w2(i),v=Ir.parseLevelPlaylist(e.data,f,g,m,0,this.variableList);if(d===bt.MANIFEST){const _={attrs:new Ti({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+kw(v,0),o.trigger(M.MANIFEST_LOADED,{levels:[_],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(M.ERROR,{type:Ye.NETWORK_ERROR,details:me.MANIFEST_PARSING_ERROR,fatal:t.type===bt.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let o=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===bt.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===bt.AUDIO_TRACK||e.type===bt.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=me.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case bt.MANIFEST:c=i?me.MANIFEST_LOAD_TIMEOUT:me.MANIFEST_LOAD_ERROR,d=!0;break;case bt.LEVEL:c=i?me.LEVEL_LOAD_TIMEOUT:me.LEVEL_LOAD_ERROR,d=!1;break;case bt.AUDIO_TRACK:c=i?me.AUDIO_TRACK_LOAD_TIMEOUT:me.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case bt.SUBTITLE_TRACK:c=i?me.SUBTITLE_TRACK_LOAD_TIMEOUT:me.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const g={type:Ye.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const m=t?.url||e.url;g.response=qt({url:m,data:void 0},n)}this.hls.trigger(M.ERROR,g)}handlePlaylistLoaded(e,t,i,n,r,o){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:g,groupId:m,deliveryDirectives:v}=n,_=Yy(t,n),b=w2(n);let E=typeof n.level=="number"&&b===qe.MAIN?d:void 0;const w=e.playlistParsingError;if(w){if(this.hls.logger.warn(`${w} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger(M.ERROR,{type:Ye.NETWORK_ERROR,details:me.LEVEL_PARSING_ERROR,fatal:!1,url:_,error:w,reason:w.message,response:t,context:n,level:E,parent:b,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const L=e.playlistParsingError=new Error("No Segments found in Playlist");u.trigger(M.ERROR,{type:Ye.NETWORK_ERROR,details:me.LEVEL_EMPTY_ERROR,fatal:!1,url:_,error:L,reason:L.message,response:t,context:n,level:E,parent:b,networkDetails:r,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case bt.MANIFEST:case bt.LEVEL:if(E){if(!f)E=0;else if(f!==u.levels[E]){const L=u.levels.indexOf(f);L>-1&&(E=L)}}u.trigger(M.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:E||0,id:g||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===bt.MANIFEST});break;case bt.AUDIO_TRACK:u.trigger(M.AUDIO_TRACK_LOADED,{details:e,track:f,id:g||0,groupId:m||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case bt.SUBTITLE_TRACK:u.trigger(M.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:g||0,groupId:m||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class Xn{static get version(){return Kd}static isMSESupported(){return RL()}static isSupported(){return K6()}static getMediaSource(){return So()}static get Events(){return M}static get MetadataSchema(){return gn}static get ErrorTypes(){return Ye}static get ErrorDetails(){return me}static get DefaultConfig(){return Xn.defaultConfig?Xn.defaultConfig:M6}static set DefaultConfig(e){Xn.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 e_,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=nF(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=B6(Xn.DefaultConfig,e,t);this.userConfig=e,i.progressive&&F6(i,t);const{abrController:n,bufferController:r,capLevelController:o,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),g=new JF(this),m=i.interstitialsController,v=m?this.interstitialsController=new m(this,Xn):null,_=this.bufferController=new r(this,g),b=this.capLevelController=new o(this),E=new c(this),w=new Z6(this),L=i.contentSteeringController,I=L?new L(this):null,F=this.levelController=new z6(this,I),B=new V6(this),V=new Q6(this.config,this.logger),N=this.streamController=new X6(this,g,V),q=this.gapController=new H6(this,g);b.setStreamController(N),E.setStreamController(N);const R=[w,F,N];v&&R.splice(1,0,v),I&&R.splice(1,0,I),this.networkControllers=R;const P=[f,_,q,b,E,B,g];this.audioTrackController=this.createController(i.audioTrackController,R);const z=i.audioStreamController;z&&R.push(this.audioStreamController=new z(this,g,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);const ee=i.subtitleStreamController;ee&&R.push(this.subtititleStreamController=new ee(this,g,V)),this.createController(i.timelineController,P),V.emeController=this.emeController=this.createController(i.emeController,P),this.cmcdController=this.createController(i.cmcdController,P),this.latencyController=this.createController(q6,P),this.coreComponents=P,R.push(d);const ie=d.onErrorOut;typeof ie=="function"&&this.on(M.ERROR,ie,d),this.on(M.MANIFEST_LOADED,w.onManifestLoaded,w)}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===M.ERROR;this.trigger(M.ERROR,{type:Ye.OTHER_ERROR,details:me.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(M.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(M.ERROR,{type:Ye.OTHER_ERROR,details:me.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(M.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(M.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(M.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=GT.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(M.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={[qe.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[qe.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[qe.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=H8()),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){BF(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let n=0;n=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const o=e[r].attrs["HDCP-LEVEL"];if(o&&o<=i)return r}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=yw(t);return gw(e,i,navigator.mediaCapabilities)}}Xn.defaultConfig=void 0;function J6({src:s,muted:e,className:t}){const i=Y.useRef(null),[n,r]=Y.useState(!1);return Y.useEffect(()=>{let o=!1,u=null;const c=i.current;if(!c)return;r(!1),c.muted=e;async function d(){const g=Date.now();for(;!o&&Date.now()-g<2e4;){try{const m=await fetch(s,{cache:"no-store"});if(m.status!==204){if(m.ok)return!0}}catch{}await new Promise(m=>setTimeout(m,400))}return!1}async function f(g){if(!await d()||o){o||r(!0);return}if(g.canPlayType("application/vnd.apple.mpegurl")){g.src=s,g.play().catch(()=>{});return}if(!Xn.isSupported()){r(!0);return}u=new Xn({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:4}),u.on(Xn.Events.ERROR,(v,_)=>{_.fatal&&r(!0)}),u.loadSource(s),u.attachMedia(g),u.on(Xn.Events.MANIFEST_PARSED,()=>{g.play().catch(()=>{})})}return f(c),()=>{o=!0,u?.destroy()}},[s,e]),n?U.jsx("div",{className:"text-xs text-gray-400 italic",children:"–"}):U.jsx("video",{ref:i,className:t,playsInline:!0,autoPlay:!0,muted:e,onClick:()=>{const o=i.current;o&&(o.muted=!1,o.play().catch(()=>{}))}})}function L2({jobId:s,thumbTick:e,autoTickMs:t=3e4}){const[i,n]=Y.useState(0),[r,o]=Y.useState(!1),u=Y.useRef(null),[c,d]=Y.useState(!1);Y.useEffect(()=>{if(typeof e=="number"||!c||document.hidden)return;const v=window.setInterval(()=>{n(_=>_+1)},t);return()=>window.clearInterval(v)},[e,t,c]),Y.useEffect(()=>{const v=u.current;if(!v)return;const _=new IntersectionObserver(b=>{const E=b[0];d(!!E?.isIntersecting)},{root:null,threshold:.1});return _.observe(v),()=>_.disconnect()},[]);const f=typeof e=="number"?e:i;Y.useEffect(()=>{o(!1)},[f]);const g=Y.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${f}`,[s,f]),m=Y.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&file=index_hq.m3u8`,[s]);return U.jsx(pA,{content:v=>v&&U.jsx("div",{className:"w-[420px]",children:U.jsx("div",{className:"aspect-video",children:U.jsx(J6,{src:m,muted:!1,className:"w-full h-full bg-black"})})}),children:U.jsx("div",{ref:u,className:"w-20 h-16 rounded bg-gray-100 dark:bg-white/5 overflow-hidden flex items-center justify-center",children:r?U.jsx("div",{className:"text-[10px] text-gray-500 dark:text-gray-400 px-1 text-center",children:"keine Vorschau"}):U.jsx("img",{src:g,loading:"lazy",alt:"",className:"w-full h-full object-cover",onError:()=>o(!0),onLoad:()=>o(!1)})})})}function e$({models:s}){const e=Y.useMemo(()=>[{key:"model",header:"Model",cell:t=>U.jsx("span",{className:"truncate font-medium text-gray-900 dark:text-white",title:t.modelKey,children:t.modelKey})},{key:"status",header:"Status",cell:t=>U.jsx("span",{className:"font-medium",children:t.currentShow||"unknown"})},{key:"open",header:"Öffnen",srOnlyHeader:!0,align:"right",cell:t=>U.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline",onClick:i=>i.stopPropagation(),children:"Öffnen"})}],[]);return s.length===0?null:U.jsxs(U.Fragment,{children:[U.jsx("div",{className:"sm:hidden space-y-2",children:s.map(t=>U.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md bg-white/60 dark:bg-white/5 px-3 py-2",children:[U.jsxs("div",{className:"min-w-0",children:[U.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:t.modelKey}),U.jsxs("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:["Status: ",U.jsx("span",{className:"font-medium",children:t.currentShow||"unknown"})]})]}),U.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-xs text-indigo-600 dark:text-indigo-400 hover:underline",children:"Öffnen"})]},t.id))}),U.jsx("div",{className:"hidden sm:block",children:U.jsx(dg,{rows:s,columns:e,getRowKey:t=>t.id,striped:!0,fullWidth:!0})})]})}const Zv=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",I2=s=>{const e=Zv(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},t$=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`},R2=s=>{const e=Date.parse(String(s.startedAt||""));if(!Number.isFinite(e))return"—";const t=s.endedAt?Date.parse(String(s.endedAt)):Date.now();return Number.isFinite(t)?t$(t-e):"—"};function i$({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i}){const n=Y.useMemo(()=>[{key:"preview",header:"Vorschau",cell:r=>U.jsx(L2,{jobId:r.id})},{key:"model",header:"Modelname",cell:r=>{const o=I2(r.output);return U.jsx("span",{className:"truncate",title:o,children:o})}},{key:"sourceUrl",header:"Source",cell:r=>U.jsx("a",{href:r.sourceUrl,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline",onClick:o=>o.stopPropagation(),children:r.sourceUrl})},{key:"output",header:"Datei",cell:r=>Zv(r.output||"")},{key:"status",header:"Status"},{key:"runtime",header:"Dauer",cell:r=>R2(r)},{key:"actions",header:"Aktion",srOnlyHeader:!0,align:"right",cell:r=>U.jsx(ci,{size:"md",variant:"primary",onClick:o=>{o.stopPropagation(),i(r.id)},children:"Stop"})}],[i]);return s.length===0&&e.length===0?U.jsx(In,{grayBody:!0,children:U.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Downloads."})}):U.jsxs(U.Fragment,{children:[e.length>0&&U.jsx(In,{grayBody:!0,header:U.jsxs("div",{className:"flex items-center justify-between gap-3",children:[U.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Online (wartend – Download startet nur bei ",U.jsx("span",{className:"font-semibold",children:"public"}),")"]}),U.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:e.length})]}),children:U.jsx(e$,{models:e})}),s.length===0&&e.length>0&&U.jsx(In,{grayBody:!0,children:U.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Kein aktiver Download – wartet auf public."})}),s.length>0&&U.jsxs(U.Fragment,{children:[U.jsx("div",{className:"sm:hidden space-y-3",children:s.map(r=>{const o=I2(r.output),u=Zv(r.output||""),c=R2(r);return U.jsx("div",{role:"button",tabIndex:0,className:"cursor-pointer",onClick:()=>t(r),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&t(r)},children:U.jsx(In,{header:U.jsxs("div",{className:"flex items-start justify-between gap-3",children:[U.jsxs("div",{className:"min-w-0",children:[U.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:o}),U.jsx("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:u||"—"})]}),U.jsx(ci,{size:"sm",variant:"primary",onClick:d=>{d.stopPropagation(),i(r.id)},children:"Stop"})]}),children:U.jsxs("div",{className:"flex gap-3",children:[U.jsx("div",{className:"shrink-0",onClick:d=>d.stopPropagation(),children:U.jsx(L2,{jobId:r.id})}),U.jsxs("div",{className:"min-w-0 flex-1",children:[U.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Status: ",U.jsx("span",{className:"font-medium",children:r.status}),U.jsx("span",{className:"mx-2 opacity-60",children:"•"}),"Dauer: ",U.jsx("span",{className:"font-medium",children:c})]}),r.sourceUrl?U.jsx("a",{href:r.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 dark:text-indigo-400 hover:underline",onClick:d=>d.stopPropagation(),children:r.sourceUrl}):null]})]})})},r.id)})}),U.jsx("div",{className:"hidden sm:block",children:U.jsx(dg,{rows:s,columns:n,getRowKey:r=>r.id,striped:!0,fullWidth:!0,onRowClick:t})})]})]})}function s$({open:s,onClose:e,title:t,children:i,footer:n,icon:r}){return U.jsx(op,{show:s,as:Y.Fragment,children:U.jsxs(ku,{as:"div",className:"relative z-50",onClose:e,children:[U.jsx(op.Child,{as:Y.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:U.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),U.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center px-4 py-6 sm:p-0",children:U.jsx(op.Child,{as:Y.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:U.jsxs(ku.Panel,{className:"relative w-full max-w-lg transform overflow-hidden rounded-lg bg-white p-6 text-left shadow-xl transition-all dark:bg-gray-800 dark:outline dark:-outline-offset-1 dark:outline-white/10",children:[r&&U.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-500/10",children:r}),t&&U.jsx(ku.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:t}),U.jsx("div",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:i}),n&&U.jsx("div",{className:"mt-6 flex justify-end gap-3",children:n})]})})})]})})}function k2(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 n$(s,e,t,i){if(s<=1)return[1];const n=1,r=s,o=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(...o),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const g=new Set;return f.filter(m=>{const v=String(m);return g.has(v)?!1:(g.add(v),!0)})}function r$({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const o=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return U.jsx("button",{type:"button",disabled:e,onClick:e?void 0:i,title:r,className:kt("relative inline-flex items-center px-4 py-2 text-sm font-semibold focus:z-20 focus:outline-offset-0",o,e?"opacity-50 cursor-not-allowed":"cursor-pointer",s?"z-10 bg-indigo-600 text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:focus-visible:outline-indigo-500":"text-gray-900 inset-ring inset-ring-gray-300 hover:bg-gray-50 dark:text-gray-200 dark:inset-ring-gray-700 dark:hover:bg-white/5"),"aria-current":s?"page":void 0,children:n})}function a$({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:o=!0,className:u,ariaLabel:c="Pagination",prevLabel:d="Previous",nextLabel:f="Next"}){const g=Math.max(1,Math.ceil((t||0)/Math.max(1,e||1))),m=k2(s||1,1,g);if(g<=1)return null;const v=t===0?0:(m-1)*e+1,_=Math.min(m*e,t),b=n$(g,m,r,n),E=w=>i(k2(w,1,g));return U.jsxs("div",{className:kt("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:[U.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[U.jsx("button",{type:"button",onClick:()=>E(m-1),disabled:m<=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}),U.jsx("button",{type:"button",onClick:()=>E(m+1),disabled:m>=g,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})]}),U.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[U.jsx("div",{children:o?U.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",U.jsx("span",{className:"font-medium",children:v})," to"," ",U.jsx("span",{className:"font-medium",children:_})," of"," ",U.jsx("span",{className:"font-medium",children:t})," results"]}):null}),U.jsx("div",{children:U.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[U.jsxs("button",{type:"button",onClick:()=>E(m-1),disabled:m<=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:[U.jsx("span",{className:"sr-only",children:d}),U.jsx(SO,{"aria-hidden":"true",className:"size-5"})]}),b.map((w,L)=>w==="ellipsis"?U.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-${L}`):U.jsx(r$,{active:w===m,onClick:()=>E(w),rounded:"none",children:w},w)),U.jsxs("button",{type:"button",onClick:()=>E(m+1),disabled:m>=g,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:[U.jsx("span",{className:"sr-only",children:f}),U.jsx(EO,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}async function np(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 O2=(s,e)=>U.jsx("span",{className:kt("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 o$(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 l$(s){if(!s)return[];const e=s.split(",").map(i=>i.trim()).filter(Boolean),t=Array.from(new Set(e));return t.sort((i,n)=>i.localeCompare(n,void 0,{sensitivity:"base"})),t}function P2({children:s,title:e}){return U.jsx("span",{title:e,className:"inline-flex max-w-[11rem] items-center truncate rounded-md bg-sky-50 px-2 py-0.5 text-xs text-sky-700 dark:bg-sky-500/10 dark:text-sky-200",children:s})}function M2({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return U.jsx("span",{className:kt(t&&!e?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:U.jsx(ci,{variant:e?"soft":"secondary",size:"xs",className:kt("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:U.jsx("span",{className:"text-base leading-none",children:n})})})}function u$(){const[s,e]=Y.useState([]),[t,i]=Y.useState(!1),[n,r]=Y.useState(null),[o,u]=Y.useState(""),[c,d]=Y.useState(1),f=10,[g,m]=Y.useState(""),[v,_]=Y.useState(null),[b,E]=Y.useState(null),[w,L]=Y.useState(!1),[I,F]=Y.useState(!1),[B,V]=Y.useState(null),[N,q]=Y.useState(null),[R,P]=Y.useState("favorite"),[z,ee]=Y.useState(!1),[ie,Q]=Y.useState(null);async function oe(){if(B){ee(!0),q(null),r(null);try{const Ae=new FormData;Ae.append("file",B),Ae.append("kind",R);const Be=await fetch("/api/models/import",{method:"POST",body:Ae});if(!Be.ok)throw new Error(await Be.text());const $e=await Be.json();q(`✅ Import: ${$e.inserted} neu, ${$e.updated} aktualisiert, ${$e.skipped} übersprungen`),F(!1),V(null),await X()}catch(Ae){Q(Ae?.message??String(Ae))}finally{ee(!1)}}}const H=()=>{Q(null),q(null),V(null),P("favorite"),F(!0)},X=Y.useCallback(async()=>{i(!0),r(null);try{const Ae=await np("/api/models/list");e(Array.isArray(Ae)?Ae:[])}catch(Ae){r(Ae?.message??String(Ae))}finally{i(!1)}},[]);Y.useEffect(()=>{X()},[X]),Y.useEffect(()=>{const Ae=()=>{X()};return window.addEventListener("models-changed",Ae),()=>window.removeEventListener("models-changed",Ae)},[X]),Y.useEffect(()=>{const Ae=g.trim();if(!Ae){_(null),E(null);return}const Be=o$(Ae);if(!Be){_(null),E("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const $e=window.setTimeout(async()=>{try{const Je=await np("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Be})});if(!Je?.isUrl){_(null),E("Bitte nur URLs einfügen (keine Modelnamen).");return}_(Je),E(null)}catch(Je){_(null),E(Je?.message??String(Je))}},300);return()=>window.clearTimeout($e)},[g]);const te=Y.useMemo(()=>s.map(Ae=>({m:Ae,hay:`${Ae.modelKey} ${Ae.host??""} ${Ae.input??""} ${Ae.tags??""}`.toLowerCase()})),[s]),ae=Y.useDeferredValue(o),ce=Y.useMemo(()=>{const Ae=ae.trim().toLowerCase();return Ae?te.filter(Be=>Be.hay.includes(Ae)).map(Be=>Be.m):s},[s,te,ae]);Y.useEffect(()=>{d(1)},[o]);const $=ce.length,se=Y.useMemo(()=>Math.max(1,Math.ceil($/f)),[$,f]);Y.useEffect(()=>{c>se&&d(se)},[c,se]);const he=Y.useMemo(()=>{const Ae=(c-1)*f;return ce.slice(Ae,Ae+f)},[ce,c,f]),Se=async()=>{if(v){if(!v.isUrl){E("Bitte nur URLs einfügen (keine Modelnamen).");return}L(!0),r(null);try{const Ae=await np("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});e(Be=>{const $e=Be.filter(Je=>Je.id!==Ae.id);return[Ae,...$e]}),m(""),_(null)}catch(Ae){r(Ae?.message??String(Ae))}finally{L(!1)}}},be=async(Ae,Be)=>{r(null);try{const $e=await np("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:Ae,...Be})});e(Je=>{const ht=Je.findIndex(Ni=>Ni.id===$e.id);if(ht===-1)return Je;const Tt=Je.slice();return Tt[ht]=$e,Tt})}catch($e){r($e?.message??String($e))}},Pe=Y.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:Ae=>{const Be=Ae.liked===!0,$e=Ae.favorite===!0,Je=Ae.watching===!0,ht=!Je&&!$e&&!Be;return U.jsxs("div",{className:"group flex items-center justify-center gap-1",children:[U.jsx("span",{className:kt(ht&&!Je?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:U.jsx(ci,{variant:Je?"soft":"secondary",size:"xs",className:kt("px-2 py-1 leading-none",!Je&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:Je?"Nicht mehr beobachten":"Beobachten",onClick:Tt=>{Tt.stopPropagation(),be(Ae.id,{watching:!Je})},children:U.jsx("span",{className:kt("text-base leading-none",Je?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),U.jsx(M2,{title:$e?"Favorit entfernen":"Als Favorit markieren",active:$e,hiddenUntilHover:ht,onClick:Tt=>{Tt.stopPropagation(),$e?be(Ae.id,{favorite:!1}):be(Ae.id,{favorite:!0,clearLiked:!0})},icon:U.jsx("span",{className:$e?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),U.jsx(M2,{title:Be?"Gefällt mir entfernen":"Gefällt mir",active:Be,hiddenUntilHover:ht,onClick:Tt=>{Tt.stopPropagation(),Be?be(Ae.id,{clearLiked:!0}):be(Ae.id,{liked:!0,favorite:!1})},icon:U.jsx("span",{className:Be?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",cell:Ae=>U.jsxs("div",{className:"min-w-0",children:[U.jsx("div",{className:"font-medium truncate",children:Ae.modelKey}),U.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:Ae.host??"—"})]})},{key:"url",header:"URL",cell:Ae=>U.jsx("a",{href:Ae.input,target:"_blank",rel:"noreferrer",className:"text-indigo-600 dark:text-indigo-400 hover:underline truncate block max-w-[520px]",onClick:Be=>Be.stopPropagation(),title:Ae.input,children:Ae.input})},{key:"tags",header:"Tags",cell:Ae=>{const Be=l$(Ae.tags),$e=Be.slice(0,6),Je=Be.length-$e.length,ht=Be.join(", ");return U.jsxs("div",{className:"flex flex-wrap gap-2",title:ht||void 0,children:[Ae.hot?O2(!0,"🔥 HOT"):null,Ae.keep?O2(!0,"📌 Behalten"):null,$e.map(Tt=>U.jsx(P2,{title:Tt,children:Tt},Tt)),Je>0?U.jsxs(P2,{title:ht,children:["+",Je]}):null,!Ae.hot&&!Ae.keep&&Be.length===0?U.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}}],[]);return U.jsxs("div",{className:"space-y-4",children:[U.jsx(In,{header:U.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:U.jsxs("div",{className:"grid gap-2",children:[U.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[U.jsx("input",{value:g,onChange:Ae=>m(Ae.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"}),U.jsx(ci,{className:"px-3 py-2 text-sm",onClick:Se,disabled:!v||w,title:v?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),U.jsx(ci,{className:"px-3 py-2 text-sm",onClick:X,disabled:t,children:"Aktualisieren"})]}),b?U.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:b}):v?U.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",U.jsx("span",{className:"font-medium",children:v.modelKey}),v.host?U.jsxs("span",{className:"opacity-70",children:[" • ",v.host]}):null]}):null,n?U.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null]})}),U.jsxs(In,{header:U.jsxs("div",{className:"flex items-center justify-between gap-2",children:[U.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models (",ce.length,")"]}),U.jsxs("div",{className:"flex items-center gap-2",children:[U.jsx(ci,{variant:"secondary",size:"sm",onClick:H,children:"Importieren"}),U.jsx("input",{value:o,onChange:Ae=>u(Ae.target.value),placeholder:"Suchen…",className:"w-[220px] rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"})]})]}),noBodyPadding:!0,children:[U.jsx(dg,{rows:he,columns:Pe,getRowKey:Ae=>Ae.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,onRowClick:Ae=>Ae.input&&window.open(Ae.input,"_blank","noreferrer")}),U.jsx(a$,{page:c,pageSize:f,totalItems:$,onPageChange:d})]}),U.jsx(s$,{open:I,onClose:()=>!z&&F(!1),title:"Models importieren",footer:U.jsxs(U.Fragment,{children:[U.jsx(ci,{variant:"secondary",onClick:()=>F(!1),disabled:z,children:"Abbrechen"}),U.jsx(ci,{variant:"primary",onClick:oe,isLoading:z,disabled:!B||z,children:"Import starten"})]}),children:U.jsxs("div",{className:"space-y-3",children:[U.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),U.jsxs("div",{className:"space-y-2",children:[U.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),U.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[U.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[U.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:R==="favorite",onChange:()=>P("favorite"),disabled:z}),"Favoriten (★)"]}),U.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[U.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:R==="liked",onChange:()=>P("liked"),disabled:z}),"Gefällt mir (♥)"]})]})]}),U.jsx("input",{type:"file",accept:".csv,text/csv",onChange:Ae=>{const Be=Ae.target.files?.[0]??null;Q(null),V(Be)},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"}),B?U.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",U.jsx("span",{className:"font-medium",children:B.name})]}):null,ie?U.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:ie}):null,N?U.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:N}):null]})})]})}const Xy="record_cookies";function rp(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 es(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 c$={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!1,autoStartAddedDownloads:!1,useChaturbateApi:!1},ap=s=>new Promise(e=>window.setTimeout(e,s));function N2(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g))if(/^https?:\/\//i.test(t))try{return new URL(t).toString()}catch{}return null}const lo=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function Qy(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function d$(s){return s.startsWith("HOT ")?s.slice(4):s}const h$=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function f$(s){const t=d$(lo(s)).replace(/\.[^.]+$/,""),i=t.match(h$);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function p$(){const[s,e]=Y.useState(""),[,t]=Y.useState(null),[,i]=Y.useState(null),[n,r]=Y.useState([]),[o,u]=Y.useState([]),[c,d]=Y.useState(0),[f,g]=Y.useState(null),m=Y.useRef(null),v=Y.useRef([]),[,_]=Y.useState(null),[b,E]=Y.useState(!1),[w,L]=Y.useState(!1),[I,F]=Y.useState({}),[B,V]=Y.useState(!1),[N,q]=Y.useState("running"),[R,P]=Y.useState(null),[z,ee]=Y.useState(!1),[ie,Q]=Y.useState(c$),[oe,H]=Y.useState([]),X=Y.useRef([]),te=Y.useRef(new Set),ae=Y.useRef(!1),ce=!!ie.autoAddToDownloadList,$=!!ie.autoStartAddedDownloads,se=Y.useRef(!1),he=Y.useRef({}),Se=Y.useRef([]);Y.useEffect(()=>{se.current=b},[b]),Y.useEffect(()=>{he.current=I},[I]),Y.useEffect(()=>{Se.current=n},[n]);const be=Y.useRef(null),Pe=Y.useRef("");Y.useEffect(()=>{let Oe=!1;const Fe=async()=>{try{const rt=await es("/api/settings",{cache:"no-store"});!Oe&&rt&&Q(pt=>({...pt,...rt}))}catch{}},je=()=>{Fe()},Qe=()=>{Fe()};return window.addEventListener("recorder-settings-updated",je),window.addEventListener("focus",Qe),document.addEventListener("visibilitychange",Qe),Fe(),()=>{Oe=!0,window.removeEventListener("recorder-settings-updated",je),window.removeEventListener("focus",Qe),document.removeEventListener("visibilitychange",Qe)}},[]),Y.useEffect(()=>{let Oe=!1;const Fe=async()=>{try{const Qe=await es("/api/models/meta",{cache:"no-store"}),rt=Number(Qe?.count??0);!Oe&&Number.isFinite(rt)&&d(rt)}catch{}};Fe();const je=window.setInterval(Fe,document.hidden?6e4:3e4);return()=>{Oe=!0,window.clearInterval(je)}},[]),Y.useEffect(()=>{if(!ie.useChaturbateApi){v.current=[];return}let Oe=!1,Fe=!1;const je=async()=>{if(!(Oe||Fe)){Fe=!0;try{const rt=await es("/api/models/watched?host=chaturbate.com",{cache:"no-store"});if(Oe)return;v.current=Array.isArray(rt)?rt:[]}catch{Oe||(v.current=[])}finally{Fe=!1}}};je();const Qe=window.setInterval(je,document.hidden?3e4:1e4);return()=>{Oe=!0,window.clearInterval(Qe)}},[ie.useChaturbateApi]);const Ae=Y.useMemo(()=>Object.entries(I).map(([Oe,Fe])=>({name:Oe,value:Fe})),[I]),Be=Oe=>{P(Oe),ee(!1)},$e=n.filter(Oe=>Oe.status==="running"),Je=[{id:"running",label:"Laufende Downloads",count:$e.length+oe.length},{id:"finished",label:"Abgeschlossene Downloads",count:o.length},{id:"models",label:"Models",count:c},{id:"settings",label:"Einstellungen"}],ht=Y.useMemo(()=>s.trim().length>0&&!b,[s,b]);Y.useEffect(()=>{let Oe=!1;return(async()=>{try{const je=await es("/api/cookies",{cache:"no-store"}),Qe=rp(je?.cookies);if(Oe||F(Qe),Object.keys(Qe).length===0){const rt=localStorage.getItem(Xy);if(rt)try{const pt=JSON.parse(rt),et=rp(pt);Object.keys(et).length>0&&(Oe||F(et),await es("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:et})}))}catch{}}}catch{const je=localStorage.getItem(Xy);if(je)try{const Qe=JSON.parse(je);Oe||F(rp(Qe))}catch{}}finally{Oe||V(!0)}})(),()=>{Oe=!0}},[]),Y.useEffect(()=>{B&&localStorage.setItem(Xy,JSON.stringify(I))},[I,B]),Y.useEffect(()=>{if(s.trim()===""){t(null),i(null);return}const Oe=setTimeout(async()=>{try{const Fe=await es("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:s.trim()})});t(Fe),i(null)}catch(Fe){t(null),i(Fe?.message??String(Fe))}},300);return()=>clearTimeout(Oe)},[s]),Y.useEffect(()=>{let Oe=!1;const Fe=async()=>{try{const Qe=await es("/api/record/list");Oe||r(Array.isArray(Qe)?Qe:[])}catch{}};Fe();const je=setInterval(Fe,1e3);return()=>{Oe=!0,clearInterval(je)}},[]),Y.useEffect(()=>{const Oe=async()=>{try{const je=await es("/api/record/done");u(Array.isArray(je)?je:[])}catch{u([])}};Oe();const Fe=setInterval(Oe,5e3);return()=>clearInterval(Fe)},[]);function Tt(Oe){try{return new URL(Oe).hostname.includes("chaturbate.com")}catch{return!1}}function Ni(Oe,Fe){const je=Object.fromEntries(Object.entries(Oe).map(([Qe,rt])=>[Qe.trim().toLowerCase(),rt]));for(const Qe of Fe){const rt=je[Qe.toLowerCase()];if(rt)return rt}}function It(Oe){const Fe=Ni(Oe,["cf_clearance"]),je=Ni(Oe,["sessionid","session_id","sessionid","sessionId"]);return!!(Fe&&je)}const Li=Y.useCallback(async(Oe,Fe)=>{const je=Oe.trim();if(!je||se.current)return!1;const Qe=!!Fe?.silent;Qe||_(null);const rt=he.current;if(Tt(je)&&!It(rt))return Qe||_('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(Se.current.some(et=>et.status==="running"&&String(et.sourceUrl||"")===je))return!0;E(!0),se.current=!0;try{const et=Object.entries(rt).map(([Ft,ti])=>`${Ft}=${ti}`).join("; "),ei=await es("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:je,cookie:et})});return r(Ft=>[ei,...Ft]),Se.current=[ei,...Se.current],!0}catch(et){return Qe||_(et?.message??String(et)),!1}finally{E(!1),se.current=!1}},[]);async function We(Oe){const Fe=Oe.sourceUrl??Oe.SourceURL??"",je=N2(Fe);if(je){const ti=await es("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:je})});return await es("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ti)})}const Qe=f$(Oe.output||"");if(!Qe)return null;const rt=Date.now(),pt=m.current;if(!pt||rt-pt.ts>3e4){const ti=await es("/api/models/list",{cache:"no-store"});m.current={ts:rt,list:Array.isArray(ti)?ti:[]}}const et=m.current?.list??[],ei=Qe.toLowerCase(),Ft=et.filter(ti=>(ti.modelKey||"").toLowerCase()===ei);return Ft.length===0?null:Ft.sort((ti,vi)=>+!!vi.favorite-+!!ti.favorite)[0]}Y.useEffect(()=>{let Oe=!1;if(!R){g(null);return}return(async()=>{try{const Fe=await We(R);Oe||g(Fe)}catch{Oe||g(null)}})(),()=>{Oe=!0}},[R]);async function Jt(){return Li(s)}const Bt=Y.useCallback(async Oe=>{if(Oe.status==="running"){await xs(Oe.id),P(null);return}const Fe=lo(Oe.output||"");Fe&&(await es(`/api/record/delete?file=${encodeURIComponent(Fe)}`,{method:"POST"}),u(je=>je.filter(Qe=>lo(Qe.output||"")!==Fe)),r(je=>je.filter(Qe=>lo(Qe.output||"")!==Fe)),P(null))},[]),oi=Y.useCallback(async Oe=>{const Fe=lo(Oe.output||"");if(!Fe)return;const je=await es(`/api/record/toggle-hot?file=${encodeURIComponent(Fe)}`,{method:"POST"}),Qe=Qy(Oe.output||"",je.newFile);P(rt=>rt&&{...rt,output:Qe}),u(rt=>rt.map(pt=>lo(pt.output||"")===Fe?{...pt,output:Qy(pt.output||"",je.newFile)}:pt)),r(rt=>rt.map(pt=>lo(pt.output||"")===Fe?{...pt,output:Qy(pt.output||"",je.newFile)}:pt))},[]);async function Xe(Oe){return es("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Oe)})}const _t=Y.useCallback(async Oe=>{let Fe=f;if(Fe||(Fe=await We(Oe),g(Fe)),!Fe)return;const je=!Fe.favorite,Qe=await Xe({id:Fe.id,favorite:je});g(Qe),window.dispatchEvent(new Event("models-changed"))},[f]),Ct=Y.useCallback(async Oe=>{let Fe=f;if(Fe||(Fe=await We(Oe),g(Fe)),!Fe)return;const je=Fe.liked!==!0,Qe=await Xe({id:Fe.id,liked:je});g(Qe),window.dispatchEvent(new Event("models-changed"))},[f]),Gi=Oe=>(Oe||"").trim().toLowerCase(),$t=Oe=>{try{const Fe=new URL(Oe);if(!Fe.hostname.toLowerCase().includes("chaturbate.com"))return null;const je=Fe.pathname.split("/").filter(Boolean);return je[0]?Gi(je[0]):null}catch{return null}};Y.useEffect(()=>{if(!ie.useChaturbateApi){H([]),X.current=[],te.current=new Set;return}let Oe=!1,Fe=!1;const je=async()=>{if(!(Oe||Fe)){Fe=!0;try{const rt=It(he.current),pt=v.current,et=await es("/api/chaturbate/online",{cache:"no-store"});if(!et?.enabled)return;const ei=new Map;for(const Rt of et.rooms??[])ei.set(Gi(Rt.username),String(Rt.current_show||"unknown").toLowerCase());const Ft=new Set(Se.current.filter(Rt=>Rt.status==="running").map(Rt=>$t(String(Rt.sourceUrl||""))).filter(Boolean)),ti=(pt??[]).filter(Rt=>!!Rt?.watching&&(String(Rt?.host||"").toLowerCase().includes("chaturbate.com")||Tt(String(Rt?.input||"")))),vi=new Set(ti.map(Rt=>Gi(Rt.modelKey)).filter(Boolean));{const Rt=[];for(const xi of X.current)vi.has(xi.userKey)&&ei.has(xi.userKey)&&(Ft.has(xi.userKey)||Rt.push(xi));X.current=Rt,te.current=new Set(Rt.map(xi=>xi.userKey))}const Fn=new Map;for(const Rt of ti){const xi=Gi(Rt.modelKey);if(!xi)continue;const Os=ei.get(xi);if(!Os||Ft.has(xi))continue;const Tn=/^https?:\/\//i.test(Rt.input||"")?String(Rt.input).trim():`https://chaturbate.com/${Rt.modelKey}/`;Fn.has(xi)||Fn.set(xi,{id:Rt.id,modelKey:Rt.modelKey,url:Tn,currentShow:Os}),Os==="public"&&rt&&!te.current.has(xi)&&(X.current.push({userKey:xi,url:Tn}),te.current.add(xi))}Oe||H([...Fn.values()])}catch{}finally{Fe=!1}}};je();const Qe=window.setInterval(je,document.hidden?15e3:5e3);return()=>{Oe=!0,window.clearInterval(Qe)}},[ie.useChaturbateApi]),Y.useEffect(()=>{if(!ie.useChaturbateApi)return;let Oe=!1;return(async()=>{if(!ae.current){ae.current=!0;try{for(;!Oe;){if(se.current){await ap(500);continue}const je=X.current.shift();if(!je){await ap(1e3);continue}te.current.delete(je.userKey);const Qe=await Li(je.url,{silent:!0});Qe&&H(rt=>rt.filter(pt=>Gi(pt.modelKey)!==je.userKey)),Qe?await ap(5e3):await ap(5e3)}}finally{ae.current=!1}}})(),()=>{Oe=!0}},[ie.useChaturbateApi,Li]),Y.useEffect(()=>{if(!ce&&!$||!navigator.clipboard?.readText)return;let Oe=!1,Fe=!1,je=null;const Qe=async()=>{if(!(Oe||Fe)){Fe=!0;try{const et=await navigator.clipboard.readText(),ei=N2(et);if(!ei||ei===Pe.current)return;Pe.current=ei,ce&&e(ei),$&&(se.current?be.current=ei:(be.current=null,await Li(ei)))}catch{}finally{Fe=!1}}},rt=et=>{Oe||(je=window.setTimeout(async()=>{await Qe(),rt(document.hidden?5e3:1500)},et))},pt=()=>{Qe()};return window.addEventListener("focus",pt),document.addEventListener("visibilitychange",pt),rt(0),()=>{Oe=!0,je&&window.clearTimeout(je),window.removeEventListener("focus",pt),document.removeEventListener("visibilitychange",pt)}},[ce,$,Li]),Y.useEffect(()=>{if(b||!$)return;const Oe=be.current;Oe&&(be.current=null,Li(Oe))},[b,$,Li]);async function xs(Oe){try{await es(`/api/record/stop?id=${encodeURIComponent(Oe)}`,{method:"POST"})}catch{}}return U.jsxs("div",{className:"mx-auto py-4 max-w-7xl sm:px-6 lg:px-8 space-y-6",children:[U.jsxs(In,{header:U.jsxs("div",{className:"flex items-start justify-between gap-4",children:[U.jsx("h2",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Recorder"}),U.jsxs("div",{className:"flex gap-2",children:[U.jsx(ci,{variant:"secondary",onClick:()=>L(!0),children:"Cookies"}),U.jsx(ci,{variant:"primary",onClick:Jt,disabled:!ht,children:"Start"})]})]}),children:[U.jsx("label",{className:"block text-sm font-medium text-gray-900 dark:text-gray-200",children:"Source URL"}),U.jsx("input",{value:s,onChange:Oe=>e(Oe.target.value),placeholder:"https://…",className:"mt-1 block w-full rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white"}),Tt(s)&&!It(I)&&U.jsxs("div",{className:"mt-2 text-xs text-amber-600 dark:text-amber-400",children:["⚠️ Für Chaturbate werden die Cookies ",U.jsx("code",{children:"cf_clearance"})," und"," ",U.jsx("code",{children:"sessionId"})," benötigt."]})]}),U.jsx(yO,{tabs:Je,value:N,onChange:q,ariaLabel:"Tabs",variant:"pillsBrand"}),N==="running"&&U.jsx(i$,{jobs:$e,pending:oe,onOpenPlayer:Be,onStopJob:xs}),N==="finished"&&U.jsx(LO,{jobs:n,doneJobs:o,onOpenPlayer:Be}),N==="models"&&U.jsx(u$,{}),N==="settings"&&U.jsx(vO,{}),U.jsx(pO,{open:w,onClose:()=>L(!1),initialCookies:Ae,onApply:Oe=>{const Fe=rp(Object.fromEntries(Oe.map(je=>[je.name,je.value])));F(Fe),es("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:Fe})}).catch(()=>{})}}),R&&U.jsx(WB,{job:R,expanded:z,onToggleExpand:()=>ee(Oe=>!Oe),onClose:()=>P(null),isHot:lo(R.output||"").startsWith("HOT "),isFavorite:!!f?.favorite,isLiked:f?.liked===!0,onDelete:Bt,onToggleHot:oi,onToggleFavorite:_t,onToggleLike:Ct})]})}tR.createRoot(document.getElementById("root")).render(U.jsx(Y.StrictMode,{children:U.jsx(p$,{})})); diff --git a/backend/web/dist/index.html b/backend/web/dist/index.html new file mode 100644 index 0000000..7205e15 --- /dev/null +++ b/backend/web/dist/index.html @@ -0,0 +1,14 @@ + + + + + + + frontend + + + + +
+ + diff --git a/backend/web/dist/vite.svg b/backend/web/dist/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/backend/web/dist/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f2ee76e..bd541bc 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,11 +1,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import './App.css' import Button from './components/ui/Button' -import Table, { type Column } from './components/ui/Table' import CookieModal from './components/ui/CookieModal' import Card from './components/ui/Card' import Tabs, { type TabItem } from './components/ui/Tabs' -import ModelPreview from './components/ui/ModelPreview' import RecorderSettings from './components/ui/RecorderSettings' import FinishedDownloads from './components/ui/FinishedDownloads' import Player from './components/ui/Player' @@ -15,6 +13,15 @@ import ModelsTab from './components/ui/ModelsTab' const COOKIE_STORAGE_KEY = 'record_cookies' +function normalizeCookies(obj: Record | null | undefined): Record { + const input = obj ?? {} + return Object.fromEntries( + Object.entries(input) + .map(([k, v]) => [k.trim().toLowerCase(), String(v ?? '').trim()] as const) + .filter(([k, v]) => k.length > 0 && v.length > 0) + ) +} + async function apiJSON(url: string, init?: RequestInit): Promise { const res = await fetch(url, init) if (!res.ok) { @@ -24,52 +31,13 @@ async function apiJSON(url: string, init?: RequestInit): Promise { return res.json() as Promise } -const baseName = (p: string) => { - const n = (p || '').replaceAll('\\', '/').trim() - const parts = n.split('/') - return parts[parts.length - 1] || '' -} - -const modelNameFromOutput = (output?: string) => { - const file = baseName(output || '') - if (!file) return '—' - const stem = file.replace(/\.[^.]+$/, '') - - // _MM_DD_YYYY__HH-MM-SS - const m = stem.match(/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}$/) - if (m?.[1]) return m[1] - - // fallback: alles bis zum letzten '_' nehmen - const i = stem.lastIndexOf('_') - return i > 0 ? stem.slice(0, i) : stem -} - - -const formatDuration = (ms: number): string => { - if (!Number.isFinite(ms) || ms <= 0) return '—' - const total = Math.floor(ms / 1000) - const h = Math.floor(total / 3600) - const m = Math.floor((total % 3600) / 60) - const s = total % 60 - if (h > 0) return `${h}h ${m}m` - if (m > 0) return `${m}m ${s}s` - return `${s}s` -} - -const runtimeOf = (j: RecordJob) => { - const start = Date.parse(String(j.startedAt || '')) - if (!Number.isFinite(start)) return '—' - const end = j.endedAt ? Date.parse(String(j.endedAt)) : Date.now() // running -> jetzt - if (!Number.isFinite(end)) return '—' - return formatDuration(end - start) -} - type RecorderSettings = { recordDir: string doneDir: string ffmpegPath?: string autoAddToDownloadList?: boolean autoStartAddedDownloads?: boolean + useChaturbateApi?: boolean } const DEFAULT_RECORDER_SETTINGS: RecorderSettings = { @@ -78,8 +46,42 @@ const DEFAULT_RECORDER_SETTINGS: RecorderSettings = { ffmpegPath: '', autoAddToDownloadList: false, autoStartAddedDownloads: false, + useChaturbateApi: false, } +type StoredModel = { + id: string + input: string + host?: string + modelKey: string + watching: boolean + favorite?: boolean + liked?: boolean | null +} + + +type ChaturbateRoom = { + username: string + current_show?: 'public' | 'private' | 'hidden' | 'away' | string +} + +type ChaturbateOnlineResponse = { + enabled: boolean + fetchedAt?: string + lastError?: string + count?: number + rooms: ChaturbateRoom[] +} + +type PendingWatchedRoom = { + id: string + modelKey: string + url: string + currentShow: string +} + +const sleep = (ms: number) => new Promise((r) => window.setTimeout(r, ms)) + function extractFirstHttpUrl(text: string): string | null { const t = (text ?? '').trim() if (!t) return null @@ -94,13 +96,48 @@ function extractFirstHttpUrl(text: string): string | null { return null } +const baseName = (p: string) => (p || '').replaceAll('\\', '/').split('/').pop() || '' + +function replaceBasename(fullPath: string, newBase: string) { + const norm = (fullPath || '').replaceAll('\\', '/') + const parts = norm.split('/') + parts[parts.length - 1] = newBase + return parts.join('/') +} + +function stripHotPrefix(name: string) { + return name.startsWith('HOT ') ? name.slice(4) : name +} + +// wie backend models.go +const reModel = /^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/ + +function modelKeyFromFilename(fileOrPath: string): string | null { + const file = stripHotPrefix(baseName(fileOrPath)) + const base = file.replace(/\.[^.]+$/, '') // ext weg + + const m = base.match(reModel) + if (m?.[1]?.trim()) return m[1].trim() + + const i = base.lastIndexOf('_') + if (i > 0) return base.slice(0, i) + + return base ? base : null +} + + export default function App() { const [sourceUrl, setSourceUrl] = useState('') - const [parsed, setParsed] = useState(null) - const [parseError, setParseError] = useState(null) + const [, setParsed] = useState(null) + const [, setParseError] = useState(null) const [jobs, setJobs] = useState([]) const [doneJobs, setDoneJobs] = useState([]) - const [error, setError] = useState(null) + const [modelsCount, setModelsCount] = useState(0) + + const [playerModel, setPlayerModel] = useState(null) + const modelsCacheRef = useRef<{ ts: number; list: StoredModel[] } | null>(null) + const watchedModelsRef = useRef([]) + const [, setError] = useState(null) const [busy, setBusy] = useState(false) const [cookieModalOpen, setCookieModalOpen] = useState(false) const [cookies, setCookies] = useState>({}) @@ -111,6 +148,12 @@ export default function App() { const [recSettings, setRecSettings] = useState(DEFAULT_RECORDER_SETTINGS) + // ✅ Watched+Online (wartend) + Autostart-Queue + const [pendingWatchedRooms, setPendingWatchedRooms] = useState([]) + const autoStartQueueRef = useRef>([]) + const autoStartQueuedUsersRef = useRef>(new Set()) + const autoStartWorkerRef = useRef(false) + const autoAddEnabled = Boolean(recSettings.autoAddToDownloadList) const autoStartEnabled = Boolean(recSettings.autoStartAddedDownloads) @@ -128,7 +171,7 @@ export default function App() { // um identische Clipboard-Werte nicht dauernd zu triggern const lastClipboardUrlRef = useRef('') - // settings poll (damit Umschalten im Settings-Tab ohne Reload wirkt) + // ✅ settings: nur einmal laden + nach Save-Event + optional bei focus/visibility useEffect(() => { let cancelled = false @@ -141,14 +184,78 @@ export default function App() { } } + const onUpdated = () => void load() + const onFocus = () => void load() + + window.addEventListener('recorder-settings-updated', onUpdated as EventListener) + window.addEventListener('focus', onFocus) + document.addEventListener('visibilitychange', onFocus) + + load() // einmal initial + + return () => { + cancelled = true + window.removeEventListener('recorder-settings-updated', onUpdated as EventListener) + window.removeEventListener('focus', onFocus) + document.removeEventListener('visibilitychange', onFocus) + } + }, []) + + // ✅ 1) Models-Count (leicht): nur Zahl fürs Tab, nicht die komplette Liste + useEffect(() => { + let cancelled = false + + const load = async () => { + try { + const meta = await apiJSON<{ count?: number }>('/api/models/meta', { cache: 'no-store' }) + const c = Number(meta?.count ?? 0) + if (!cancelled && Number.isFinite(c)) setModelsCount(c) + } catch { + // ignore + } + } + load() - const t = window.setInterval(load, 3000) + const t = window.setInterval(load, document.hidden ? 60000 : 30000) return () => { cancelled = true window.clearInterval(t) } }, []) + // ✅ 2) Watched-Chaturbate-Models (kleine Payload) – nur für den Online-Abgleich/Autostart + useEffect(() => { + if (!recSettings.useChaturbateApi) { + watchedModelsRef.current = [] + return + } + + let cancelled = false + let inFlight = false + + const load = async () => { + if (cancelled || inFlight) return + inFlight = true + try { + const list = await apiJSON('/api/models/watched?host=chaturbate.com', { cache: 'no-store' }) + if (cancelled) return + watchedModelsRef.current = Array.isArray(list) ? list : [] + } catch { + if (!cancelled) watchedModelsRef.current = [] + } finally { + inFlight = false + } + } + + load() + const t = window.setInterval(load, document.hidden ? 30000 : 10000) + return () => { + cancelled = true + window.clearInterval(t) + } + }, [recSettings.useChaturbateApi]) + + const initialCookies = useMemo( () => Object.entries(cookies).map(([name, value]) => ({ name, value })), [cookies] @@ -162,26 +269,62 @@ export default function App() { const runningJobs = jobs.filter((j) => j.status === 'running') const tabs: TabItem[] = [ - { id: 'running', label: 'Laufende Downloads', count: runningJobs.length }, + { id: 'running', label: 'Laufende Downloads', count: runningJobs.length + pendingWatchedRooms.length }, { id: 'finished', label: 'Abgeschlossene Downloads', count: doneJobs.length }, - { id: 'models', label: 'Models' }, + { id: 'models', label: 'Models', count: modelsCount }, { id: 'settings', label: 'Einstellungen' }, ] const canStart = useMemo(() => sourceUrl.trim().length > 0 && !busy, [sourceUrl, busy]) useEffect(() => { - const raw = localStorage.getItem(COOKIE_STORAGE_KEY) - if (raw) { + let cancelled = false + + const load = async () => { + // 1) Try backend first (persisted + encrypted in recorder_settings.json) try { - const obj = JSON.parse(raw) as Record - const normalized = Object.fromEntries( - Object.entries(obj).map(([k, v]) => [k.trim().toLowerCase(), String(v ?? '').trim()]) - ) - setCookies(normalized) - } catch {} + const res = await apiJSON<{ cookies?: Record }>('/api/cookies', { cache: 'no-store' }) + const fromBackend = normalizeCookies(res?.cookies) + if (!cancelled) setCookies(fromBackend) + + // Optional migration: if backend is empty but localStorage has cookies, push them once + if (Object.keys(fromBackend).length === 0) { + const raw = localStorage.getItem(COOKIE_STORAGE_KEY) + if (raw) { + try { + const obj = JSON.parse(raw) as Record + const local = normalizeCookies(obj) + if (Object.keys(local).length > 0) { + if (!cancelled) setCookies(local) + await apiJSON('/api/cookies', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ cookies: local }), + }) + } + } catch { + // ignore + } + } + } + } catch { + // 2) Fallback: localStorage + const raw = localStorage.getItem(COOKIE_STORAGE_KEY) + if (raw) { + try { + const obj = JSON.parse(raw) as Record + if (!cancelled) setCookies(normalizeCookies(obj)) + } catch {} + } + } finally { + if (!cancelled) setCookiesLoaded(true) + } + } + + load() + return () => { + cancelled = true } - setCookiesLoaded(true) }, []) useEffect(() => { @@ -285,25 +428,26 @@ export default function App() { return Boolean(cf && sess) } - const startUrl = useCallback(async (rawUrl: string) => { + const startUrl = useCallback(async (rawUrl: string, opts?: { silent?: boolean }): Promise => { const url = rawUrl.trim() - if (!url) return - if (busyRef.current) return + if (!url) return false + if (busyRef.current) return false - setError(null) + const silent = Boolean(opts?.silent) + if (!silent) setError(null) // ❌ Chaturbate ohne Cookies blockieren const currentCookies = cookiesRef.current if (isChaturbate(url) && !hasRequiredChaturbateCookies(currentCookies)) { - setError('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.') - return + if (!silent) setError('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.') + return false } // Duplicate-running guard const alreadyRunning = jobsRef.current.some( (j) => j.status === 'running' && String(j.sourceUrl || '') === url ) - if (alreadyRunning) return + if (alreadyRunning) return true setBusy(true) busyRef.current = true @@ -320,18 +464,330 @@ export default function App() { }) setJobs((prev) => [created, ...prev]) + // sofort in Ref, damit Duplicate-Guard greift, bevor Jobs-Polling nachzieht + jobsRef.current = [created, ...jobsRef.current] + return true } catch (e: any) { - setError(e?.message ?? String(e)) + if (!silent) setError(e?.message ?? String(e)) + return false } finally { setBusy(false) busyRef.current = false } }, []) // arbeitet über refs, daher keine deps nötig + async function resolveModelForJob(job: RecordJob): Promise { + const urlFromJob = ((job as any).sourceUrl ?? (job as any).SourceURL ?? '') as string + const url = extractFirstHttpUrl(urlFromJob) + + // 1) Wenn URL da ist: parse + upsert => liefert ID + flags + if (url) { + const parsed = await apiJSON('/api/models/parse', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ input: url }), + }) + + const saved = await apiJSON('/api/models/upsert', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(parsed), + }) + + return saved + } + + // 2) Fallback: aus Dateiname modelKey ableiten und im Store suchen + const key = modelKeyFromFilename(job.output || '') + if (!key) return null + + const now = Date.now() + const cached = modelsCacheRef.current + if (!cached || now - cached.ts > 30_000) { + const list = await apiJSON('/api/models/list', { cache: 'no-store' as any }) + modelsCacheRef.current = { ts: now, list: Array.isArray(list) ? list : [] } + } + + const list = modelsCacheRef.current?.list ?? [] + const needle = key.toLowerCase() + + // wenn mehrere: nimm Favorite zuerst, dann irgendeins + const hits = list.filter(m => (m.modelKey || '').toLowerCase() === needle) + if (hits.length === 0) return null + return hits.sort((a, b) => Number(Boolean(b.favorite)) - Number(Boolean(a.favorite)))[0] + } + + useEffect(() => { + let cancelled = false + if (!playerJob) { + setPlayerModel(null) + return + } + + ;(async () => { + try { + const m = await resolveModelForJob(playerJob) + if (!cancelled) setPlayerModel(m) + } catch { + if (!cancelled) setPlayerModel(null) + } + })() + + return () => { cancelled = true } + }, [playerJob]) + + async function onStart() { return startUrl(sourceUrl) } + const handlePlayerDelete = useCallback(async (job: RecordJob) => { + // running => stop (macht mp4 remux etc) + if (job.status === 'running') { + await stopJob(job.id) + setPlayerJob(null) + return + } + + const file = baseName(job.output || '') + if (!file) return + + await apiJSON(`/api/record/delete?file=${encodeURIComponent(file)}`, { method: 'POST' }) + + // UI sofort aktualisieren + setDoneJobs(prev => prev.filter(j => baseName(j.output || '') !== file)) + setJobs(prev => prev.filter(j => baseName(j.output || '') !== file)) + setPlayerJob(null) + }, []) + + const handleToggleHot = useCallback(async (job: RecordJob) => { + const file = baseName(job.output || '') + if (!file) return + + const res = await apiJSON<{ ok: boolean; oldFile: string; newFile: string }>( + `/api/record/toggle-hot?file=${encodeURIComponent(file)}`, + { method: 'POST' } + ) + + const newOutput = replaceBasename(job.output || '', res.newFile) + + setPlayerJob(prev => (prev ? { ...prev, output: newOutput } : prev)) + setDoneJobs(prev => prev.map(j => baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) + setJobs(prev => prev.map(j => baseName(j.output || '') === file ? { ...j, output: replaceBasename(j.output || '', res.newFile) } : j)) + }, []) + + async function patchModelFlags(patch: any) { + return apiJSON('/api/models/flags', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(patch), + }) + } + + const handleToggleFavorite = useCallback(async (job: RecordJob) => { + let m = playerModel + if (!m) { + m = await resolveModelForJob(job) + setPlayerModel(m) + } + if (!m) return + + const next = !Boolean(m.favorite) + const updated = await patchModelFlags({ id: m.id, favorite: next }) + + setPlayerModel(updated) + window.dispatchEvent(new Event('models-changed')) + }, [playerModel]) + + const handleToggleLike = useCallback(async (job: RecordJob) => { + let m = playerModel + if (!m) { + m = await resolveModelForJob(job) + setPlayerModel(m) + } + if (!m) return + + const next = !(m.liked === true) + const updated = await patchModelFlags({ id: m.id, liked: next }) + + setPlayerModel(updated) + window.dispatchEvent(new Event('models-changed')) + }, [playerModel]) + + + const normUser = (s: string) => (s || '').trim().toLowerCase() + + const chaturbateUserFromUrl = (u: string): string | null => { + try { + const url = new URL(u) + if (!url.hostname.toLowerCase().includes('chaturbate.com')) return null + const parts = url.pathname.split('/').filter(Boolean) + return parts[0] ? normUser(parts[0]) : null + } catch { + return null + } + } + + // ✅ 1) Poll: alle watched+online Models als "wartend" anzeigen (public/private/hidden/away) + // und public-Models in eine Start-Queue legen + useEffect(() => { + if (!recSettings.useChaturbateApi) { + setPendingWatchedRooms([]) + autoStartQueueRef.current = [] + autoStartQueuedUsersRef.current = new Set() + return + } + + let cancelled = false + let inFlight = false + + const poll = async () => { + if (cancelled || inFlight) return + inFlight = true + try { + const canAutoStart = hasRequiredChaturbateCookies(cookiesRef.current) + + const modelsList = watchedModelsRef.current + + const online = await apiJSON('/api/chaturbate/online', { cache: 'no-store' }) + + if (!online?.enabled) return + + // online username -> show + const showByUser = new Map() + for (const r of online.rooms ?? []) { + showByUser.set(normUser(r.username), String(r.current_show || 'unknown').toLowerCase()) + } + + // running username set (damit wir nichts doppelt starten/anzeigen) + const runningUsers = new Set( + jobsRef.current + .filter((j) => j.status === 'running') + .map((j) => chaturbateUserFromUrl(String(j.sourceUrl || ''))) + .filter(Boolean) as string[] + ) + + // watched username set + const watchedModels = (modelsList ?? []).filter( + (m) => Boolean(m?.watching) && ( + String(m?.host || '').toLowerCase().includes('chaturbate.com') || isChaturbate(String(m?.input || '')) + ) + ) + + const watchedUsers = new Set(watchedModels.map((m) => normUser(m.modelKey)).filter(Boolean)) + + // ✅ Queue aufräumen: raus, wenn nicht mehr watched, offline oder schon running + { + const nextQueue: Array<{ userKey: string; url: string }> = [] + for (const q of autoStartQueueRef.current) { + if (!watchedUsers.has(q.userKey)) continue + if (!showByUser.has(q.userKey)) continue + if (runningUsers.has(q.userKey)) continue + nextQueue.push(q) + } + autoStartQueueRef.current = nextQueue + autoStartQueuedUsersRef.current = new Set(nextQueue.map((q) => q.userKey)) + } + + // ✅ Pending Map: alle watched+online, die NICHT running sind + const pendingMap = new Map() + + for (const m of watchedModels) { + const key = normUser(m.modelKey) + if (!key) continue + + const currentShow = showByUser.get(key) + if (!currentShow) continue // offline -> nicht pending + + // running -> nicht pending (steht ja in Jobs) + if (runningUsers.has(key)) continue + + const url = /^https?:\/\//i.test(m.input || '') + ? String(m.input).trim() + : `https://chaturbate.com/${m.modelKey}/` + + // ✅ erst mal ALLE watched+online als wartend anzeigen (auch public) + if (!pendingMap.has(key)) { + pendingMap.set(key, { id: m.id, modelKey: m.modelKey, url, currentShow }) + } + + // ✅ public in Queue (wenn Cookies da), aber ohne Duplikate + if (currentShow === 'public' && canAutoStart && !autoStartQueuedUsersRef.current.has(key)) { + autoStartQueueRef.current.push({ userKey: key, url }) + autoStartQueuedUsersRef.current.add(key) + } + } + + if (!cancelled) setPendingWatchedRooms([...pendingMap.values()]) + } catch { + // silent + } finally { + inFlight = false + } + } + + poll() + const t = window.setInterval(poll, document.hidden ? 15000 : 5000) + return () => { + cancelled = true + window.clearInterval(t) + } + }, [recSettings.useChaturbateApi]) + + // ✅ 2) Worker: startet Queue nacheinander (5s Pause nach jedem Start) + useEffect(() => { + if (!recSettings.useChaturbateApi) return + + let cancelled = false + + const loop = async () => { + if (autoStartWorkerRef.current) return + autoStartWorkerRef.current = true + + try { + while (!cancelled) { + // wenn UI gerade manuell startet -> warten + if (busyRef.current) { + await sleep(500) + continue + } + + const next = autoStartQueueRef.current.shift() + if (!next) { + await sleep(1000) + continue + } + + // aus queued-set entfernen (damit Poll ggf. neu einreihen kann, falls Start nicht klappt) + autoStartQueuedUsersRef.current.delete(next.userKey) + + // start attempt (silent) + const ok = await startUrl(next.url, { silent: true }) + if (ok) { + // pending sofort rausnehmen, damit UI direkt "running" zeigt + setPendingWatchedRooms((prev) => prev.filter((p) => normUser(p.modelKey) !== next.userKey)) + } + + // ✅ 5s Abstand nach (erfolgreichem) Starten – ich warte auch bei failure, + // damit wir nicht in eine schnelle Retry-Schleife laufen. + if (ok) { + await sleep(5000) + } else { + await sleep(5000) + } + } + } finally { + autoStartWorkerRef.current = false + } + } + + void loop() + + return () => { + cancelled = true + } + }, [recSettings.useChaturbateApi, startUrl]) + useEffect(() => { if (!autoAddEnabled && !autoStartEnabled) return if (!navigator.clipboard?.readText) return @@ -459,6 +915,7 @@ export default function App() { {selectedTab === 'running' && ( @@ -482,12 +939,19 @@ export default function App() { onClose={() => setCookieModalOpen(false)} initialCookies={initialCookies} onApply={(list) => { - const normalized = Object.fromEntries( - list - .map((c) => [c.name.trim().toLowerCase(), c.value.trim()] as const) - .filter(([k, v]) => k.length > 0 && v.length > 0) + const normalized = normalizeCookies( + Object.fromEntries(list.map((c) => [c.name, c.value] as const)) ) setCookies(normalized) + + // Persist encrypted in recorder_settings.json via backend + void apiJSON('/api/cookies', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ cookies: normalized }), + }).catch(() => { + // keep UI usable; backend persistence failed + }) }} /> @@ -497,6 +961,15 @@ export default function App() { expanded={playerExpanded} onToggleExpand={() => setPlayerExpanded((v) => !v)} onClose={() => setPlayerJob(null)} + + isHot={baseName(playerJob.output || '').startsWith('HOT ')} + isFavorite={Boolean(playerModel?.favorite)} + isLiked={playerModel?.liked === true} + + onDelete={handlePlayerDelete} + onToggleHot={handleToggleHot} + onToggleFavorite={handleToggleFavorite} + onToggleLike={handleToggleLike} /> )} diff --git a/frontend/src/components/ui/Button.tsx b/frontend/src/components/ui/Button.tsx index a873814..8e08c64 100644 --- a/frontend/src/components/ui/Button.tsx +++ b/frontend/src/components/ui/Button.tsx @@ -2,6 +2,7 @@ import * as React from 'react' type Variant = 'primary' | 'secondary' | 'soft' type Size = 'xs' | 'sm' | 'md' | 'lg' +type Color = 'indigo' | 'blue' | 'emerald' | 'red' | 'amber' export type ButtonProps = Omit< React.ButtonHTMLAttributes, @@ -10,6 +11,7 @@ export type ButtonProps = Omit< children: React.ReactNode variant?: Variant size?: Size + color?: Color rounded?: 'sm' | 'md' | 'full' leadingIcon?: React.ReactNode trailingIcon?: React.ReactNode @@ -37,42 +39,69 @@ const sizeMap: Record = { lg: 'px-3.5 py-2.5 text-sm', } -// Varianten basieren auf deinen Klassen :contentReference[oaicite:1]{index=1} -const variantMap: Record = { - primary: - 'bg-indigo-600 text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-indigo-600 ' + - 'dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500', - secondary: - 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + - 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', - soft: - 'bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 ' + - 'dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30', +const colorMap: Record> = { + indigo: { + primary: + 'bg-indigo-600 text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-indigo-600 ' + + 'dark:bg-indigo-500 dark:shadow-none dark:hover:bg-indigo-400 dark:focus-visible:outline-indigo-500', + secondary: + 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', + soft: + 'bg-indigo-50 text-indigo-600 shadow-xs hover:bg-indigo-100 ' + + 'dark:bg-indigo-500/20 dark:text-indigo-400 dark:shadow-none dark:hover:bg-indigo-500/30', + }, + blue: { + primary: + 'bg-blue-600 text-white shadow-xs hover:bg-blue-500 focus-visible:outline-blue-600 ' + + 'dark:bg-blue-500 dark:shadow-none dark:hover:bg-blue-400 dark:focus-visible:outline-blue-500', + secondary: + 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', + soft: + 'bg-blue-50 text-blue-600 shadow-xs hover:bg-blue-100 ' + + 'dark:bg-blue-500/20 dark:text-blue-400 dark:shadow-none dark:hover:bg-blue-500/30', + }, + emerald: { + primary: + 'bg-emerald-600 text-white shadow-xs hover:bg-emerald-500 focus-visible:outline-emerald-600 ' + + 'dark:bg-emerald-500 dark:shadow-none dark:hover:bg-emerald-400 dark:focus-visible:outline-emerald-500', + secondary: + 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', + soft: + 'bg-emerald-50 text-emerald-700 shadow-xs hover:bg-emerald-100 ' + + 'dark:bg-emerald-500/20 dark:text-emerald-400 dark:shadow-none dark:hover:bg-emerald-500/30', + }, + red: { + primary: + 'bg-red-600 text-white shadow-xs hover:bg-red-500 focus-visible:outline-red-600 ' + + 'dark:bg-red-500 dark:shadow-none dark:hover:bg-red-400 dark:focus-visible:outline-red-500', + secondary: + 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', + soft: + 'bg-red-50 text-red-700 shadow-xs hover:bg-red-100 ' + + 'dark:bg-red-500/20 dark:text-red-400 dark:shadow-none dark:hover:bg-red-500/30', + }, + amber: { + primary: + 'bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:outline-amber-500 ' + + 'dark:bg-amber-500 dark:shadow-none dark:hover:bg-amber-400 dark:focus-visible:outline-amber-500', + secondary: + 'bg-white text-gray-900 shadow-xs inset-ring inset-ring-gray-300 hover:bg-gray-50 ' + + 'dark:bg-white/10 dark:text-white dark:shadow-none dark:inset-ring-white/5 dark:hover:bg-white/20', + soft: + 'bg-amber-50 text-amber-800 shadow-xs hover:bg-amber-100 ' + + 'dark:bg-amber-500/20 dark:text-amber-300 dark:shadow-none dark:hover:bg-amber-500/30', + }, } function Spinner() { return ( - {children} - {trailingIcon && !isLoading && ( - {trailingIcon} - )} + {trailingIcon && !isLoading && {trailingIcon}} ) } diff --git a/frontend/src/components/ui/FinishedDownloads.tsx b/frontend/src/components/ui/FinishedDownloads.tsx index 5d9e26f..f48e6d1 100644 --- a/frontend/src/components/ui/FinishedDownloads.tsx +++ b/frontend/src/components/ui/FinishedDownloads.tsx @@ -3,12 +3,13 @@ import * as React from 'react' import { useMemo } from 'react' -import Table, { type Column } from './Table' +import Table, { type Column, type SortState } from './Table' import Card from './Card' import type { RecordJob } from '../../types' import FinishedVideoPreview from './FinishedVideoPreview' import ContextMenu, { type ContextMenuItem } from './ContextMenu' import { buildDownloadContextMenu } from './DownloadContextMenu' +import Button from './Button' type Props = { jobs: RecordJob[] @@ -59,8 +60,16 @@ const modelNameFromOutput = (output?: string) => { } export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Props) { + const PAGE_SIZE = 50 + const [visibleCount, setVisibleCount] = React.useState(PAGE_SIZE) const [ctx, setCtx] = React.useState<{ x: number; y: number; job: RecordJob } | null>(null) + // 🗑️ lokale Optimistik: sofort ausblenden, ohne auf das nächste Polling zu warten + const [deletedKeys, setDeletedKeys] = React.useState>(() => new Set()) + const [deletingKeys, setDeletingKeys] = React.useState>(() => new Set()) + + const [sort, setSort] = React.useState(null) + // 🔄 globaler Tick für animierte Thumbnails der fertigen Videos const [thumbTick, setThumbTick] = React.useState(0) @@ -85,6 +94,52 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop setCtx({ x, y, job }) } + const markDeleting = React.useCallback((key: string, value: boolean) => { + setDeletingKeys((prev) => { + const next = new Set(prev) + if (value) next.add(key) + else next.delete(key) + return next + }) + }, []) + + const markDeleted = React.useCallback((key: string) => { + setDeletedKeys((prev) => { + const next = new Set(prev) + next.add(key) + return next + }) + }, []) + + const deleteVideo = React.useCallback( + async (job: RecordJob) => { + const file = baseName(job.output || '') + const key = keyFor(job) + if (!file) { + window.alert('Kein Dateiname gefunden – kann nicht löschen.') + return + } + if (deletingKeys.has(key)) return + + markDeleting(key, true) + try { + const res = await fetch(`/api/record/delete?file=${encodeURIComponent(file)}`, { + method: 'POST', + }) + if (!res.ok) { + const text = await res.text().catch(() => '') + throw new Error(text || `HTTP ${res.status}`) + } + markDeleted(key) + } catch (e: any) { + window.alert(`Löschen fehlgeschlagen: ${String(e?.message || e)}`) + } finally { + markDeleting(key, false) + } + }, + [deletingKeys, markDeleted, markDeleting] + ) + const items = React.useMemo(() => { if (!ctx) return [] const j = ctx.job @@ -113,10 +168,24 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop onToggleHot: (job) => console.log('toggle hot', job.id), onToggleKeep: (job) => console.log('toggle keep', job.id), - onDelete: (job) => console.log('delete', job.id), + onDelete: (job) => { + setCtx(null) + void deleteVideo(job) + }, }, }) - }, [ctx, onOpenPlayer]) + }, [ctx, deleteVideo, onOpenPlayer]) + + const runtimeSecondsForSort = React.useCallback((job: RecordJob) => { + const k = keyFor(job) + const sec = durations[k] + if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) return sec + + const start = Date.parse(String(job.startedAt || '')) + const end = Date.parse(String(job.endedAt || '')) + if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return Number.POSITIVE_INFINITY + return (end - start) / 1000 + }, [durations]) const rows = useMemo(() => { const map = new Map() @@ -130,13 +199,20 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop if (map.has(k)) map.set(k, { ...map.get(k)!, ...j }) } - const list = Array.from(map.values()).filter( - (j) => j.status === 'finished' || j.status === 'failed' || j.status === 'stopped' - ) + const list = Array.from(map.values()).filter((j) => { + if (deletedKeys.has(keyFor(j))) return false + return j.status === 'finished' || j.status === 'failed' || j.status === 'stopped' + }) list.sort((a, b) => norm(b.endedAt || '').localeCompare(norm(a.endedAt || ''))) return list - }, [jobs, doneJobs]) + }, [jobs, doneJobs, deletedKeys]) + + React.useEffect(() => { + setVisibleCount(PAGE_SIZE) + }, [rows.length]) + + const visibleRows = React.useMemo(() => rows.slice(0, visibleCount), [rows, visibleCount]) // 🧠 Laufzeit-Anzeige: bevorzugt Videodauer, sonst Fallback auf startedAt/endedAt const runtimeOf = (job: RecordJob): string => { @@ -178,6 +254,8 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop { key: 'model', header: 'Modelname', + sortable: true, + sortValue: (j) => modelNameFromOutput(j.output), cell: (j) => { const name = modelNameFromOutput(j.output) return ( @@ -190,11 +268,15 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop { key: 'output', header: 'Datei', + sortable: true, + sortValue: (j) => baseName(j.output || ''), cell: (j) => baseName(j.output || ''), }, { key: 'status', header: 'Status', + sortable: true, + sortValue: (j) => (j.status === 'finished' ? 0 : j.status === 'stopped' ? 1 : j.status === 'failed' ? 2 : 9), cell: (j) => { if (j.status !== 'failed') return j.status const code = httpCodeFromError(j.error) @@ -209,6 +291,8 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop { key: 'runtime', header: 'Dauer', + sortable: true, + sortValue: (j) => runtimeSecondsForSort(j), cell: (j) => runtimeOf(j), }, { @@ -216,7 +300,26 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop header: 'Aktion', align: 'right', srOnlyHeader: true, - cell: () => , + cell: (j) => { + const k = keyFor(j) + const busy = deletingKeys.has(k) + return ( + + ) + }, }, ] @@ -234,7 +337,7 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop <> {/* ✅ Mobile: Cards */}
- {rows.map((j) => { + {visibleRows.map((j) => { const model = modelNameFromOutput(j.output) const file = baseName(j.output || '') const dur = runtimeOf(j) @@ -272,20 +375,35 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop
- {/* ✅ Menü-Button für Touch/Small Devices */} - +
+ {/* 🗑️ Direkt-Löschen */} + + + {/* ✅ Menü-Button für Touch/Small Devices */} + +
} > @@ -331,11 +449,13 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop {/* ✅ Desktop/Tablet: Tabelle */}
keyFor(j)} striped fullWidth + sort={sort} + onSortChange={setSort} onRowClick={onOpenPlayer} onRowContextMenu={(job, e) => openCtx(job, e)} /> @@ -348,6 +468,18 @@ export default function FinishedDownloads({ jobs, doneJobs, onOpenPlayer }: Prop items={items} onClose={() => setCtx(null)} /> + + {rows.length > visibleCount ? ( +
+ +
+ ) : null} ) } diff --git a/frontend/src/components/ui/LiveHlsVideo.tsx b/frontend/src/components/ui/LiveHlsVideo.tsx index 44ad49b..725bb9f 100644 --- a/frontend/src/components/ui/LiveHlsVideo.tsx +++ b/frontend/src/components/ui/LiveHlsVideo.tsx @@ -19,11 +19,13 @@ export default function LiveHlsVideo({ let cancelled = false let hls: Hls | null = null - const video = ref.current - if (!video) return + // NOTE: Narrowing ("if (!video) return") wirkt NICHT in async-Callbacks. + // Deshalb reichen wir das Element explizit in start() rein. + const videoEl = ref.current + if (!videoEl) return setBroken(false) - video.muted = muted + videoEl.muted = muted async function waitForManifest() { const started = Date.now() @@ -42,7 +44,7 @@ export default function LiveHlsVideo({ return false } - async function start() { + async function start(video: HTMLVideoElement) { const ok = await waitForManifest() if (!ok || cancelled) { if (!cancelled) setBroken(true) @@ -79,7 +81,7 @@ export default function LiveHlsVideo({ }) } - start() + void start(videoEl) return () => { cancelled = true diff --git a/frontend/src/components/ui/ModelPreview.tsx b/frontend/src/components/ui/ModelPreview.tsx index 0e8194d..75c4476 100644 --- a/frontend/src/components/ui/ModelPreview.tsx +++ b/frontend/src/components/ui/ModelPreview.tsx @@ -1,21 +1,69 @@ // frontend/src/components/ui/ModelPreview.tsx 'use client' -import { useMemo } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import HoverPopover from './HoverPopover' import LiveHlsVideo from './LiveHlsVideo' type Props = { jobId: string - // wird von außen hochgezählt (z.B. alle 5s) - thumbTick: number + // Optional: wird von außen hochgezählt (z.B. alle 5s). Wenn nicht gesetzt, + // tickt die Komponente selbst (weniger Re-Renders im Parent). + thumbTick?: number + // wie oft (ms) der Thumbnail neu geladen werden soll, wenn thumbTick nicht gesetzt ist + autoTickMs?: number } -export default function ModelPreview({ jobId, thumbTick }: Props) { +export default function ModelPreview({ jobId, thumbTick, autoTickMs = 30000 }: Props) { + const [localTick, setLocalTick] = useState(0) + const [imgError, setImgError] = useState(false) + const rootRef = useRef(null) + const [inView, setInView] = useState(false) + + useEffect(() => { + // Wenn Parent tickt, kein lokales Ticken + if (typeof thumbTick === 'number') return + + // Nur animieren, wenn im Sichtbereich UND Tab sichtbar + if (!inView || document.hidden) return + + const id = window.setInterval(() => { + setLocalTick((t) => t + 1) + }, autoTickMs) + + return () => window.clearInterval(id) + }, [thumbTick, autoTickMs, inView]) + + useEffect(() => { + const el = rootRef.current + if (!el) return + + const obs = new IntersectionObserver( + (entries) => { + const entry = entries[0] + setInView(Boolean(entry?.isIntersecting)) + }, + { + root: null, + threshold: 0.1, + } + ) + + obs.observe(el) + return () => obs.disconnect() + }, []) + + const tick = typeof thumbTick === 'number' ? thumbTick : localTick + + // bei neuem Tick Error-Flag zurücksetzen (damit wir retries erlauben) + useEffect(() => { + setImgError(false) + }, [tick]) + // Thumbnail mit Cache-Buster (?v=...) const thumb = useMemo( - () => `/api/record/preview?id=${encodeURIComponent(jobId)}&v=${thumbTick}`, - [jobId, thumbTick] + () => `/api/record/preview?id=${encodeURIComponent(jobId)}&v=${tick}`, + [jobId, tick] ) // HLS nur für große Vorschau im Popover @@ -41,13 +89,24 @@ export default function ModelPreview({ jobId, thumbTick }: Props) { ) } > -
- +
+ {!imgError ? ( + setImgError(true)} + onLoad={() => setImgError(false)} + /> + ) : ( +
+ keine Vorschau +
+ )}
) diff --git a/frontend/src/components/ui/ModelsTab.tsx b/frontend/src/components/ui/ModelsTab.tsx index c67918b..63c91bc 100644 --- a/frontend/src/components/ui/ModelsTab.tsx +++ b/frontend/src/components/ui/ModelsTab.tsx @@ -5,6 +5,9 @@ import clsx from 'clsx' import Card from './Card' import Button from './Button' import Table, { type Column } from './Table' +import Modal from './Modal' +import Pagination from './Pagination' + type ParsedModel = { input: string @@ -14,6 +17,8 @@ type ParsedModel = { modelKey: string } +type ImportKind = 'liked' | 'favorite' + export type StoredModel = { id: string input: string @@ -21,6 +26,9 @@ export type StoredModel = { host?: string path?: string modelKey: string + tags?: string + lastStream?: string + watching: boolean favorite: boolean hot: boolean @@ -30,6 +38,7 @@ export type StoredModel = { updatedAt: string } + async function apiJSON(url: string, init?: RequestInit): Promise { const res = await fetch(url, init) if (!res.ok) { @@ -68,6 +77,41 @@ function normalizeHttpUrl(raw: string): string | null { } } +function splitTags(raw?: string): string[] { + if (!raw) return [] + + const tags = raw + .split(',') + .map((t) => t.trim()) + .filter(Boolean) + + const uniq = Array.from(new Set(tags)) + + // ✅ alphabetisch (case-insensitive), aber original casing bleibt + uniq.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })) + + return uniq +} + + +function TagBadge({ + children, + title, +}: { + children: React.ReactNode + title?: string +}) { + return ( + + {children} + + ) +} + + function IconToggle({ title, active, @@ -113,11 +157,55 @@ export default function ModelsTab() { const [err, setErr] = React.useState(null) const [q, setQ] = React.useState('') + const [page, setPage] = React.useState(1) + const pageSize = 10 + const [input, setInput] = React.useState('') const [parsed, setParsed] = React.useState(null) const [parseError, setParseError] = React.useState(null) const [adding, setAdding] = React.useState(false) + const [importOpen, setImportOpen] = React.useState(false) + const [importFile, setImportFile] = React.useState(null) + const [importMsg, setImportMsg] = React.useState(null) + + const [importKind, setImportKind] = React.useState('favorite') + const [importing, setImporting] = React.useState(false) + const [importErr, setImportErr] = React.useState(null) + + + async function doImport() { + if (!importFile) return + setImporting(true) + setImportMsg(null) + setErr(null) + try { + const fd = new FormData() + fd.append('file', importFile) + fd.append('kind', importKind) + + const res = await fetch('/api/models/import', { method: 'POST', body: fd }) + if (!res.ok) throw new Error(await res.text()) + const data = await res.json() + setImportMsg(`✅ Import: ${data.inserted} neu, ${data.updated} aktualisiert, ${data.skipped} übersprungen`) + setImportOpen(false) + setImportFile(null) + await refresh() + } catch (e: any) { + setImportErr(e?.message ?? String(e)) + } finally { + setImporting(false) + } + } + + const openImport = () => { + setImportErr(null) + setImportMsg(null) + setImportFile(null) + setImportKind('favorite') // optional + setImportOpen(true) + } + const refresh = React.useCallback(async () => { setLoading(true) setErr(null) @@ -135,6 +223,12 @@ export default function ModelsTab() { refresh() }, [refresh]) + React.useEffect(() => { + const onChanged = () => { void refresh() } + window.addEventListener('models-changed', onChanged as any) + return () => window.removeEventListener('models-changed', onChanged as any) + }, [refresh]) + // Parse (debounced) nur bei gültiger URL React.useEffect(() => { const raw = input.trim() @@ -176,14 +270,36 @@ export default function ModelsTab() { return () => window.clearTimeout(t) }, [input]) + const modelsWithHay = React.useMemo(() => { + return models.map((m) => ({ + m, + hay: `${m.modelKey} ${m.host ?? ''} ${m.input ?? ''} ${m.tags ?? ''}`.toLowerCase(), + })) + }, [models]) + + const deferredQ = React.useDeferredValue(q) + const filtered = React.useMemo(() => { - const needle = q.trim().toLowerCase() + const needle = deferredQ.trim().toLowerCase() if (!needle) return models - return models.filter((m) => { - const hay = [m.modelKey, m.host ?? '', m.input ?? ''].join(' ').toLowerCase() - return hay.includes(needle) - }) - }, [models, q]) + return modelsWithHay.filter(x => x.hay.includes(needle)).map(x => x.m) + }, [models, modelsWithHay, deferredQ]) + + React.useEffect(() => { + setPage(1) + }, [q]) + + const totalItems = filtered.length + const totalPages = React.useMemo(() => Math.max(1, Math.ceil(totalItems / pageSize)), [totalItems, pageSize]) + + React.useEffect(() => { + if (page > totalPages) setPage(totalPages) + }, [page, totalPages]) + + const pageRows = React.useMemo(() => { + const start = (page - 1) * pageSize + return filtered.slice(start, start + pageSize) + }, [filtered, page, pageSize]) const upsertFromParsed = async () => { if (!parsed) return @@ -221,7 +337,13 @@ export default function ModelsTab() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, ...body }), }) - setModels((prev) => prev.map((m) => (m.id === updated.id ? updated : m))) + setModels((prev) => { + const idx = prev.findIndex((m) => m.id === updated.id) + if (idx === -1) return prev + const next = prev.slice() + next[idx] = updated + return next + }) } catch (e: any) { setErr(e?.message ?? String(e)) } @@ -337,12 +459,31 @@ export default function ModelsTab() { { key: 'tags', header: 'Tags', - cell: (m) => ( -
- {m.hot ? badge(true, '🔥 HOT') : null} - {m.keep ? badge(true, '📌 Behalten') : null} -
- ), + cell: (m) => { + const tags = splitTags(m.tags) + const shown = tags.slice(0, 6) + const rest = tags.length - shown.length + const full = tags.join(', ') + + return ( +
+ {m.hot ? badge(true, '🔥 HOT') : null} + {m.keep ? badge(true, '📌 Behalten') : null} + + {shown.map((t) => ( + + {t} + + ))} + + {rest > 0 ? +{rest} : null} + + {!m.hot && !m.keep && tags.length === 0 ? ( + + ) : null} +
+ ) + }, }, ] }, []) @@ -350,7 +491,10 @@ export default function ModelsTab() { return (
- Model hinzufügen
} grayBody> + Model hinzufügen
} + grayBody + >
-
Models ({filtered.length})
- setQ(e.target.value)} - placeholder="Suchen…" - className="w-[220px] rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" - /> +
+ Models ({filtered.length}) +
+ +
+ + + setQ(e.target.value)} + placeholder="Suchen…" + className="w-[220px] rounded-md px-3 py-2 text-sm bg-white text-gray-900 dark:bg-white/10 dark:text-white" + /> +
} noBodyPadding >
m.id} striped @@ -409,7 +562,105 @@ export default function ModelsTab() { stickyHeader onRowClick={(m) => m.input && window.open(m.input, '_blank', 'noreferrer')} /> + + + + !importing && setImportOpen(false)} + title="Models importieren" + footer={ + <> + + + + } + > +
+
+ Wähle eine CSV-Datei zum Import aus. +
+ +
+
+ Import-Typ +
+ +
+ + + +
+
+ + { + const f = e.target.files?.[0] ?? null + setImportErr(null) + setImportFile(f) + }} + 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" + /> + + {importFile ? ( +
+ Ausgewählt: {importFile.name} +
+ ) : null} + + {importErr ? ( +
{importErr}
+ ) : null} + + {/* OPTIONAL: Import-Ergebnis anzeigen, falls du state importMsg/importResult hast */} + {importMsg ? ( +
+ {importMsg} +
+ ) : null} +
+
) } diff --git a/frontend/src/components/ui/Pagination.tsx b/frontend/src/components/ui/Pagination.tsx new file mode 100644 index 0000000..8be6c32 --- /dev/null +++ b/frontend/src/components/ui/Pagination.tsx @@ -0,0 +1,262 @@ +'use client' + +import * as React from 'react' +import clsx from 'clsx' +import { ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/20/solid' + +type PageItem = number | 'ellipsis' + +export type PaginationProps = { + page: number // 1-based + pageSize: number + totalItems: number + onPageChange: (page: number) => void + + /** wie viele Seiten links/rechts neben aktueller Seite */ + siblingCount?: number + /** wie viele Seiten am Anfang/Ende immer gezeigt werden */ + boundaryCount?: number + + /** Summary "Showing x to y of z" anzeigen */ + showSummary?: boolean + /** Wrapper Klassen */ + className?: string + + /** Labels (optional) */ + ariaLabel?: string + prevLabel?: string + nextLabel?: string +} + +function clamp(n: number, min: number, max: number) { + return Math.max(min, Math.min(max, n)) +} + +function range(start: number, end: number): number[] { + const out: number[] = [] + for (let i = start; i <= end; i++) out.push(i) + return out +} + +function getPageItems( + totalPages: number, + current: number, + boundaryCount: number, + siblingCount: number +): PageItem[] { + if (totalPages <= 1) return [1] + + const first = 1 + const last = totalPages + + const startPages = range(first, Math.min(boundaryCount, last)) + const endPages = range(Math.max(last - boundaryCount + 1, boundaryCount + 1), last) + + const siblingsStart = Math.max( + Math.min( + current - siblingCount, + last - boundaryCount - siblingCount * 2 - 1 + ), + boundaryCount + 1 + ) + + const siblingsEnd = Math.min( + Math.max( + current + siblingCount, + boundaryCount + siblingCount * 2 + 2 + ), + last - boundaryCount + ) + + const items: PageItem[] = [] + + // start + items.push(...startPages) + + // left gap + if (siblingsStart > boundaryCount + 1) { + items.push('ellipsis') + } else if (boundaryCount + 1 < last - boundaryCount) { + items.push(boundaryCount + 1) + } + + // siblings + items.push(...range(siblingsStart, siblingsEnd)) + + // right gap + if (siblingsEnd < last - boundaryCount) { + items.push('ellipsis') + } else if (last - boundaryCount > boundaryCount) { + items.push(last - boundaryCount) + } + + // end + items.push(...endPages) + + // dedupe + keep order + const seen = new Set() + return items.filter((x) => { + const k = String(x) + if (seen.has(k)) return false + seen.add(k) + return true + }) +} + +function PageButton({ + active, + disabled, + rounded, + onClick, + children, + title, +}: { + active?: boolean + disabled?: boolean + rounded?: 'l' | 'r' | 'none' + onClick?: () => void + children: React.ReactNode + title?: string +}) { + const roundedCls = + rounded === 'l' ? 'rounded-l-md' : rounded === 'r' ? 'rounded-r-md' : '' + + return ( + + ) +} + +export default function Pagination({ + page, + pageSize, + totalItems, + onPageChange, + siblingCount = 1, + boundaryCount = 1, + showSummary = true, + className, + ariaLabel = 'Pagination', + prevLabel = 'Previous', + nextLabel = 'Next', +}: PaginationProps) { + const totalPages = Math.max(1, Math.ceil((totalItems || 0) / Math.max(1, pageSize || 1))) + const current = clamp(page || 1, 1, totalPages) + + if (totalPages <= 1) return null + + const from = totalItems === 0 ? 0 : (current - 1) * pageSize + 1 + const to = Math.min(current * pageSize, totalItems) + + const items = getPageItems(totalPages, current, boundaryCount, siblingCount) + + const go = (p: number) => onPageChange(clamp(p, 1, totalPages)) + + return ( +
+ {/* Mobile: nur Previous/Next */} +
+ + +
+ + {/* Desktop: Summary + Zahlen */} +
+
+ {showSummary ? ( +

+ Showing {from} to{' '} + {to} of{' '} + {totalItems} results +

+ ) : null} +
+ +
+ +
+
+
+ ) +} diff --git a/frontend/src/components/ui/Player.tsx b/frontend/src/components/ui/Player.tsx index 55435d7..337aa40 100644 --- a/frontend/src/components/ui/Player.tsx +++ b/frontend/src/components/ui/Player.tsx @@ -9,19 +9,56 @@ import Button from './Button' import videojs from 'video.js' import type VideoJsPlayer from 'video.js/dist/types/player' import 'video.js/dist/video-js.css' -import { ArrowsPointingOutIcon, ArrowsPointingInIcon } from '@heroicons/react/24/outline' +import { createPortal } from 'react-dom' +import { + ArrowsPointingOutIcon, + ArrowsPointingInIcon, + FireIcon, + HeartIcon, + HandThumbUpIcon, + TrashIcon, + XMarkIcon, +} from '@heroicons/react/24/outline' const baseName = (p: string) => (p || '').replaceAll('\\', '/').split('/').pop() || '' +function cn(...parts: Array) { + return parts.filter(Boolean).join(' ') +} + export type PlayerProps = { job: RecordJob expanded: boolean onClose: () => void onToggleExpand: () => void className?: string + + // states für Buttons + isHot?: boolean + isFavorite?: boolean + isLiked?: boolean + + // actions + onDelete?: (job: RecordJob) => void | Promise + onToggleHot?: (job: RecordJob) => void | Promise + onToggleFavorite?: (job: RecordJob) => void | Promise + onToggleLike?: (job: RecordJob) => void | Promise } -export default function Player({ job, expanded, onClose, onToggleExpand, className }: PlayerProps) { +export default function Player({ + job, + expanded, + onClose, + onToggleExpand, + className, + isHot = false, + isFavorite = false, + isLiked = false, + onDelete, + onToggleHot, + onToggleFavorite, + onToggleLike, +}: PlayerProps) { const title = React.useMemo(() => baseName(job.output?.trim() || '') || job.id, [job.output, job.id]) React.useEffect(() => { @@ -30,18 +67,37 @@ export default function Player({ job, expanded, onClose, onToggleExpand, classNa return () => window.removeEventListener('keydown', onKeyDown) }, [onClose]) - const src = React.useMemo(() => { + const media = React.useMemo(() => { + // Running: LIVE über Preview-HLS + if (job.status === 'running') { + return { + src: `/api/record/preview?id=${encodeURIComponent(job.id)}&file=index_hq.m3u8`, + type: 'application/x-mpegURL', + } + } + const file = baseName(job.output?.trim() || '') - if (file && job.status !== 'running') return `/api/record/video?file=${encodeURIComponent(file)}` - return `/api/record/video?id=${encodeURIComponent(job.id)}` + if (file) { + return { + src: `/api/record/video?file=${encodeURIComponent(file)}`, + type: 'video/mp4', + } + } + + // Fallback (nur solange Job im RAM existiert) + return { src: `/api/record/video?id=${encodeURIComponent(job.id)}`, type: 'video/mp4' } }, [job.id, job.output, job.status]) const containerRef = React.useRef(null) const playerRef = React.useRef(null) const videoNodeRef = React.useRef(null) - // ✅ 1x initialisieren (Element wird sicher in den DOM gehängt) + const [mounted, setMounted] = React.useState(false) + React.useEffect(() => setMounted(true), []) + + // ✅ 1x initialisieren React.useLayoutEffect(() => { + if (!mounted) return if (!containerRef.current) return if (playerRef.current) return @@ -52,8 +108,9 @@ export default function Player({ job, expanded, onClose, onToggleExpand, classNa containerRef.current.appendChild(videoEl) videoNodeRef.current = videoEl - playerRef.current = videojs(videoEl, { + const p = videojs(videoEl, { autoplay: true, + muted: true, // <- wichtig für Autoplay ohne Klick in vielen Browsern controls: true, preload: 'auto', playsinline: true, @@ -76,100 +133,207 @@ export default function Player({ job, expanded, onClose, onToggleExpand, classNa playbackRates: [0.5, 1, 1.25, 1.5, 2], }) + playerRef.current = p + return () => { - if (playerRef.current) { - playerRef.current.dispose() - playerRef.current = null - } - if (videoNodeRef.current) { - videoNodeRef.current.remove() - videoNodeRef.current = null + try { + if (playerRef.current) { + playerRef.current.dispose() + playerRef.current = null + } + } finally { + if (videoNodeRef.current) { + videoNodeRef.current.remove() + videoNodeRef.current = null + } } } - }, []) + }, [mounted]) - // ✅ Source wechseln ohne Remount +// ✅ Source setzen + immer versuchen zu starten React.useEffect(() => { + if (!mounted) return + const p = playerRef.current if (!p || (p as any).isDisposed?.()) return - const wasPlaying = !p.paused() const t = p.currentTime() || 0 - p.src({ src, type: 'video/mp4' }) + // Autoplay-Policy: vor play() immer muted setzen + p.muted(true) + + // Source setzen + p.src({ src: media.src, type: media.type }) + + const tryPlay = () => { + const ret = p.play?.() + if (ret && typeof (ret as any).catch === 'function') { + ;(ret as Promise).catch(() => { + // ok: Browser blockt evtl. Autoplay trotz muted (selten) + }) + } + } + p.one('loadedmetadata', () => { if ((p as any).isDisposed?.()) return - if (t > 0) p.currentTime(t) - if (wasPlaying) { - const ret = p.play?.() - if (ret && typeof (ret as any).catch === 'function') { - ;(ret as Promise).catch(() => {}) - } - } - }) - }, [src]) - // ✅ bei Größenwechsel kurz resize triggern (hilft manchmal) + // bei HLS live nicht versuchen zu seeken + if (t > 0 && media.type !== 'application/x-mpegURL') p.currentTime(t) + + tryPlay() + }) + + // zusätzlich sofort versuchen (hilft je nach Browser/Cache) + tryPlay() + }, [mounted, media.src, media.type]) + + + // ✅ Resize triggern bei expand/collapse React.useEffect(() => { const p = playerRef.current if (!p || (p as any).isDisposed?.()) return queueMicrotask(() => p.trigger('resize')) }, [expanded]) - return ( - -
-
{title}
+ if (!mounted) return null + + const mini = !expanded + + const footerRight = ( +
+ + + + + + + +
+ ) + + return createPortal( + <> + {expanded && ( + -
- - + } + footer={ +
+
+ Status: {job.status} + {job.output ? • {job.output} : null} +
+ + {/* Buttons primär im Mini-Player */} + {mini ? footerRight : null} +
+ } + grayBody={false} + > +
+
+
- } - footer={ -
-
- Status: {job.status} - {job.output ? • {job.output} : null} -
- {job.output ? ( - - ) : null} -
- } - grayBody={false} - > -
-
-
-
-
- + + , + document.body ) } diff --git a/frontend/src/components/ui/RecorderSettings.tsx b/frontend/src/components/ui/RecorderSettings.tsx index ad2b275..5e0f275 100644 --- a/frontend/src/components/ui/RecorderSettings.tsx +++ b/frontend/src/components/ui/RecorderSettings.tsx @@ -14,6 +14,9 @@ type RecorderSettings = { // ✅ neue Optionen autoAddToDownloadList?: boolean autoStartAddedDownloads?: boolean + + // ✅ Chaturbate Online-Rooms API (Backend pollt, sobald aktiviert) + useChaturbateApi?: boolean } const DEFAULTS: RecorderSettings = { @@ -25,6 +28,8 @@ const DEFAULTS: RecorderSettings = { // ✅ defaults für switches autoAddToDownloadList: true, autoStartAddedDownloads: true, + + useChaturbateApi: false, } export default function RecorderSettings() { @@ -46,11 +51,14 @@ export default function RecorderSettings() { setValue({ recordDir: (data.recordDir || DEFAULTS.recordDir).toString(), doneDir: (data.doneDir || DEFAULTS.doneDir).toString(), - ffmpegPath: (data.ffmpegPath ?? DEFAULTS.ffmpegPath).toString(), + ffmpegPath: String(data.ffmpegPath ?? DEFAULTS.ffmpegPath ?? ''), + // ✅ falls backend die Felder noch nicht hat -> defaults nutzen autoAddToDownloadList: data.autoAddToDownloadList ?? DEFAULTS.autoAddToDownloadList, autoStartAddedDownloads: data.autoStartAddedDownloads ?? DEFAULTS.autoStartAddedDownloads, + + useChaturbateApi: data.useChaturbateApi ?? DEFAULTS.useChaturbateApi, }) }) .catch(() => { @@ -108,6 +116,8 @@ export default function RecorderSettings() { const autoAddToDownloadList = !!value.autoAddToDownloadList const autoStartAddedDownloads = autoAddToDownloadList ? !!value.autoStartAddedDownloads : false + const useChaturbateApi = !!value.useChaturbateApi + setSaving(true) try { const res = await fetch('/api/settings', { @@ -117,8 +127,10 @@ export default function RecorderSettings() { recordDir, doneDir, ffmpegPath, - autoAddToDownloadList: value.autoAddToDownloadList, - autoStartAddedDownloads: value.autoStartAddedDownloads, + autoAddToDownloadList, + autoStartAddedDownloads, + + useChaturbateApi, }), }) if (!res.ok) { @@ -126,6 +138,7 @@ export default function RecorderSettings() { throw new Error(t || `HTTP ${res.status}`) } setMsg('✅ Gespeichert.') + window.dispatchEvent(new CustomEvent('recorder-settings-updated')) } catch (e: any) { setErr(e?.message ?? String(e)) } finally { @@ -236,6 +249,13 @@ export default function RecorderSettings() { label="Hinzugefügte Downloads automatisch starten" description="Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)." /> + + setValue((v) => ({ ...v, useChaturbateApi: checked }))} + label="Chaturbate API" + description="Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models." + />
diff --git a/frontend/src/components/ui/RunningDownloads.tsx b/frontend/src/components/ui/RunningDownloads.tsx index 9f2ba81..ae47cf5 100644 --- a/frontend/src/components/ui/RunningDownloads.tsx +++ b/frontend/src/components/ui/RunningDownloads.tsx @@ -1,15 +1,21 @@ // RunningDownloads.tsx 'use client' -import { useEffect, useMemo, useState } from 'react' +import { useMemo } from 'react' import Table, { type Column } from './Table' import Card from './Card' import Button from './Button' import ModelPreview from './ModelPreview' +import WaitingModelsTable, { type WaitingModelRow } from './WaitingModelsTable' import type { RecordJob } from '../../types' +type PendingWatchedRoom = WaitingModelRow & { + currentShow: string // public / private / hidden / away / unknown +} + type Props = { jobs: RecordJob[] + pending?: PendingWatchedRoom[] onOpenPlayer: (job: RecordJob) => void onStopJob: (id: string) => void } @@ -49,24 +55,13 @@ const runtimeOf = (j: RecordJob) => { return formatDuration(end - start) } -export default function RunningDownloads({ jobs, onOpenPlayer, onStopJob }: Props) { - // globaler Tick für alle Thumbnails - const [thumbTick, setThumbTick] = useState(0) - - useEffect(() => { - const id = window.setInterval(() => { - setThumbTick((t) => t + 1) - }, 5000) // alle 5s - - return () => window.clearInterval(id) - }, []) - +export default function RunningDownloads({ jobs, pending = [], onOpenPlayer, onStopJob }: Props) { const columns = useMemo[]>(() => { return [ { key: 'preview', header: 'Vorschau', - cell: (j) => , + cell: (j) => , }, { key: 'model', @@ -125,105 +120,127 @@ export default function RunningDownloads({ jobs, onOpenPlayer, onStopJob }: Prop ), }, ] - }, [onStopJob, thumbTick]) + }, [onStopJob]) - if (jobs.length === 0) { + if (jobs.length === 0 && pending.length === 0) { return ( -
- Keine laufenden Downloads. -
+
Keine laufenden Downloads.
) } return ( <> - {/* ✅ Mobile: Cards */} -
- {jobs.map((j) => { - const model = modelNameFromOutput(j.output) - const file = baseName(j.output || '') - const dur = runtimeOf(j) - - return ( -
onOpenPlayer(j)} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === ' ') onOpenPlayer(j) - }} - > - -
-
- {model} -
-
- {file || '—'} -
-
- - -
- } - > -
-
e.stopPropagation()}> - -
- -
-
- Status: {j.status} - - Dauer: {dur} -
- - {j.sourceUrl ? ( - e.stopPropagation()} - > - {j.sourceUrl} - - ) : null} -
-
- + {pending.length > 0 && ( + +
+ Online (wartend – Download startet nur bei public) +
+
{pending.length}
- ) - })} -
+ } + > + +
+ )} - {/* ✅ Desktop/Tablet: Tabelle */} -
-
r.id} - striped - fullWidth - onRowClick={onOpenPlayer} - /> - + {jobs.length === 0 && pending.length > 0 && ( + +
+ Kein aktiver Download – wartet auf public. +
+
+ )} + + {jobs.length > 0 && ( + <> + {/* ✅ Mobile: Cards */} +
+ {jobs.map((j) => { + const model = modelNameFromOutput(j.output) + const file = baseName(j.output || '') + const dur = runtimeOf(j) + + return ( +
onOpenPlayer(j)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenPlayer(j) + }} + > + +
+
{model}
+
{file || '—'}
+
+ + +
+ } + > +
+
e.stopPropagation()}> + +
+ +
+
+ Status: {j.status} + + Dauer: {dur} +
+ + {j.sourceUrl ? ( + e.stopPropagation()} + > + {j.sourceUrl} + + ) : null} +
+
+ +
+ ) + })} + + + {/* ✅ Desktop/Tablet: Tabelle */} +
+
r.id} + striped + fullWidth + onRowClick={onOpenPlayer} + /> + + + )} ) } diff --git a/frontend/src/components/ui/Table.tsx b/frontend/src/components/ui/Table.tsx index d04402f..69f7f11 100644 --- a/frontend/src/components/ui/Table.tsx +++ b/frontend/src/components/ui/Table.tsx @@ -1,7 +1,13 @@ +'use client' + import * as React from 'react' +import { ChevronDownIcon } from '@heroicons/react/20/solid' type Align = 'left' | 'center' | 'right' +export type SortDirection = 'asc' | 'desc' +export type SortState = { key: string; direction: SortDirection } | null + export type Column = { key: string header: React.ReactNode @@ -9,12 +15,24 @@ export type Column = { align?: Align className?: string headerClassName?: string + /** Wenn gesetzt: so wird die Zelle gerendert */ cell?: (row: T, rowIndex: number) => React.ReactNode /** Standard: row[col.key] */ accessor?: (row: T) => React.ReactNode /** Optional: sr-only Header (z.B. für Action-Spalte) */ srOnlyHeader?: boolean + + /** Sortieren aktivieren (Header wird klickbar) */ + sortable?: boolean + /** + * Wert, nach dem sortiert werden soll (empfohlen!), + * z.B. number/string/Date/boolean. + * Fallback ist row[col.key]. + */ + sortValue?: (row: T) => string | number | boolean | Date | null | undefined + /** Optional: komplett eigene Vergleichsfunktion */ + sortFn?: (a: T, b: T) => number } export type TableProps = { @@ -40,9 +58,21 @@ export type TableProps = { className?: string onRowClick?: (row: T) => void - onRowContextMenu?: (row: T, e: React.MouseEvent) => void + /** + * Controlled Sorting: + * - sort: aktueller Sort-Status + * - onSortChange: wird bei Klick auf Header aufgerufen + */ + sort?: SortState + onSortChange?: (next: SortState) => void + + /** + * Uncontrolled Sorting: + * Initiale Sortierung (wenn sort nicht gesetzt ist) + */ + defaultSort?: SortState } function cn(...parts: Array) { @@ -55,6 +85,22 @@ function alignTd(a?: Align) { return 'text-left' } +function justifyForAlign(a?: Align) { + if (a === 'center') return 'justify-center' + if (a === 'right') return 'justify-end' + return 'justify-start' +} + +function normalizeSortValue(v: any): { isNull: boolean; kind: 'number' | 'string'; value: number | string } { + if (v === null || v === undefined) return { isNull: true, kind: 'string', value: '' } + if (v instanceof Date) return { isNull: false, kind: 'number', value: v.getTime() } + if (typeof v === 'number') return { isNull: false, kind: 'number', value: v } + if (typeof v === 'boolean') return { isNull: false, kind: 'number', value: v ? 1 : 0 } + if (typeof v === 'bigint') return { isNull: false, kind: 'number', value: Number(v) } + // strings & sonstiges + return { isNull: false, kind: 'string', value: String(v).toLocaleLowerCase() } +} + export default function Table({ columns, rows, @@ -71,11 +117,60 @@ export default function Table({ emptyLabel = 'Keine Daten vorhanden.', className, onRowClick, - onRowContextMenu + onRowContextMenu, + sort, + onSortChange, + defaultSort = null, }: TableProps) { const cellY = compact ? 'py-2' : 'py-4' const headY = compact ? 'py-3' : 'py-3.5' + const isControlled = sort !== undefined + const [internalSort, setInternalSort] = React.useState(defaultSort) + const sortState = isControlled ? sort! : internalSort + + const setSortState = React.useCallback( + (next: SortState) => { + if (!isControlled) setInternalSort(next) + onSortChange?.(next) + }, + [isControlled, onSortChange] + ) + + const sortedRows = React.useMemo(() => { + if (!sortState) return rows + const col = columns.find((c) => c.key === sortState.key) + if (!col) return rows + + const dirMul = sortState.direction === 'asc' ? 1 : -1 + + const decorated = rows.map((r, i) => ({ r, i })) + decorated.sort((x, y) => { + let res = 0 + + if (col.sortFn) { + res = col.sortFn(x.r, y.r) + } else { + const ax = col.sortValue ? col.sortValue(x.r) : (x.r as any)?.[col.key] + const by = col.sortValue ? col.sortValue(y.r) : (y.r as any)?.[col.key] + + const na = normalizeSortValue(ax) + const nb = normalizeSortValue(by) + + // nulls immer nach hinten + if (na.isNull && !nb.isNull) res = 1 + else if (!na.isNull && nb.isNull) res = -1 + else if (na.kind === 'number' && nb.kind === 'number') res = na.value < nb.value ? -1 : na.value > nb.value ? 1 : 0 + else res = String(na.value).localeCompare(String(nb.value), undefined, { numeric: true }) + } + + if (res === 0) return x.i - y.i // stable + return res * dirMul + }) + + return decorated.map((d) => d.r) + }, [rows, columns, sortState]) + return (
{(title || description || actions) && ( @@ -112,71 +207,109 @@ export default function Table({
- {columns.map((col) => ( - - ))} + {columns.map((col) => { + const isSorted = !!sortState && sortState.key === col.key + const dir = isSorted ? sortState!.direction : undefined + const ariaSort = + col.sortable && !col.srOnlyHeader + ? isSorted + ? dir === 'asc' + ? 'ascending' + : 'descending' + : 'none' + : undefined + + const nextSort = () => { + if (!col.sortable || col.srOnlyHeader) return + if (!isSorted) return setSortState({ key: col.key, direction: 'asc' }) + if (dir === 'asc') return setSortState({ key: col.key, direction: 'desc' }) + return setSortState(null) + } + + return ( + + ) + })} {isLoading ? ( - - ) : rows.length === 0 ? ( + ) : sortedRows.length === 0 ? ( - ) : ( - rows.map((row, rowIndex) => { - const key = getRowKey - ? getRowKey(row, rowIndex) - : String(rowIndex) + sortedRows.map((row, rowIndex) => { + const key = getRowKey ? getRowKey(row, rowIndex) : String(rowIndex) return ( onRowClick?.(row)} onContextMenu={ @@ -202,7 +335,6 @@ export default function Table({ 'px-3 text-sm whitespace-nowrap', alignTd(col.align), col.className, - // “Primäre” Spalte wirkt wie in den Beispielen: etwas stärker col.key === columns[0]?.key ? 'font-medium text-gray-900 dark:text-white' : 'text-gray-500 dark:text-gray-400' diff --git a/frontend/src/components/ui/WaitingModelsTable.tsx b/frontend/src/components/ui/WaitingModelsTable.tsx new file mode 100644 index 0000000..18f2566 --- /dev/null +++ b/frontend/src/components/ui/WaitingModelsTable.tsx @@ -0,0 +1,91 @@ +// WaitingModelsTable.tsx +'use client' + +import { useMemo } from 'react' +import Table, { type Column } from './Table' + +export type WaitingModelRow = { + id: string + modelKey: string + url: string + currentShow?: string // public / private / hidden / away / unknown +} + +type Props = { + models: WaitingModelRow[] +} + +export default function WaitingModelsTable({ models }: Props) { + const columns = useMemo[]>(() => { + return [ + { + key: 'model', + header: 'Model', + cell: (m) => ( + + {m.modelKey} + + ), + }, + { + key: 'status', + header: 'Status', + cell: (m) => {m.currentShow || 'unknown'}, + }, + { + key: 'open', + header: 'Öffnen', + srOnlyHeader: true, + align: 'right', + cell: (m) => ( + e.stopPropagation()} + > + Öffnen + + ), + }, + ] + }, []) + + if (models.length === 0) return null + + return ( + <> + {/* ✅ Mobile: kompakte Liste */} +
+ {models.map((m) => ( +
+
+
{m.modelKey}
+
+ Status: {m.currentShow || 'unknown'} +
+
+ + + Öffnen + +
+ ))} +
+ + {/* ✅ Desktop/Tablet: Tabelle */} +
+
- {col.srOnlyHeader ? ( - {col.header} - ) : ( - col.header - )} - + {col.srOnlyHeader ? ( + {col.header} + ) : col.sortable ? ( + + ) : ( + col.header + )} +
+ Lädt…
+ {emptyLabel}
r.id} striped fullWidth /> + + + ) +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index f73976e..aa1f025 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -10,9 +10,10 @@ export default defineConfig({ emptyOutDir: true, }, server: { + host: true, // oder '0.0.0.0' proxy: { '/api': { - target: 'http://localhost:8080', + target: 'http://10.0.1.25:9999', changeOrigin: true, }, },