vod frog, frog with the vods
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

fix Safari: prefer native HLS for Opus support, fix event listener ordering, add web fonts, fix profile route prerender

goose.art dfef0f8f 22cc0ed6

+4329 -3637
+50 -20
.svelte-kit/ambient.d.ts
··· 39 39 */ 40 40 declare module '$env/static/private' { 41 41 export const NVM_INC: string; 42 - export const ZEROBREW_PREFIX: string; 43 42 export const MANPATH: string; 43 + export const ZEROBREW_PREFIX: string; 44 44 export const GHOSTTY_RESOURCES_DIR: string; 45 45 export const TERM_PROGRAM: string; 46 46 export const NODE: string; 47 47 export const SSL_CERT_FILE: string; 48 48 export const ZEROBREW_BIN: string; 49 + export const INIT_CWD: string; 50 + export const NVM_CD_FLAGS: string; 49 51 export const _P9K_TTY: string; 50 - export const NVM_CD_FLAGS: string; 51 52 export const SHELL: string; 52 53 export const TERM: string; 53 - export const HOMEBREW_REPOSITORY: string; 54 54 export const CURL_CA_BUNDLE: string; 55 + export const HOMEBREW_REPOSITORY: string; 55 56 export const TMPDIR: string; 57 + export const npm_config_global_prefix: string; 56 58 export const TERM_PROGRAM_VERSION: string; 59 + export const COLOR: string; 60 + export const npm_config_noproxy: string; 57 61 export const npm_config_local_prefix: string; 58 62 export const ZSH: string; 59 63 export const NVM_DIR: string; 60 - export const ZEROBREW_ROOT: string; 61 64 export const USER: string; 65 + export const ZEROBREW_ROOT: string; 62 66 export const LS_COLORS: string; 67 + export const COMMAND_MODE: string; 63 68 export const OPENAI_API_KEY: string; 64 - export const COMMAND_MODE: string; 69 + export const npm_config_globalconfig: string; 65 70 export const ENVMAN_LOAD: string; 66 71 export const SSH_AUTH_SOCK: string; 67 72 export const __CF_USER_TEXT_ENCODING: string; 68 73 export const npm_execpath: string; 69 74 export const PAGER: string; 75 + export const TMUX: string; 70 76 export const LSCOLORS: string; 71 77 export const PATH: string; 72 78 export const npm_package_json: string; 79 + export const npm_config_engine_strict: string; 73 80 export const _: string; 81 + export const GHOSTTY_SHELL_FEATURES: string; 74 82 export const LaunchInstanceID: string; 75 - export const GHOSTTY_SHELL_FEATURES: string; 83 + export const npm_config_userconfig: string; 84 + export const npm_config_init_module: string; 76 85 export const __CFBundleIdentifier: string; 77 86 export const npm_command: string; 78 87 export const PWD: string; 79 88 export const npm_lifecycle_event: string; 89 + export const EDITOR: string; 80 90 export const P9K_SSH: string; 81 91 export const npm_package_name: string; 92 + export const LANG: string; 82 93 export const P9K_TTY: string; 83 - export const LANG: string; 94 + export const npm_config_npm_version: string; 95 + export const TMUX_PANE: string; 84 96 export const XPC_FLAGS: string; 97 + export const npm_config_node_gyp: string; 85 98 export const ZEROBREW_DIR: string; 86 99 export const npm_package_version: string; 87 100 export const SSL_CERT_DIR: string; ··· 91 104 export const TERMINFO: string; 92 105 export const HOMEBREW_PREFIX: string; 93 106 export const CLAUDE_KEY: string; 107 + export const npm_config_cache: string; 94 108 export const LESS: string; 95 109 export const LOGNAME: string; 96 110 export const npm_lifecycle_script: string; 97 111 export const XDG_DATA_DIRS: string; 98 112 export const GHOSTTY_BIN_DIR: string; 99 - export const NVM_BIN: string; 100 113 export const BUN_INSTALL: string; 114 + export const NVM_BIN: string; 101 115 export const PKG_CONFIG_PATH: string; 102 116 export const npm_config_user_agent: string; 103 - export const INFOPATH: string; 104 117 export const HOMEBREW_CELLAR: string; 105 - export const _P9K_SSH_TTY: string; 118 + export const INFOPATH: string; 106 119 export const DISPLAY: string; 120 + export const _P9K_SSH_TTY: string; 107 121 export const OSLogRateLimit: string; 108 122 export const SECURITYSESSIONID: string; 109 123 export const npm_node_execpath: string; 124 + export const npm_config_prefix: string; 110 125 export const COLORTERM: string; 111 126 export const NODE_ENV: string; 112 127 } ··· 196 211 declare module '$env/dynamic/private' { 197 212 export const env: { 198 213 NVM_INC: string; 199 - ZEROBREW_PREFIX: string; 200 214 MANPATH: string; 215 + ZEROBREW_PREFIX: string; 201 216 GHOSTTY_RESOURCES_DIR: string; 202 217 TERM_PROGRAM: string; 203 218 NODE: string; 204 219 SSL_CERT_FILE: string; 205 220 ZEROBREW_BIN: string; 221 + INIT_CWD: string; 222 + NVM_CD_FLAGS: string; 206 223 _P9K_TTY: string; 207 - NVM_CD_FLAGS: string; 208 224 SHELL: string; 209 225 TERM: string; 210 - HOMEBREW_REPOSITORY: string; 211 226 CURL_CA_BUNDLE: string; 227 + HOMEBREW_REPOSITORY: string; 212 228 TMPDIR: string; 229 + npm_config_global_prefix: string; 213 230 TERM_PROGRAM_VERSION: string; 231 + COLOR: string; 232 + npm_config_noproxy: string; 214 233 npm_config_local_prefix: string; 215 234 ZSH: string; 216 235 NVM_DIR: string; 217 - ZEROBREW_ROOT: string; 218 236 USER: string; 237 + ZEROBREW_ROOT: string; 219 238 LS_COLORS: string; 239 + COMMAND_MODE: string; 220 240 OPENAI_API_KEY: string; 221 - COMMAND_MODE: string; 241 + npm_config_globalconfig: string; 222 242 ENVMAN_LOAD: string; 223 243 SSH_AUTH_SOCK: string; 224 244 __CF_USER_TEXT_ENCODING: string; 225 245 npm_execpath: string; 226 246 PAGER: string; 247 + TMUX: string; 227 248 LSCOLORS: string; 228 249 PATH: string; 229 250 npm_package_json: string; 251 + npm_config_engine_strict: string; 230 252 _: string; 253 + GHOSTTY_SHELL_FEATURES: string; 231 254 LaunchInstanceID: string; 232 - GHOSTTY_SHELL_FEATURES: string; 255 + npm_config_userconfig: string; 256 + npm_config_init_module: string; 233 257 __CFBundleIdentifier: string; 234 258 npm_command: string; 235 259 PWD: string; 236 260 npm_lifecycle_event: string; 261 + EDITOR: string; 237 262 P9K_SSH: string; 238 263 npm_package_name: string; 264 + LANG: string; 239 265 P9K_TTY: string; 240 - LANG: string; 266 + npm_config_npm_version: string; 267 + TMUX_PANE: string; 241 268 XPC_FLAGS: string; 269 + npm_config_node_gyp: string; 242 270 ZEROBREW_DIR: string; 243 271 npm_package_version: string; 244 272 SSL_CERT_DIR: string; ··· 248 276 TERMINFO: string; 249 277 HOMEBREW_PREFIX: string; 250 278 CLAUDE_KEY: string; 279 + npm_config_cache: string; 251 280 LESS: string; 252 281 LOGNAME: string; 253 282 npm_lifecycle_script: string; 254 283 XDG_DATA_DIRS: string; 255 284 GHOSTTY_BIN_DIR: string; 256 - NVM_BIN: string; 257 285 BUN_INSTALL: string; 286 + NVM_BIN: string; 258 287 PKG_CONFIG_PATH: string; 259 288 npm_config_user_agent: string; 260 - INFOPATH: string; 261 289 HOMEBREW_CELLAR: string; 262 - _P9K_SSH_TTY: string; 290 + INFOPATH: string; 263 291 DISPLAY: string; 292 + _P9K_SSH_TTY: string; 264 293 OSLogRateLimit: string; 265 294 SECURITYSESSIONID: string; 266 295 npm_node_execpath: string; 296 + npm_config_prefix: string; 267 297 COLORTERM: string; 268 298 NODE_ENV: string; 269 299 [key: `PUBLIC_${string}`]: undefined;
+4 -2
.svelte-kit/generated/client-optimized/app.js
··· 3 3 export const nodes = [ 4 4 () => import('./nodes/0'), 5 5 () => import('./nodes/1'), 6 - () => import('./nodes/2') 6 + () => import('./nodes/2'), 7 + () => import('./nodes/3') 7 8 ]; 8 9 9 10 export const server_loads = []; 10 11 11 12 export const dictionary = { 12 - "/": [2] 13 + "/": [2], 14 + "/profile/[handle]": [3] 13 15 }; 14 16 15 17 export const hooks = {
+3
.svelte-kit/generated/client-optimized/nodes/3.js
··· 1 + import * as universal from "../../../../src/routes/profile/[handle]/+page.ts"; 2 + export { universal }; 3 + export { default as component } from "../../../../src/routes/profile/[handle]/+page.svelte";
+4 -2
.svelte-kit/generated/client/app.js
··· 3 3 export const nodes = [ 4 4 () => import('./nodes/0'), 5 5 () => import('./nodes/1'), 6 - () => import('./nodes/2') 6 + () => import('./nodes/2'), 7 + () => import('./nodes/3') 7 8 ]; 8 9 9 10 export const server_loads = []; 10 11 11 12 export const dictionary = { 12 - "/": [2] 13 + "/": [2], 14 + "/profile/[handle]": [3] 13 15 }; 14 16 15 17 export const hooks = {
+3
.svelte-kit/generated/client/nodes/3.js
··· 1 + import * as universal from "../../../../src/routes/profile/[handle]/+page.ts"; 2 + export { universal }; 3 + export { default as component } from "../../../../src/routes/profile/[handle]/+page.svelte";
+1 -1
.svelte-kit/generated/server/internal.js
··· 25 25 app: ({ head, body, assets, nonce, env }) => "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"/frogicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>vod frog</title>\n " + head + "\n </head>\n <body>\n <div style=\"display: contents\">" + body + "</div>\n </body>\n</html>\n", 26 26 error: ({ status, message }) => "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\" />\n\t\t<title>" + message + "</title>\n\n\t\t<style>\n\t\t\tbody {\n\t\t\t\t--bg: white;\n\t\t\t\t--fg: #222;\n\t\t\t\t--divider: #ccc;\n\t\t\t\tbackground: var(--bg);\n\t\t\t\tcolor: var(--fg);\n\t\t\t\tfont-family:\n\t\t\t\t\tsystem-ui,\n\t\t\t\t\t-apple-system,\n\t\t\t\t\tBlinkMacSystemFont,\n\t\t\t\t\t'Segoe UI',\n\t\t\t\t\tRoboto,\n\t\t\t\t\tOxygen,\n\t\t\t\t\tUbuntu,\n\t\t\t\t\tCantarell,\n\t\t\t\t\t'Open Sans',\n\t\t\t\t\t'Helvetica Neue',\n\t\t\t\t\tsans-serif;\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t\tjustify-content: center;\n\t\t\t\theight: 100vh;\n\t\t\t\tmargin: 0;\n\t\t\t}\n\n\t\t\t.error {\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t\tmax-width: 32rem;\n\t\t\t\tmargin: 0 1rem;\n\t\t\t}\n\n\t\t\t.status {\n\t\t\t\tfont-weight: 200;\n\t\t\t\tfont-size: 3rem;\n\t\t\t\tline-height: 1;\n\t\t\t\tposition: relative;\n\t\t\t\ttop: -0.05rem;\n\t\t\t}\n\n\t\t\t.message {\n\t\t\t\tborder-left: 1px solid var(--divider);\n\t\t\t\tpadding: 0 0 0 1rem;\n\t\t\t\tmargin: 0 0 0 1rem;\n\t\t\t\tmin-height: 2.5rem;\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t}\n\n\t\t\t.message h1 {\n\t\t\t\tfont-weight: 400;\n\t\t\t\tfont-size: 1em;\n\t\t\t\tmargin: 0;\n\t\t\t}\n\n\t\t\t@media (prefers-color-scheme: dark) {\n\t\t\t\tbody {\n\t\t\t\t\t--bg: #222;\n\t\t\t\t\t--fg: #ddd;\n\t\t\t\t\t--divider: #666;\n\t\t\t\t}\n\t\t\t}\n\t\t</style>\n\t</head>\n\t<body>\n\t\t<div class=\"error\">\n\t\t\t<span class=\"status\">" + status + "</span>\n\t\t\t<div class=\"message\">\n\t\t\t\t<h1>" + message + "</h1>\n\t\t\t</div>\n\t\t</div>\n\t</body>\n</html>\n" 27 27 }, 28 - version_hash: "139m7hs" 28 + version_hash: "1gh8pzr" 29 29 }; 30 30 31 31 export async function get_hooks() {
+7 -5
.svelte-kit/non-ambient.d.ts
··· 29 29 type MatcherParam<M> = M extends (param : string) => param is (infer U extends string) ? U : string; 30 30 31 31 export interface AppTypes { 32 - RouteId(): "/"; 32 + RouteId(): "/" | "/profile" | "/profile/[handle]"; 33 33 RouteParams(): { 34 - 34 + "/profile/[handle]": { handle: string } 35 35 }; 36 36 LayoutParams(): { 37 - "/": Record<string, never> 37 + "/": { handle?: string }; 38 + "/profile": { handle?: string }; 39 + "/profile/[handle]": { handle: string } 38 40 }; 39 - Pathname(): "/"; 41 + Pathname(): "/" | `/profile/${string}` & {}; 40 42 ResolvedPathname(): `${"" | `/${string}`}${ReturnType<AppTypes['Pathname']>}`; 41 - Asset(): "/favicon.png" | "/favicon.svg" | "/frogcursor-small.png" | "/frogcursor.png" | "/frogeye.png" | "/froggie.png" | "/froggiejump.png" | "/froggiestand.png" | "/frogicon.png" | "/robots.txt" | string & {}; 43 + Asset(): "/favicon.png" | "/favicon.svg" | "/frogcursor-small.png" | "/frogcursor.png" | "/frogeye.png" | "/froggie.png" | "/froggiejump.png" | "/froggiestand.png" | "/frogicon.png" | "/leaves.png" | "/robots.txt" | string & {}; 42 44 } 43 45 }
+118 -70
.svelte-kit/output/client/.vite/manifest.json
··· 1 1 { 2 2 ".svelte-kit/generated/client-optimized/app.js": { 3 - "file": "_app/immutable/entry/app.BiVWJwsp.js", 3 + "file": "_app/immutable/entry/app.CwuxgLSd.js", 4 4 "name": "entry/app", 5 5 "src": ".svelte-kit/generated/client-optimized/app.js", 6 6 "isEntry": true, 7 7 "imports": [ 8 - "_w0kPbzMq.js", 9 - "_BcVkVDn_.js", 10 - "_mmStoiki.js", 11 - "_B43_79mg.js", 12 - "_C_B-Ij-b.js", 13 - "_C6hdjiAW.js" 8 + "_CkzjbUDB.js", 9 + "_BsDbD4Ku.js", 10 + "_DGbOEUpF.js", 11 + "_DxGD2b0U.js", 12 + "_XE2G8ySY.js", 13 + "_CFYBLbZM.js", 14 + "_Dr80VTgO.js" 14 15 ], 15 16 "dynamicImports": [ 16 17 ".svelte-kit/generated/client-optimized/nodes/0.js", 17 18 ".svelte-kit/generated/client-optimized/nodes/1.js", 18 - ".svelte-kit/generated/client-optimized/nodes/2.js" 19 + ".svelte-kit/generated/client-optimized/nodes/2.js", 20 + ".svelte-kit/generated/client-optimized/nodes/3.js" 19 21 ] 20 22 }, 21 23 ".svelte-kit/generated/client-optimized/nodes/0.js": { 22 - "file": "_app/immutable/nodes/0.D6CLfhqK.js", 24 + "file": "_app/immutable/nodes/0.Cq8Xsn4J.js", 23 25 "name": "nodes/0", 24 26 "src": ".svelte-kit/generated/client-optimized/nodes/0.js", 25 27 "isEntry": true, 26 28 "isDynamicEntry": true, 27 29 "imports": [ 28 - "_mmStoiki.js", 29 - "_w0kPbzMq.js", 30 - "_8u-mThFx.js", 31 - "_DsupRLPE.js", 32 - "_C_B-Ij-b.js" 30 + "_DGbOEUpF.js", 31 + "_CkzjbUDB.js", 32 + "_DmyE0d-6.js", 33 + "_B46dcLgj.js" 33 34 ], 34 35 "css": [ 35 - "_app/immutable/assets/0.CyGpFWYY.css" 36 + "_app/immutable/assets/0.DIlgUleF.css" 36 37 ] 37 38 }, 38 39 ".svelte-kit/generated/client-optimized/nodes/1.js": { 39 - "file": "_app/immutable/nodes/1.xyjmz21p.js", 40 + "file": "_app/immutable/nodes/1.BfJAtU5y.js", 40 41 "name": "nodes/1", 41 42 "src": ".svelte-kit/generated/client-optimized/nodes/1.js", 42 43 "isEntry": true, 43 44 "isDynamicEntry": true, 44 45 "imports": [ 45 - "_mmStoiki.js", 46 - "_DsupRLPE.js", 47 - "_w0kPbzMq.js", 48 - "_BcVkVDn_.js", 49 - "_D9RahMPT.js" 46 + "_DGbOEUpF.js", 47 + "_B46dcLgj.js", 48 + "_CkzjbUDB.js", 49 + "_BsDbD4Ku.js", 50 + "_C0nNmPgn.js" 50 51 ] 51 52 }, 52 53 ".svelte-kit/generated/client-optimized/nodes/2.js": { 53 - "file": "_app/immutable/nodes/2.D4xyri_M.js", 54 + "file": "_app/immutable/nodes/2.DCJPxWEg.js", 54 55 "name": "nodes/2", 55 56 "src": ".svelte-kit/generated/client-optimized/nodes/2.js", 56 57 "isEntry": true, 57 58 "isDynamicEntry": true, 58 59 "imports": [ 59 - "_mmStoiki.js", 60 - "_B43_79mg.js", 61 - "_w0kPbzMq.js", 62 - "_BcVkVDn_.js", 63 - "_C_B-Ij-b.js", 64 - "_8u-mThFx.js", 65 - "_C6hdjiAW.js", 66 - "_DsupRLPE.js" 60 + "_DGbOEUpF.js", 61 + "_DxGD2b0U.js", 62 + "_CkzjbUDB.js", 63 + "_BsDbD4Ku.js", 64 + "_XE2G8ySY.js", 65 + "_DmyE0d-6.js", 66 + "_D_t83wNY.js", 67 + "_Dr80VTgO.js" 67 68 ], 68 69 "css": [ 69 - "_app/immutable/assets/2.BKmFmlcI.css" 70 + "_app/immutable/assets/2.CHt1yucP.css" 70 71 ] 71 72 }, 72 - "_8u-mThFx.js": { 73 - "file": "_app/immutable/chunks/8u-mThFx.js", 74 - "name": "class", 73 + ".svelte-kit/generated/client-optimized/nodes/3.js": { 74 + "file": "_app/immutable/nodes/3.CW9t1woG.js", 75 + "name": "nodes/3", 76 + "src": ".svelte-kit/generated/client-optimized/nodes/3.js", 77 + "isEntry": true, 78 + "isDynamicEntry": true, 75 79 "imports": [ 76 - "_w0kPbzMq.js", 77 - "_C_B-Ij-b.js" 80 + "_DGbOEUpF.js", 81 + "_DxGD2b0U.js", 82 + "_CkzjbUDB.js", 83 + "_BsDbD4Ku.js", 84 + "_XE2G8ySY.js", 85 + "_DmyE0d-6.js", 86 + "_D_t83wNY.js", 87 + "_C0nNmPgn.js" 88 + ], 89 + "css": [ 90 + "_app/immutable/assets/3.CjGf6tQE.css" 78 91 ] 79 92 }, 80 - "_B43_79mg.js": { 81 - "file": "_app/immutable/chunks/B43_79mg.js", 82 - "name": "index-client", 93 + "_B46dcLgj.js": { 94 + "file": "_app/immutable/chunks/B46dcLgj.js", 95 + "name": "legacy", 83 96 "imports": [ 84 - "_w0kPbzMq.js" 97 + "_CkzjbUDB.js" 85 98 ] 86 99 }, 87 - "_BcVkVDn_.js": { 88 - "file": "_app/immutable/chunks/BcVkVDn_.js", 100 + "_BsDbD4Ku.js": { 101 + "file": "_app/immutable/chunks/BsDbD4Ku.js", 89 102 "name": "render", 90 103 "imports": [ 91 - "_w0kPbzMq.js", 92 - "_mmStoiki.js" 104 + "_CkzjbUDB.js", 105 + "_DGbOEUpF.js" 93 106 ] 94 107 }, 95 - "_C6hdjiAW.js": { 96 - "file": "_app/immutable/chunks/C6hdjiAW.js", 97 - "name": "props", 108 + "_C0nNmPgn.js": { 109 + "file": "_app/immutable/chunks/C0nNmPgn.js", 110 + "name": "entry", 98 111 "imports": [ 99 - "_w0kPbzMq.js" 112 + "_CkzjbUDB.js", 113 + "_DxGD2b0U.js" 100 114 ] 101 115 }, 102 - "_C_B-Ij-b.js": { 103 - "file": "_app/immutable/chunks/C_B-Ij-b.js", 104 - "name": "if", 116 + "_CFYBLbZM.js": { 117 + "file": "_app/immutable/chunks/CFYBLbZM.js", 118 + "name": "branches", 105 119 "imports": [ 106 - "_w0kPbzMq.js" 120 + "_CkzjbUDB.js" 107 121 ] 108 122 }, 109 - "_D9RahMPT.js": { 110 - "file": "_app/immutable/chunks/D9RahMPT.js", 111 - "name": "entry", 123 + "_CkzjbUDB.js": { 124 + "file": "_app/immutable/chunks/CkzjbUDB.js", 125 + "name": "runtime" 126 + }, 127 + "_DGbOEUpF.js": { 128 + "file": "_app/immutable/chunks/DGbOEUpF.js", 129 + "name": "disclose-version", 112 130 "imports": [ 113 - "_w0kPbzMq.js", 114 - "_B43_79mg.js" 131 + "_CkzjbUDB.js" 115 132 ] 116 133 }, 117 - "_DsupRLPE.js": { 118 - "file": "_app/immutable/chunks/DsupRLPE.js", 119 - "name": "legacy", 134 + "_D_t83wNY.js": { 135 + "file": "_app/immutable/chunks/D_t83wNY.js", 136 + "name": "FrogHeader", 120 137 "imports": [ 121 - "_w0kPbzMq.js" 138 + "_DGbOEUpF.js", 139 + "_CkzjbUDB.js", 140 + "_DmyE0d-6.js", 141 + "_XE2G8ySY.js", 142 + "_BsDbD4Ku.js" 143 + ], 144 + "css": [ 145 + "_app/immutable/assets/FrogHeader.8kzFzgPu.css" 122 146 ] 123 147 }, 124 - "_mmStoiki.js": { 125 - "file": "_app/immutable/chunks/mmStoiki.js", 126 - "name": "disclose-version", 148 + "_DmyE0d-6.js": { 149 + "file": "_app/immutable/chunks/DmyE0d-6.js", 150 + "name": "svelte-head", 151 + "imports": [ 152 + "_CkzjbUDB.js", 153 + "_CFYBLbZM.js" 154 + ] 155 + }, 156 + "_Dr80VTgO.js": { 157 + "file": "_app/immutable/chunks/Dr80VTgO.js", 158 + "name": "this", 159 + "imports": [ 160 + "_CkzjbUDB.js" 161 + ] 162 + }, 163 + "_DxGD2b0U.js": { 164 + "file": "_app/immutable/chunks/DxGD2b0U.js", 165 + "name": "index-client", 127 166 "imports": [ 128 - "_w0kPbzMq.js" 167 + "_CkzjbUDB.js" 129 168 ] 130 169 }, 131 - "_w0kPbzMq.js": { 132 - "file": "_app/immutable/chunks/w0kPbzMq.js", 133 - "name": "runtime" 170 + "_FrogHeader.8kzFzgPu.css": { 171 + "file": "_app/immutable/assets/FrogHeader.8kzFzgPu.css", 172 + "src": "_FrogHeader.8kzFzgPu.css" 173 + }, 174 + "_XE2G8ySY.js": { 175 + "file": "_app/immutable/chunks/XE2G8ySY.js", 176 + "name": "props", 177 + "imports": [ 178 + "_CkzjbUDB.js", 179 + "_CFYBLbZM.js", 180 + "_DxGD2b0U.js" 181 + ] 134 182 }, 135 183 "node_modules/@sveltejs/kit/src/runtime/client/entry.js": { 136 - "file": "_app/immutable/entry/start.YsP-T6iU.js", 184 + "file": "_app/immutable/entry/start.BUzUbSG3.js", 137 185 "name": "entry/start", 138 186 "src": "node_modules/@sveltejs/kit/src/runtime/client/entry.js", 139 187 "isEntry": true, 140 188 "imports": [ 141 - "_D9RahMPT.js" 189 + "_C0nNmPgn.js" 142 190 ] 143 191 } 144 192 }
-1
.svelte-kit/output/client/_app/immutable/assets/0.CyGpFWYY.css
··· 1 - .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-1;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;top:0;bottom:0;width:100px;z-index:100;pointer-events:none;opacity:.85}.plant-overlay.left.svelte-11afcec{left:10px}.plant-overlay.right.svelte-11afcec{right:10px}.plant-overlay.svelte-11afcec svg:where(.svelte-11afcec){width:100%;height:100%}@media(max-width:900px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
+1
.svelte-kit/output/client/_app/immutable/assets/0.DIlgUleF.css
··· 1 + .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-2;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;inset:0;z-index:-1;pointer-events:none;overflow:hidden;mix-blend-mode:multiply}.leaves.svelte-11afcec{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}@media(max-width:768px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Nunito,Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
-1
.svelte-kit/output/client/_app/immutable/assets/2.BKmFmlcI.css
··· 1 - .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-svg.svelte-7frlgw{position:absolute;inset:-8px;width:calc(100% + 16px);height:calc(100% + 16px);z-index:0;pointer-events:none}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.player-wrapper.svelte-zbxgh1{position:relative;width:100%;background:#0a182b;overflow:hidden}video.svelte-zbxgh1{width:100%;display:block;max-height:70vh}.error-overlay.svelte-zbxgh1{position:absolute;bottom:0;left:0;right:0;background:#ff3992d9;color:#ffdeed;padding:8px 12px;font-family:Fang,system-ui,sans-serif;font-size:.8rem}.card.svelte-1nxalmg{all:unset;cursor:url(../../../frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Fang,system-ui,sans-serif;font-size:1rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:6px}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.thumb-img.hidden.svelte-1nxalmg{opacity:0}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:8px 2px 0}.title.svelte-1nxalmg{margin:0;font-family:Fang,system-ui,sans-serif;font-size:.9rem;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.frog-header.svelte-1kxia9k{padding:30px 20px 10px;position:relative}.title-row.svelte-1kxia9k{display:flex;align-items:flex-end;gap:10px}.logo-text.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px}.header-frog.svelte-1kxia9k{width:clamp(60px,10vw,120px);height:auto;transform:rotate(-10deg);filter:drop-shadow(2px 3px 4px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px}.subtitle.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 100px 60px}.player-section.svelte-1uha8ag{margin-bottom:30px;padding:0 10px}.player-info.svelte-1uha8ag{display:flex;justify-content:space-between;align-items:flex-start;padding:14px 4px;gap:16px}.player-title.svelte-1uha8ag{margin:0;font-family:Fang,system-ui,sans-serif;font-size:1.2rem;color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.close-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:2px solid #39FF44;border-radius:50%;width:36px;height:36px;font-size:1rem;cursor:pointer;flex-shrink:0;font-family:Fang,system-ui,sans-serif;transition:background .15s,color .15s}.close-btn.svelte-1uha8ag:hover{background:#ff3992;border-color:#ff3992;color:#ffdeed}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:30px;padding:20px 10px}.load-more.svelte-1uha8ag{text-align:center;padding:30px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag){background:#0a182b;color:#39ff44;border:3px solid #0A182B;padding:12px 36px;border-radius:40px;font-family:PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Fang,system-ui,sans-serif;border:2px solid #FF3992}@media(max-width:768px){.app.svelte-1uha8ag{padding:0 16px 40px}.grid.svelte-1uha8ag{grid-template-columns:1fr;gap:24px;padding:10px 0}}
+1
.svelte-kit/output/client/_app/immutable/assets/2.CHt1yucP.css
··· 1 + .player-wrapper.svelte-zbxgh1{position:relative;width:100%;background:#0a182b;overflow:hidden}.player-wrapper.svelte-zbxgh1:fullscreen{display:flex;align-items:center;justify-content:center}.player-wrapper.svelte-zbxgh1:fullscreen video:where(.svelte-zbxgh1){max-height:100vh;max-width:100vw;object-fit:contain}video.svelte-zbxgh1{width:100%;display:block;max-height:70vh;cursor:pointer}.controls.svelte-zbxgh1{position:absolute;bottom:5%;left:10%;right:15%;opacity:0;transition:opacity .25s ease;pointer-events:none}.controls.visible.svelte-zbxgh1{opacity:1;pointer-events:auto}.scrub-bar.svelte-zbxgh1{position:relative;height:48px;cursor:pointer}.scrub-frog.svelte-zbxgh1{position:absolute;bottom:0;transform:translate(-50%);cursor:grab;transition:left .05s linear;z-index:2;padding:6px}.scrub-frog.svelte-zbxgh1:active{cursor:grabbing}.scrub-frog.flipped.svelte-zbxgh1{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-zbxgh1{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.5));pointer-events:none}.fullscreen-btn.svelte-zbxgh1{all:unset;position:absolute;bottom:5%;right:8%;cursor:pointer;opacity:0;transition:opacity .25s ease,transform .2s ease;z-index:5}.fullscreen-btn.visible.svelte-zbxgh1{opacity:1}.fullscreen-btn.svelte-zbxgh1:hover{transform:scale(1.15)}.frogeye.svelte-zbxgh1{width:44px;height:44px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4))}.error-overlay.svelte-zbxgh1{position:absolute;bottom:15%;left:10%;right:10%;background:#ff3992d9;color:#ffdeed;padding:8px 12px;border-radius:6px;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem}.card.svelte-1nxalmg{all:unset;cursor:url(../../../frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:8px;text-align:right}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.scrub-frog.svelte-1nxalmg{position:absolute;bottom:0%;z-index:4;pointer-events:none;transform:translate(-50%);transition:left .05s linear}.scrub-frog.flipped.svelte-1nxalmg{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-1nxalmg{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4));image-rendering:auto}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:14px 10px 8px}.title.svelte-1nxalmg{margin:0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.9rem;font-weight:700;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 clamp(24px,7vw,120px) 60px}.player-section.svelte-1uha8ag{margin-bottom:40px;margin-top:20px;padding:0 10px}.player-info.svelte-1uha8ag{padding:20px 4px}.player-title.svelte-1uha8ag{margin:0;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.4rem,3vw,2rem);color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(300px,100%),1fr));gap:clamp(32px,5vw,50px);padding:20px clamp(16px,3vw,24px)}.pagination.svelte-1uha8ag{display:flex;justify-content:center;align-items:center;gap:20px;padding:30px}.page-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:3px solid #0a182b;padding:12px 32px;border-radius:40px;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.page-btn.svelte-1uha8ag:hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.page-btn.svelte-1uha8ag:disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.page-num.svelte-1uha8ag{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #ff3992}
+1
.svelte-kit/output/client/_app/immutable/assets/3.CjGf6tQE.css
··· 1 + .profile-page.svelte-oxml5t{max-width:800px;margin:0 auto;padding:0 clamp(24px,7vw,80px) 60px}.loading.svelte-oxml5t{text-align:center;padding:60px 20px}.loading-frog.svelte-oxml5t{width:64px;height:auto;animation:svelte-oxml5t-hop .6s ease-in-out infinite alternate}@keyframes svelte-oxml5t-hop{0%{transform:translateY(0)}to{transform:translateY(-12px)}}.loading-text.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.2rem;color:#0a182b;margin-top:12px}.error.svelte-oxml5t{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:20px 0;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #FF3992}.profile-layout.svelte-oxml5t{display:flex;flex-direction:column;gap:24px}.banner-img.svelte-oxml5t{width:100%;display:block;aspect-ratio:3 / 1;object-fit:cover}.profile-card-area.svelte-oxml5t{margin-top:-20px}.profile-card.svelte-oxml5t{display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px}.avatar-wrapper.svelte-oxml5t{width:clamp(80px,15vw,120px);margin-bottom:8px}.avatar.svelte-oxml5t{width:100%;display:block;aspect-ratio:1;object-fit:cover;border-radius:0}.display-name.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.8rem,4vw,2.8rem);color:#0a182b;margin:0;line-height:1.1}.handle.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:1rem;color:#0a182b;opacity:.7;margin:0}.description.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.95rem;color:#0a182b;margin:8px 0;max-width:500px;line-height:1.5}.stats.svelte-oxml5t{display:flex;gap:clamp(16px,4vw,32px);margin:12px 0}.stat.svelte-oxml5t{display:flex;flex-direction:column;align-items:center}.stat-num.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#0a182b;font-weight:700}.stat-label.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#0a182b;opacity:.6}.profile-link.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;margin-top:8px;transition:color .15s}.profile-link.svelte-oxml5t:hover{color:#ff3992}.back-link.svelte-oxml5t{text-align:center;padding:30px}.back-link.svelte-oxml5t a:where(.svelte-oxml5t){font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.back-link.svelte-oxml5t a:where(.svelte-oxml5t):hover{color:#ff3992}
+1
.svelte-kit/output/client/_app/immutable/assets/FrogHeader.8kzFzgPu.css
··· 1 + .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-clipped.svelte-7frlgw{position:relative}.wavy-fill.svelte-7frlgw{position:absolute;inset:0;z-index:0}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.wavy-stroke.svelte-7frlgw{position:absolute;inset:0;width:100%;height:100%;z-index:3;pointer-events:none;overflow:visible}.frog-header.svelte-1kxia9k{padding:30px 20px;position:relative}.title-area.svelte-1kxia9k{position:relative;display:inline-block}.logo-link.svelte-1kxia9k{text-decoration:none;color:inherit}.logo-text.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px;position:relative;z-index:1}.header-frog.svelte-1kxia9k{position:absolute;right:-80px;top:-60px;width:clamp(120px,18vw,220px);height:auto;z-index:2;transform:rotate(-10deg);filter:drop-shadow(2px 4px 6px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px;position:relative;z-index:0}.subtitle-link.svelte-1kxia9k{color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.subtitle-link.svelte-1kxia9k:hover{color:#ff3992}.subtitle.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}.header-frog.svelte-1kxia9k{right:-100px;top:-20px}}
-2
.svelte-kit/output/client/_app/immutable/chunks/8u-mThFx.js
··· 1 - import{g as p,E as v,c as N,$ as T,a0 as b,h as a,a1 as m,a2 as o,n as E,l as c,f as y,a3 as F}from"./w0kPbzMq.js";import{B as h}from"./C_B-Ij-b.js";function _(i,s,...e){var t=new h(i);p(()=>{const l=s()??null;t.ensure(l,l&&(n=>l(n,...e)))},v)}function O(i,s){let e=null,t=a;var l;if(a){e=y;for(var n=F(document.head);n!==null&&(n.nodeType!==m||n.data!==i);)n=o(n);if(n===null)E(!1);else{var r=o(n);n.remove(),c(r)}}a||(l=document.head.appendChild(N()));try{p(()=>s(l),T|b)}finally{t&&(E(!0),c(e))}}const d=[...` 2 - \r\f \v\uFEFF`];function w(i,s,e){var t=i==null?"":""+i;if(s&&(t=t?t+" "+s:s),e){for(var l of Object.keys(e))if(e[l])t=t?t+" "+l:l;else if(t.length)for(var n=l.length,r=0;(r=t.indexOf(l,r))>=0;){var f=r+n;(r===0||d.includes(t[r-1]))&&(f===t.length||d.includes(t[f]))?t=(r===0?"":t.substring(0,r))+t.substring(f+1):r=f}}return t===""?null:t}function R(i,s){return i==null?null:String(i)}function D(i,s,e,t,l,n){var r=i.__className;if(a||r!==e||r===void 0){var f=w(e,t,n);(!a||f!==i.getAttribute("class"))&&(f==null?i.removeAttribute("class"):i.className=f),i.__className=e}else if(n&&l!==n)for(var u in n){var g=!!n[u];(l==null||g!==!!l[u])&&i.classList.toggle(u,g)}return n}export{_ as a,O as h,D as s,R as t};
-1
.svelte-kit/output/client/_app/immutable/chunks/B43_79mg.js
··· 1 - import{u as l,o as t,q as u,t as o}from"./w0kPbzMq.js";function c(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function a(e){t===null&&c(),u&&t.l!==null?i(t).m.push(e):l(()=>{const n=o(e);if(typeof n=="function")return n})}function f(e){t===null&&c(),a(()=>()=>o(e))}function i(e){var n=e.l;return n.u??={a:[],b:[],m:[]}}export{f as a,a as o};
+1
.svelte-kit/output/client/_app/immutable/chunks/B46dcLgj.js
··· 1 + import{e}from"./CkzjbUDB.js";e();
-2
.svelte-kit/output/client/_app/immutable/chunks/BcVkVDn_.js
··· 1 - import{ab as Z,A as j,w as ee,ac as z,t as te,ad as Y,ae as T,f as g,h as v,x as m,af as P,g as re,i as se,ag as ie,ah as V,b as p,c as U,p as x,a as W,m as ae,ai as ne,aj as N,ak as D,al as q,am as fe,an as he,ao as J,o as X,ap as oe,d as F,l as O,aq as le,k as de,ar as S,E as ce,a0 as ue,as as _e,at as pe,au as ge,av as ve,aw as ye,ax as L,a3 as be,a1 as G,ay as me,a2 as Ee,az as M,n as R,aA as we,aB as Te,aC as Se,aD as Re,U as Ae,aE as Ne,aF as De,X as Oe}from"./w0kPbzMq.js";import{b as ke}from"./mmStoiki.js";function xe(t){let e=0,r=z(0),i;return()=>{Z()&&(j(r),ee(()=>(e===0&&(i=te(()=>t(()=>Y(r)))),e+=1,()=>{T(()=>{e-=1,e===0&&(i?.(),i=void 0,Y(r))})})))}}var Fe=ce|ue;function Le(t,e,r,i){new Me(t,e,r,i)}class Me{parent;is_pending=!1;transform_error;#t;#_=v?g:null;#i;#o;#e;#a=null;#r=null;#s=null;#n=null;#l=0;#h=0;#d=!1;#p=new Set;#g=new Set;#f=null;#b=xe(()=>(this.#f=z(this.#l),()=>{this.#f=null}));constructor(e,r,i,a){this.#t=e,this.#i=r,this.#o=s=>{var n=m;n.b=this,n.f|=P,i(s)},this.parent=m.b,this.transform_error=a??this.parent?.transform_error??(s=>s),this.#e=re(()=>{if(v){const s=this.#_;se();const n=s.data===ie;if(s.data.startsWith(V)){const f=JSON.parse(s.data.slice(V.length));this.#E(f)}else n?this.#w():this.#m()}else this.#v()},Fe),v&&(this.#t=g)}#m(){try{this.#a=p(()=>this.#o(this.#t))}catch(e){this.error(e)}}#E(e){const r=this.#i.failed;r&&(this.#s=p(()=>{r(this.#t,()=>e,()=>()=>{})}))}#w(){const e=this.#i.pending;e&&(this.is_pending=!0,this.#r=p(()=>e(this.#t)),T(()=>{var r=this.#n=document.createDocumentFragment(),i=U();r.append(i),this.#a=this.#u(()=>p(()=>this.#o(i))),this.#h===0&&(this.#t.before(r),this.#n=null,x(this.#r,()=>{this.#r=null}),this.#c(W))}))}#v(){try{if(this.is_pending=this.has_pending_snippet(),this.#h=0,this.#l=0,this.#a=p(()=>{this.#o(this.#t)}),this.#h>0){var e=this.#n=document.createDocumentFragment();ae(this.#a,e);const r=this.#i.pending;this.#r=p(()=>r(this.#t))}else this.#c(W)}catch(r){this.error(r)}}#c(e){this.is_pending=!1,e.transfer_effects(this.#p,this.#g)}defer_effect(e){ne(e,this.#p,this.#g)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#i.pending}#u(e){var r=m,i=J,a=X;N(this.#e),D(this.#e),q(this.#e.ctx);try{return fe.ensure(),e()}catch(s){return he(s),null}finally{N(r),D(i),q(a)}}#y(e,r){if(!this.has_pending_snippet()){this.parent&&this.parent.#y(e,r);return}this.#h+=e,this.#h===0&&(this.#c(r),this.#r&&x(this.#r,()=>{this.#r=null}),this.#n&&(this.#t.before(this.#n),this.#n=null))}update_pending_count(e,r){this.#y(e,r),this.#l+=e,!(!this.#f||this.#d)&&(this.#d=!0,T(()=>{this.#d=!1,this.#f&&oe(this.#f,this.#l)}))}get_effect_pending(){return this.#b(),j(this.#f)}error(e){var r=this.#i.onerror;let i=this.#i.failed;if(!r&&!i)throw e;this.#a&&(F(this.#a),this.#a=null),this.#r&&(F(this.#r),this.#r=null),this.#s&&(F(this.#s),this.#s=null),v&&(O(this.#_),le(),O(de()));var a=!1,s=!1;const n=()=>{if(a){pe();return}a=!0,s&&_e(),this.#s!==null&&x(this.#s,()=>{this.#s=null}),this.#u(()=>{this.#v()})},c=f=>{try{s=!0,r?.(f,n),s=!1}catch(h){S(h,this.#e&&this.#e.parent)}i&&(this.#s=this.#u(()=>{try{return p(()=>{var h=m;h.b=this,h.f|=P,i(this.#t,()=>f,()=>n)})}catch(h){return S(h,this.#e.parent),null}}))};T(()=>{var f;try{f=this.transform_error(e)}catch(h){S(h,this.#e&&this.#e.parent);return}f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(c,h=>S(h,this.#e&&this.#e.parent)):c(f)})}}const Ce=["touchstart","touchmove"];function Ie(t){return Ce.includes(t)}const w=Symbol("events"),K=new Set,C=new Set;function Be(t,e,r,i={}){function a(s){if(i.capture||I.call(e,s),!s.cancelBubble)return ye(()=>r?.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?T(()=>{e.addEventListener(t,a,i)}):e.addEventListener(t,a,i),a}function Ve(t,e,r,i,a){var s={capture:i,passive:a},n=Be(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&ve(()=>{e.removeEventListener(t,n,s)})}function We(t,e,r){(e[w]??={})[t]=r}function qe(t){for(var e=0;e<t.length;e++)K.add(t[e]);for(var r of C)r(t)}let $=null;function I(t){var e=this,r=e.ownerDocument,i=t.type,a=t.composedPath?.()||[],s=a[0]||t.target;$=t;var n=0,c=$===t&&t[w];if(c){var f=a.indexOf(c);if(f!==-1&&(e===document||e===window)){t[w]=e;return}var h=a.indexOf(e);if(h===-1)return;f<=h&&(n=f)}if(s=a[n]||t.target,s!==e){ge(t,"currentTarget",{configurable:!0,get(){return s||r}});var y=J,E=m;D(null),N(null);try{for(var _,l=[];s!==null;){var o=s.assignedSlot||s.parentNode||s.host||null;try{var d=s[w]?.[i];d!=null&&(!s.disabled||t.target===s)&&d.call(s,t)}catch(u){_?l.push(u):_=u}if(t.cancelBubble||o===e||o===null)break;s=o}if(_){for(let u of l)queueMicrotask(()=>{throw u});throw _}}finally{t[w]=e,delete t.currentTarget,D(y),N(E)}}}function $e(t,e){var r=e==null?"":typeof e=="object"?`${e}`:e;r!==(t.__t??=t.nodeValue)&&(t.__t=r,t.nodeValue=`${r}`)}function He(t,e){return Q(t,e)}function je(t,e){L(),e.intro=e.intro??!1;const r=e.target,i=v,a=g;try{for(var s=be(r);s&&(s.nodeType!==G||s.data!==me);)s=Ee(s);if(!s)throw M;R(!0),O(s);const n=Q(t,{...e,anchor:s});return R(!1),n}catch(n){if(n instanceof Error&&n.message.split(` 2 - `).some(c=>c.startsWith("https://svelte.dev/e/")))throw n;return n!==M&&console.warn("Failed to hydrate: ",n),e.recover===!1&&we(),L(),Te(r),R(!1),He(t,e)}finally{R(i),O(a)}}const A=new Map;function Q(t,{target:e,anchor:r,props:i={},events:a,context:s,intro:n=!0,transformError:c}){L();var f=void 0,h=Se(()=>{var y=r??e.appendChild(U());Le(y,{pending:()=>{}},l=>{Ae({});var o=X;if(s&&(o.c=s),a&&(i.$$events=a),v&&ke(l,null),f=t(l,i)||{},v&&(m.nodes.end=g,g===null||g.nodeType!==G||g.data!==Ne))throw De(),M;Oe()},c);var E=new Set,_=l=>{for(var o=0;o<l.length;o++){var d=l[o];if(!E.has(d)){E.add(d);var u=Ie(d);for(const k of[e,document]){var b=A.get(k);b===void 0&&(b=new Map,A.set(k,b));var H=b.get(d);H===void 0?(k.addEventListener(d,I,{passive:u}),b.set(d,1)):b.set(d,H+1)}}}};return _(Re(K)),C.add(_),()=>{for(var l of E)for(const u of[e,document]){var o=A.get(u),d=o.get(l);--d==0?(u.removeEventListener(l,I),o.delete(l),o.size===0&&A.delete(u)):o.set(l,d)}C.delete(_),y!==r&&y.parentNode?.removeChild(y)}});return B.set(f,h),f}let B=new WeakMap;function ze(t,e){const r=B.get(t);return r?(B.delete(t),r(e)):Promise.resolve()}export{We as a,qe as d,Ve as e,je as h,He as m,$e as s,ze as u};
+2
.svelte-kit/output/client/_app/immutable/chunks/BsDbD4Ku.js
··· 1 + import{al as Z,A as j,r as ee,am as z,u as te,an as Y,ao as T,k as g,j as v,b as m,ap as q,l as re,F as se,aq as ie,ar as P,h as p,g as J,p as x,i as V,m as ne,as as ae,at as N,au as D,av as W,aw as fe,ax as he,ay as G,c as K,az as oe,f as k,t as F,aa as le,I as de,aA as S,E as ce,n as ue,aB as _e,aC as pe,w as ge,aD as ve,x as ye,aE as I,v as be,C as U,aF as me,o as Ee,aG as L,q as R,aH as we,aI as Te,aJ as Se,aK as Re,a1 as Ae,aL as Ne,aM as De,a4 as Fe}from"./CkzjbUDB.js";import{b as Oe}from"./DGbOEUpF.js";function xe(t){let e=0,r=z(0),i;return()=>{Z()&&(j(r),ee(()=>(e===0&&(i=te(()=>t(()=>Y(r)))),e+=1,()=>{T(()=>{e-=1,e===0&&(i?.(),i=void 0,Y(r))})})))}}var ke=ce|ue;function Ie(t,e,r,i){new Le(t,e,r,i)}class Le{parent;is_pending=!1;transform_error;#t;#_=v?g:null;#i;#o;#e;#n=null;#r=null;#s=null;#a=null;#l=0;#h=0;#d=!1;#p=new Set;#g=new Set;#f=null;#b=xe(()=>(this.#f=z(this.#l),()=>{this.#f=null}));constructor(e,r,i,n){this.#t=e,this.#i=r,this.#o=s=>{var a=m;a.b=this,a.f|=q,i(s)},this.parent=m.b,this.transform_error=n??this.parent?.transform_error??(s=>s),this.#e=re(()=>{if(v){const s=this.#_;se();const a=s.data===ie;if(s.data.startsWith(P)){const f=JSON.parse(s.data.slice(P.length));this.#E(f)}else a?this.#w():this.#m()}else this.#v()},ke),v&&(this.#t=g)}#m(){try{this.#n=p(()=>this.#o(this.#t))}catch(e){this.error(e)}}#E(e){const r=this.#i.failed;r&&(this.#s=p(()=>{r(this.#t,()=>e,()=>()=>{})}))}#w(){const e=this.#i.pending;e&&(this.is_pending=!0,this.#r=p(()=>e(this.#t)),T(()=>{var r=this.#a=document.createDocumentFragment(),i=J();r.append(i),this.#n=this.#u(()=>p(()=>this.#o(i))),this.#h===0&&(this.#t.before(r),this.#a=null,x(this.#r,()=>{this.#r=null}),this.#c(V))}))}#v(){try{if(this.is_pending=this.has_pending_snippet(),this.#h=0,this.#l=0,this.#n=p(()=>{this.#o(this.#t)}),this.#h>0){var e=this.#a=document.createDocumentFragment();ne(this.#n,e);const r=this.#i.pending;this.#r=p(()=>r(this.#t))}else this.#c(V)}catch(r){this.error(r)}}#c(e){this.is_pending=!1,e.transfer_effects(this.#p,this.#g)}defer_effect(e){ae(e,this.#p,this.#g)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#i.pending}#u(e){var r=m,i=G,n=K;N(this.#e),D(this.#e),W(this.#e.ctx);try{return fe.ensure(),e()}catch(s){return he(s),null}finally{N(r),D(i),W(n)}}#y(e,r){if(!this.has_pending_snippet()){this.parent&&this.parent.#y(e,r);return}this.#h+=e,this.#h===0&&(this.#c(r),this.#r&&x(this.#r,()=>{this.#r=null}),this.#a&&(this.#t.before(this.#a),this.#a=null))}update_pending_count(e,r){this.#y(e,r),this.#l+=e,!(!this.#f||this.#d)&&(this.#d=!0,T(()=>{this.#d=!1,this.#f&&oe(this.#f,this.#l)}))}get_effect_pending(){return this.#b(),j(this.#f)}error(e){var r=this.#i.onerror;let i=this.#i.failed;if(!r&&!i)throw e;this.#n&&(k(this.#n),this.#n=null),this.#r&&(k(this.#r),this.#r=null),this.#s&&(k(this.#s),this.#s=null),v&&(F(this.#_),le(),F(de()));var n=!1,s=!1;const a=()=>{if(n){pe();return}n=!0,s&&_e(),this.#s!==null&&x(this.#s,()=>{this.#s=null}),this.#u(()=>{this.#v()})},c=f=>{try{s=!0,r?.(f,a),s=!1}catch(h){S(h,this.#e&&this.#e.parent)}i&&(this.#s=this.#u(()=>{try{return p(()=>{var h=m;h.b=this,h.f|=q,i(this.#t,()=>f,()=>a)})}catch(h){return S(h,this.#e.parent),null}}))};T(()=>{var f;try{f=this.transform_error(e)}catch(h){S(h,this.#e&&this.#e.parent);return}f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(c,h=>S(h,this.#e&&this.#e.parent)):c(f)})}}const Me=["touchstart","touchmove"];function Ce(t){return Me.includes(t)}const w=Symbol("events"),Q=new Set,M=new Set;function He(t,e,r,i={}){function n(s){if(i.capture||C.call(e,s),!s.cancelBubble)return ve(()=>r?.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?T(()=>{e.addEventListener(t,n,i)}):e.addEventListener(t,n,i),n}function Pe(t,e,r,i,n){var s={capture:i,passive:n},a=He(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&ge(()=>{e.removeEventListener(t,a,s)})}function Ve(t,e,r){(e[w]??={})[t]=r}function We(t){for(var e=0;e<t.length;e++)Q.add(t[e]);for(var r of M)r(t)}let $=null;function C(t){var e=this,r=e.ownerDocument,i=t.type,n=t.composedPath?.()||[],s=n[0]||t.target;$=t;var a=0,c=$===t&&t[w];if(c){var f=n.indexOf(c);if(f!==-1&&(e===document||e===window)){t[w]=e;return}var h=n.indexOf(e);if(h===-1)return;f<=h&&(a=f)}if(s=n[a]||t.target,s!==e){ye(t,"currentTarget",{configurable:!0,get(){return s||r}});var y=G,E=m;D(null),N(null);try{for(var _,l=[];s!==null;){var o=s.assignedSlot||s.parentNode||s.host||null;try{var d=s[w]?.[i];d!=null&&(!s.disabled||t.target===s)&&d.call(s,t)}catch(u){_?l.push(u):_=u}if(t.cancelBubble||o===e||o===null)break;s=o}if(_){for(let u of l)queueMicrotask(()=>{throw u});throw _}}finally{t[w]=e,delete t.currentTarget,D(y),N(E)}}}function $e(t,e){var r=e==null?"":typeof e=="object"?`${e}`:e;r!==(t.__t??=t.nodeValue)&&(t.__t=r,t.nodeValue=`${r}`)}function Be(t,e){return X(t,e)}function je(t,e){I(),e.intro=e.intro??!1;const r=e.target,i=v,n=g;try{for(var s=be(r);s&&(s.nodeType!==U||s.data!==me);)s=Ee(s);if(!s)throw L;R(!0),F(s);const a=X(t,{...e,anchor:s});return R(!1),a}catch(a){if(a instanceof Error&&a.message.split(` 2 + `).some(c=>c.startsWith("https://svelte.dev/e/")))throw a;return a!==L&&console.warn("Failed to hydrate: ",a),e.recover===!1&&we(),I(),Te(r),R(!1),Be(t,e)}finally{R(i),F(n)}}const A=new Map;function X(t,{target:e,anchor:r,props:i={},events:n,context:s,intro:a=!0,transformError:c}){I();var f=void 0,h=Se(()=>{var y=r??e.appendChild(J());Ie(y,{pending:()=>{}},l=>{Ae({});var o=K;if(s&&(o.c=s),n&&(i.$$events=n),v&&Oe(l,null),f=t(l,i)||{},v&&(m.nodes.end=g,g===null||g.nodeType!==U||g.data!==Ne))throw De(),L;Fe()},c);var E=new Set,_=l=>{for(var o=0;o<l.length;o++){var d=l[o];if(!E.has(d)){E.add(d);var u=Ce(d);for(const O of[e,document]){var b=A.get(O);b===void 0&&(b=new Map,A.set(O,b));var B=b.get(d);B===void 0?(O.addEventListener(d,C,{passive:u}),b.set(d,1)):b.set(d,B+1)}}}};return _(Re(Q)),M.add(_),()=>{for(var l of E)for(const u of[e,document]){var o=A.get(u),d=o.get(l);--d==0?(u.removeEventListener(l,C),o.delete(l),o.size===0&&A.delete(u)):o.set(l,d)}M.delete(_),y!==r&&y.parentNode?.removeChild(y)}});return H.set(f,h),f}let H=new WeakMap;function ze(t,e){const r=H.get(t);return r?(H.delete(t),r(e)):Promise.resolve()}export{Ve as a,We as d,Pe as e,je as h,Be as m,$e as s,ze as u};
+1
.svelte-kit/output/client/_app/immutable/chunks/C0nNmPgn.js
··· 1 + import{ab as L,A as U,B as T,aO as te,b2 as gt}from"./CkzjbUDB.js";import{w as Ee,o as De}from"./DxGD2b0U.js";class Se{constructor(t,n){this.status=t,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${t}`}}toString(){return JSON.stringify(this.body)}}class Re{constructor(t,n){this.status=t,this.location=n}}class xe extends Error{constructor(t,n,r){super(r),this.status=t,this.text=n}}new URL("sveltekit-internal://");function _t(e,t){return e==="/"||t==="ignore"?e:t==="never"?e.endsWith("/")?e.slice(0,-1):e:t==="always"&&!e.endsWith("/")?e+"/":e}function mt(e){return e.split("%25").map(decodeURI).join("%25")}function vt(e){for(const t in e)e[t]=decodeURIComponent(e[t]);return e}function pe({href:e}){return e.split("#")[0]}function wt(...e){let t=5381;for(const n of e)if(typeof n=="string"){let r=n.length;for(;r;)t=t*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)t=t*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(t>>>0).toString(36)}new TextEncoder;new TextDecoder;function yt(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}const bt=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||"GET")!=="GET"&&G.delete(Ae(e)),bt(e,t));const G=new Map;function kt(e,t){const n=Ae(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:a,...i}=JSON.parse(r.textContent);const o=r.getAttribute("data-ttl");return o&&G.set(n,{body:a,init:i,ttl:1e3*Number(o)}),r.getAttribute("data-b64")!==null&&(a=yt(a)),Promise.resolve(new Response(a,i))}return window.fetch(e,t)}function Et(e,t,n){if(G.size>0){const r=Ae(e,n),a=G.get(r);if(a){if(performance.now()<a.ttl&&["default","force-cache","only-if-cached",void 0].includes(n?.cache))return new Response(a.body,a.init);G.delete(r)}}return window.fetch(t,n)}function Ae(e,t){let r=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){const a=[];t.headers&&a.push([...new Headers(t.headers)].join(",")),t.body&&(typeof t.body=="string"||ArrayBuffer.isView(t.body))&&a.push(t.body),r+=`[data-hash="${wt(...a)}"]`}return r}const St=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;function Rt(e){const t=[];return{pattern:e==="/"?/^\/$/:new RegExp(`^${At(e).map(r=>{const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return t.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const i=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(i)return t.push({name:i[1],matcher:i[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const o=r.split(/\[(.+?)\](?!\])/);return"/"+o.map((l,c)=>{if(c%2){if(l.startsWith("x+"))return ge(String.fromCharCode(parseInt(l.slice(2),16)));if(l.startsWith("u+"))return ge(String.fromCharCode(...l.slice(2).split("-").map(_=>parseInt(_,16))));const f=St.exec(l),[,p,v,h,u]=f;return t.push({name:h,matcher:u,optional:!!p,rest:!!v,chained:v?c===1&&o[0]==="":!1}),v?"([^]*?)":p?"([^/]*)?":"([^/]+?)"}return ge(l)}).join("")}).join("")}/?$`),params:t}}function xt(e){return e!==""&&!/^\([^)]+\)$/.test(e)}function At(e){return e.slice(1).split("/").filter(xt)}function Lt(e,t,n){const r={},a=e.slice(1),i=a.filter(s=>s!==void 0);let o=0;for(let s=0;s<t.length;s+=1){const l=t[s];let c=a[s-o];if(l.chained&&l.rest&&o&&(c=a.slice(s-o,s+1).filter(f=>f).join("/"),o=0),c===void 0)if(l.rest)c="";else continue;if(!l.matcher||n[l.matcher](c)){r[l.name]=c;const f=t[s+1],p=a[s+1];f&&!f.rest&&f.optional&&p&&l.chained&&(o=0),!f&&!p&&Object.keys(r).length===i.length&&(o=0);continue}if(l.optional&&l.chained){o++;continue}return}if(!o)return r}function ge(e){return e.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function Ut({nodes:e,server_loads:t,dictionary:n,matchers:r}){const a=new Set(t);return Object.entries(n).map(([s,[l,c,f]])=>{const{pattern:p,params:v}=Rt(s),h={id:s,exec:u=>{const _=p.exec(u);if(_)return Lt(_,v,r)},errors:[1,...f||[]].map(u=>e[u]),layouts:[0,...c||[]].map(o),leaf:i(l)};return h.errors.length=h.layouts.length=Math.max(h.errors.length,h.layouts.length),h});function i(s){const l=s<0;return l&&(s=~s),[l,e[s]]}function o(s){return s===void 0?s:[a.has(s),e[s]]}}function We(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function qe(e,t,n=JSON.stringify){const r=n(t);try{sessionStorage[e]=r}catch{}}const x=globalThis.__sveltekit_1gh8pzr?.base??"",Tt=globalThis.__sveltekit_1gh8pzr?.assets??x??"",It="1774912484423",Ye="sveltekit:snapshot",He="sveltekit:scroll",Je="sveltekit:states",Ot="sveltekit:pageurl",V="sveltekit:history",Y="sveltekit:navigation",j={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Le=location.origin;function Xe(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){const n=document.getElementsByTagName("base");t=n.length?n[0].href:document.URL}return new URL(e,t)}function D(){return{x:pageXOffset,y:pageYOffset}}function q(e,t){return e.getAttribute(`data-sveltekit-${t}`)}const Ve={...j,"":j.hover};function Qe(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function Ze(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()==="A"&&e.hasAttribute("href"))return e;e=Qe(e)}}function ve(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const s=location.hash.split("#")[1]||"/";r.hash=`#${s}${r.hash}`}}catch{}const a=e instanceof SVGAElement?e.target.baseVal:e.target,i=!r||!!a||ue(r,t,n)||(e.getAttribute("rel")||"").split(/\s+/).includes("external"),o=r?.origin===Le&&e.hasAttribute("download");return{url:r,external:i,target:a,download:o}}function ne(e){let t=null,n=null,r=null,a=null,i=null,o=null,s=e;for(;s&&s!==document.documentElement;)r===null&&(r=q(s,"preload-code")),a===null&&(a=q(s,"preload-data")),t===null&&(t=q(s,"keepfocus")),n===null&&(n=q(s,"noscroll")),i===null&&(i=q(s,"reload")),o===null&&(o=q(s,"replacestate")),s=Qe(s);function l(c){switch(c){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:Ve[r??"off"],preload_data:Ve[a??"off"],keepfocus:l(t),noscroll:l(n),reload:l(i),replace_state:l(o)}}function Be(e){const t=Ee(e);let n=!0;function r(){n=!0,t.update(o=>o)}function a(o){n=!1,t.set(o)}function i(o){let s;return t.subscribe(l=>{(s===void 0||n&&l!==s)&&o(s=l)})}return{notify:r,set:a,subscribe:i}}const et={v:()=>{}};function Pt(){const{set:e,subscribe:t}=Ee(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Tt}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const o=(await a.json()).version!==It;return o&&(e(!0),et.v(),clearTimeout(n)),o}catch{return!1}}return{subscribe:t,check:r}}function ue(e,t,n){return e.origin!==Le||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function ln(e){}const tt=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...tt];const $t=new Set([...tt]);[...$t];function Ct(e){return e.filter(t=>t!=null)}function Ue(e){return e instanceof Se||e instanceof xe?e.status:500}function jt(e){return e instanceof xe?e.text:"Internal Error"}let k,H,_e;const Nt=De.toString().includes("$$")||/function \w+\(\) \{\}/.test(De.toString()),ze="a:";Nt?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(ze)},H={current:null},_e={current:!1}):(k=new class{#e=L({});get data(){return U(this.#e)}set data(t){T(this.#e,t)}#t=L(null);get form(){return U(this.#t)}set form(t){T(this.#t,t)}#n=L(null);get error(){return U(this.#n)}set error(t){T(this.#n,t)}#r=L({});get params(){return U(this.#r)}set params(t){T(this.#r,t)}#a=L({id:null});get route(){return U(this.#a)}set route(t){T(this.#a,t)}#o=L({});get state(){return U(this.#o)}set state(t){T(this.#o,t)}#s=L(-1);get status(){return U(this.#s)}set status(t){T(this.#s,t)}#i=L(new URL(ze));get url(){return U(this.#i)}set url(t){T(this.#i,t)}},H=new class{#e=L(null);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},_e=new class{#e=L(!1);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},et.v=()=>_e.current=!0);function Dt(e){Object.assign(k,e)}const qt=new Set(["icon","shortcut icon","apple-touch-icon"]);let M=null;const C=We(He)??{},J=We(Ye)??{},$={url:Be({}),page:Be({}),navigating:Ee(null),updated:Pt()};function Te(e){C[e]=D()}function Vt(e,t){let n=e+1;for(;C[n];)delete C[n],n+=1;for(n=t+1;J[n];)delete J[n],n+=1}function X(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(()=>{})}async function nt(){if("serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration(x||"/");e&&await e.update()}}function Ke(){}let Ie,we,re,I,ye,y;const ae=[],oe=[];let A=null;function be(){A?.fork?.then(e=>e?.discard()),A=null}const ee=new Map,rt=new Set,Bt=new Set,W=new Set;let m={branch:[],error:null,url:null},at=!1,se=!1,Me=!0,Q=!1,F=!1,ot=!1,Oe=!1,st,w,R,N;const ie=new Set,Fe=new Map;async function dn(e,t,n){globalThis.__sveltekit_1gh8pzr?.data&&globalThis.__sveltekit_1gh8pzr.data,document.URL!==location.href&&(location.href=location.href),y=e,await e.hooks.init?.(),Ie=Ut(e),I=document.documentElement,ye=t,we=e.nodes[0],re=e.nodes[1],we(),re(),w=history.state?.[V],R=history.state?.[Y],w||(w=R=Date.now(),history.replaceState({...history.state,[V]:w,[Y]:R},""));const r=C[w];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await tn(ye,n)):(await B({type:"enter",url:Xe(y.hash?an(new URL(location.href)):location.href),replace_state:!0}),a()),en()}function zt(){ae.length=0,Oe=!1}function it(e){oe.some(t=>t?.snapshot)&&(J[e]=oe.map(t=>t?.snapshot?.capture()))}function lt(e){J[e]?.forEach((t,n)=>{oe[n]?.snapshot?.restore(t)})}function Ge(){Te(w),qe(He,C),it(R),qe(Ye,J)}async function Kt(e,t,n,r){let a;t.invalidateAll&&be(),await B({type:"goto",url:Xe(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:n,nav_token:r,accept:()=>{t.invalidateAll&&(Oe=!0,a=[...Fe.keys()]),t.invalidate&&t.invalidate.forEach(Zt)}}),t.invalidateAll&&te().then(te).then(()=>{Fe.forEach(({resource:i},o)=>{a?.includes(o)&&i.refresh?.()})})}async function Mt(e){if(e.id!==A?.id){be();const t={};ie.add(t),A={id:e.id,token:t,promise:ut({...e,preload:t}).then(n=>(ie.delete(t),n.type==="loaded"&&n.state.error&&be(),n)),fork:null}}return A.promise}async function me(e){const t=(await fe(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(n=>n[1]()))}async function ct(e,t,n){const r={params:m.params,route:{id:m.route?.id??null},url:new URL(location.href)};m={...e.state,nav:r};const a=document.querySelector("style[data-sveltekit]");if(a&&a.remove(),Object.assign(k,e.props.page),st=new y.root({target:t,props:{...e.props,stores:$,components:oe},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),lt(R),n){const i={from:null,to:{...r,scroll:C[w]??D()},willUnload:!1,type:"enter",complete:Promise.resolve()};W.forEach(o=>o(i))}se=!0}async function le({url:e,params:t,branch:n,errors:r,status:a,error:i,route:o,form:s}){let l="never";if(x&&(e.pathname===x||e.pathname===x+"/"))l="always";else for(const u of n)u?.slash!==void 0&&(l=u.slash);e.pathname=_t(e.pathname,l),e.search=e.search;const c={type:"loaded",state:{url:e,params:t,branch:n,error:i,route:o},props:{constructors:Ct(n).map(u=>u.node.component),page:Ne(k)}};s!==void 0&&(c.props.form=s);let f={},p=!k,v=0;for(let u=0;u<Math.max(n.length,m.branch.length);u+=1){const _=n[u],g=m.branch[u];_?.data!==g?.data&&(p=!0),_&&(f={...f,..._.data},p&&(c.props[`data_${v}`]=f),v+=1)}return(!m.url||e.href!==m.url.href||m.error!==i||s!==void 0&&s!==k.form||p)&&(c.props.page={error:i,params:t,route:{id:o?.id??null},state:{},status:a,url:new URL(e),form:s??null,data:p?f:k.data}),c}async function Pe({loader:e,parent:t,url:n,params:r,route:a,server_data_node:i}){let o=null;const s={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();return{node:l,loader:e,server:i,universal:l.universal?.load?{type:"data",data:o,uses:s}:null,data:o??i?.data??null,slash:l.universal?.trailingSlash??i?.slash}}function Ft(e,t,n){let r=e instanceof Request?e.url:e;const a=new URL(r,n);a.origin===n.origin&&(r=a.href.slice(n.origin.length));const i=se?Et(r,a.href,t):kt(r,t);return{resolved:a,promise:i}}function Gt(e,t,n,r,a,i){if(Oe)return!0;if(!a)return!1;if(a.parent&&e||a.route&&t||a.url&&n)return!0;for(const o of a.search_params)if(r.has(o))return!0;for(const o of a.params)if(i[o]!==m.params[o])return!0;for(const o of a.dependencies)if(ae.some(s=>s(new URL(o))))return!0;return!1}function $e(e,t){return e?.type==="data"?e:e?.type==="skip"?t??null:null}function Wt(e,t){if(!e)return new Set(t.searchParams.keys());const n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(const r of n){const a=e.searchParams.getAll(r),i=t.searchParams.getAll(r);a.every(o=>i.includes(o))&&i.every(o=>a.includes(o))&&n.delete(r)}return n}function Yt({error:e,url:t,route:n,params:r}){return{type:"loaded",state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:Ne(k),constructors:[]}}}async function ut({id:e,invalidating:t,url:n,params:r,route:a,preload:i}){if(A?.id===e)return ie.delete(A.token),A.promise;const{errors:o,layouts:s,leaf:l}=a,c=[...s,l];o.forEach(g=>g?.().catch(()=>{})),c.forEach(g=>g?.[1]().catch(()=>{}));const f=m.url?e!==ce(m.url):!1,p=m.route?a.id!==m.route.id:!1,v=Wt(m.url,n);let h=!1;const u=c.map(async(g,d)=>{if(!g)return;const E=m.branch[d];return g[1]===E?.loader&&!Gt(h,p,f,v,E.universal?.uses,r)?E:(h=!0,Pe({loader:g[1],url:n,params:r,route:a,parent:async()=>{const O={};for(let P=0;P<d;P+=1)Object.assign(O,(await u[P])?.data);return O},server_data_node:$e(g[0]?{type:"skip"}:null,g[0]?E?.server:void 0)}))});for(const g of u)g.catch(()=>{});const _=[];for(let g=0;g<c.length;g+=1)if(c[g])try{_.push(await u[g])}catch(d){if(d instanceof Re)return{type:"redirect",location:d.location};if(ie.has(i))return Yt({error:await Z(d,{params:r,url:n,route:{id:a.id}}),url:n,params:r,route:a});let E=Ue(d),S;if(d instanceof Se)S=d.body;else{if(await $.updated.check())return await nt(),await X(n);S=await Z(d,{params:r,url:n,route:{id:a.id}})}const O=await Ht(g,_,o);return O?le({url:n,params:r,branch:_.slice(0,O.idx).concat(O.node),errors:o,status:E,error:S,route:a}):await dt(n,{id:a.id},S,E)}else _.push(void 0);return le({url:n,params:r,branch:_,errors:o,status:200,error:null,route:a,form:t?void 0:null})}async function Ht(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)r-=1;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function Ce({status:e,error:t,url:n,route:r}){const a={};let i=null;try{const o=await Pe({loader:we,url:n,params:a,route:r,parent:()=>Promise.resolve({}),server_data_node:$e(i)}),s={node:await re(),loader:re,universal:null,server:null,data:null};return le({url:n,params:a,branch:[o,s],status:e,error:t,errors:[],route:null})}catch(o){if(o instanceof Re)return Kt(new URL(o.location,location.href),{},0);throw o}}async function Jt(e){const t=e.href;if(ee.has(t))return ee.get(t);let n;try{const r=(async()=>{let a=await y.hooks.reroute({url:new URL(e),fetch:async(i,o)=>Ft(i,o,e).promise})??e;if(typeof a=="string"){const i=new URL(e);y.hash?i.hash=a:i.pathname=a,a=i}return a})();ee.set(t,r),n=await r}catch{ee.delete(t);return}return n}async function fe(e,t){if(e&&!ue(e,x,y.hash)){const n=await Jt(e);if(!n)return;const r=Xt(n);for(const a of Ie){const i=a.exec(r);if(i)return{id:ce(e),invalidating:t,route:a,params:vt(i),url:e}}}}function Xt(e){return mt(y.hash?e.hash.replace(/^#/,"").replace(/[?#].+/,""):e.pathname.slice(x.length))||"/"}function ce(e){return(y.hash?e.hash.replace(/^#/,""):e.pathname)+e.search}function ft({url:e,type:t,intent:n,delta:r,event:a,scroll:i}){let o=!1;const s=je(m,n,e,t,i??null);r!==void 0&&(s.navigation.delta=r),a!==void 0&&(s.navigation.event=a);const l={...s.navigation,cancel:()=>{o=!0,s.reject(new Error("navigation cancelled"))}};return Q||rt.forEach(c=>c(l)),o?null:s}async function B({type:e,url:t,popped:n,keepfocus:r,noscroll:a,replace_state:i,state:o={},redirect_count:s=0,nav_token:l={},accept:c=Ke,block:f=Ke,event:p}){const v=N;N=l;const h=await fe(t,!1),u=e==="enter"?je(m,h,t,e):ft({url:t,type:e,delta:n?.delta,intent:h,scroll:n?.scroll,event:p});if(!u){f(),N===l&&(N=v);return}const _=w,g=R;c(),Q=!0,se&&u.navigation.type!=="enter"&&$.navigating.set(H.current=u.navigation);let d=h&&await ut(h);if(!d){if(ue(t,x,y.hash))return await X(t,i);d=await dt(t,{id:null},await Z(new xe(404,"Not Found",`Not found: ${t.pathname}`),{url:t,params:{},route:{id:null}}),404,i)}if(t=h?.url||t,N!==l)return u.reject(new Error("navigation aborted")),!1;if(d.type==="redirect"){if(s<20){await B({type:e,url:new URL(d.location,t),popped:n,keepfocus:r,noscroll:a,replace_state:i,state:o,redirect_count:s+1,nav_token:l}),u.fulfil(void 0);return}d=await Ce({status:500,error:await Z(new Error("Redirect loop"),{url:t,params:{},route:{id:null}}),url:t,route:{id:null}})}else d.props.page.status>=400&&await $.updated.check()&&(await nt(),await X(t,i));if(zt(),Te(_),it(g),d.props.page.url.pathname!==t.pathname&&(t.pathname=d.props.page.url.pathname),o=n?n.state:o,!n){const b=i?0:1,z={[V]:w+=b,[Y]:R+=b,[Je]:o};(i?history.replaceState:history.pushState).call(history,z,"",t),i||Vt(w,R)}const E=h&&A?.id===h.id?A.fork:null;A=null,d.props.page.state=o;let S;if(se){const b=(await Promise.all(Array.from(Bt,K=>K(u.navigation)))).filter(K=>typeof K=="function");if(b.length>0){let K=function(){b.forEach(he=>{W.delete(he)})};b.push(K),b.forEach(he=>{W.add(he)})}const z=u.navigation.to;m={...d.state,nav:{params:z.params,route:z.route,url:z.url}},d.props.page&&(d.props.page.url=t);const de=E&&await E;de?S=de.commit():(M=null,st.$set(d.props),M&&Object.assign(d.props.page,M),Dt(d.props.page),S=gt?.()),ot=!0}else await ct(d,ye,!1);const{activeElement:O}=document;await S,await te(),await te();let P=null;if(Me){const b=n?n.scroll:a?D():null;b?scrollTo(b.x,b.y):(P=t.hash&&document.getElementById(ht(t)))?P.scrollIntoView():scrollTo(0,0)}const pt=document.activeElement!==O&&document.activeElement!==document.body;!r&&!pt&&rn(t,!P),Me=!0,d.props.page&&(M&&Object.assign(d.props.page,M),Object.assign(k,d.props.page)),Q=!1,e==="popstate"&&lt(R),u.fulfil(void 0),u.navigation.to&&(u.navigation.to.scroll=D()),W.forEach(b=>b(u.navigation)),$.navigating.set(H.current=null)}async function dt(e,t,n,r,a){return e.origin===Le&&e.pathname===location.pathname&&!at?await Ce({status:r,error:n,url:e,route:t}):await X(e,a)}function Qt(){let e,t={element:void 0,href:void 0},n;I.addEventListener("mousemove",s=>{const l=s.target;clearTimeout(e),e=setTimeout(()=>{i(l,j.hover)},20)});function r(s){s.defaultPrevented||i(s.composedPath()[0],j.tap)}I.addEventListener("mousedown",r),I.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(s=>{for(const l of s)l.isIntersecting&&(me(new URL(l.target.href)),a.unobserve(l.target))},{threshold:0});async function i(s,l){const c=Ze(s,I),f=c===t.element&&c?.href===t.href&&l>=n;if(!c||f)return;const{url:p,external:v,download:h}=ve(c,x,y.hash);if(v||h)return;const u=ne(c),_=p&&ce(m.url)===ce(p);if(!(u.reload||_))if(l<=u.preload_data){t={element:c,href:c.href},n=j.tap;const g=await fe(p,!1);if(!g)return;Mt(g)}else l<=u.preload_code&&(t={element:c,href:c.href},n=l,me(p))}function o(){a.disconnect();for(const s of I.querySelectorAll("a")){const{url:l,external:c,download:f}=ve(s,x,y.hash);if(c||f)continue;const p=ne(s);p.reload||(p.preload_code===j.viewport&&a.observe(s),p.preload_code===j.eager&&me(l))}}W.add(o),o()}function Z(e,t){if(e instanceof Se)return e.body;const n=Ue(e),r=jt(e);return y.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function Zt(e){if(typeof e=="function")ae.push(e);else{const{href:t}=new URL(e,location.href);ae.push(n=>n.href===t)}}function en(){history.scrollRestoration="manual",addEventListener("beforeunload",t=>{let n=!1;if(Ge(),!Q){const r=je(m,void 0,null,"leave"),a={...r.navigation,cancel:()=>{n=!0,r.reject(new Error("navigation cancelled"))}};rt.forEach(i=>i(a))}n?(t.preventDefault(),t.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Ge()}),navigator.connection?.saveData||Qt(),I.addEventListener("click",async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;const n=Ze(t.composedPath()[0],I);if(!n)return;const{url:r,external:a,target:i,download:o}=ve(n,x,y.hash);if(!r)return;if(i==="_parent"||i==="_top"){if(window.parent!==window)return}else if(i&&i!=="_self")return;const s=ne(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&!(r.protocol==="https:"||r.protocol==="http:")||o)return;const[c,f]=(y.hash?r.hash.replace(/^#/,""):r.href).split("#"),p=c===pe(location);if(a||s.reload&&(!p||!f)){ft({url:r,type:"link",event:t})?Q=!0:t.preventDefault();return}if(f!==void 0&&p){const[,v]=m.url.href.split("#");if(v===f){if(t.preventDefault(),f===""||f==="top"&&n.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=n.ownerDocument.getElementById(decodeURIComponent(f));h&&(h.scrollIntoView(),h.focus())}return}if(F=!0,Te(w),e(r),!s.replace_state)return;F=!1}t.preventDefault(),await new Promise(v=>{requestAnimationFrame(()=>{setTimeout(v,0)}),setTimeout(v,100)}),await B({type:"link",url:r,keepfocus:s.keepfocus,noscroll:s.noscroll,replace_state:s.replace_state??r.href===location.href,event:t})}),I.addEventListener("submit",t=>{if(t.defaultPrevented)return;const n=HTMLFormElement.prototype.cloneNode.call(t.target),r=t.submitter;if((r?.formTarget||n.target)==="_blank"||(r?.formMethod||n.method)!=="get")return;const o=new URL(r?.hasAttribute("formaction")&&r?.formAction||n.action);if(ue(o,x,!1))return;const s=t.target,l=ne(s);if(l.reload)return;t.preventDefault(),t.stopPropagation();const c=new FormData(s,r);o.search=new URLSearchParams(c).toString(),B({type:"form",url:o,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??o.href===location.href,event:t})}),addEventListener("popstate",async t=>{if(!ke){if(t.state?.[V]){const n=t.state[V];if(N={},n===w)return;const r=C[n],a=t.state[Je]??{},i=new URL(t.state[Ot]??location.href),o=t.state[Y],s=m.url?pe(location)===pe(m.url):!1;if(o===R&&(ot||s)){a!==k.state&&(k.state=a),e(i),C[w]=D(),r&&scrollTo(r.x,r.y),w=n;return}const c=n-w;await B({type:"popstate",url:i,popped:{state:a,scroll:r,delta:c},accept:()=>{w=n,R=o},block:()=>{history.go(-c)},nav_token:N,event:t})}else if(!F){const n=new URL(location.href);e(n),y.hash&&location.reload()}}}),addEventListener("hashchange",()=>{F&&(F=!1,history.replaceState({...history.state,[V]:++w,[Y]:R},"",location.href))});for(const t of document.querySelectorAll("link"))qt.has(t.rel)&&(t.href=t.href);addEventListener("pageshow",t=>{t.persisted&&$.navigating.set(H.current=null)});function e(t){m.url=k.url=t,$.page.set(Ne(k)),$.page.notify()}}async function tn(e,{status:t=200,error:n,node_ids:r,params:a,route:i,server_route:o,data:s,form:l}){at=!0;const c=new URL(location.href);let f;({params:a={},route:i={id:null}}=await fe(c,!1)||{}),f=Ie.find(({id:h})=>h===i.id);let p,v=!0;try{const h=r.map(async(_,g)=>{const d=s[g];return d?.uses&&(d.uses=nn(d.uses)),Pe({loader:y.nodes[_],url:c,params:a,route:i,parent:async()=>{const E={};for(let S=0;S<g;S+=1)Object.assign(E,(await h[S]).data);return E},server_data_node:$e(d)})}),u=await Promise.all(h);if(f){const _=f.layouts;for(let g=0;g<_.length;g++)_[g]||u.splice(g,0,void 0)}p=await le({url:c,params:a,branch:u,status:t,error:n,errors:f?.errors,form:l,route:f??null})}catch(h){if(h instanceof Re){await X(new URL(h.location,location.href));return}p=await Ce({status:Ue(h),error:await Z(h,{url:c,params:a,route:i}),url:c,route:i}),e.textContent="",v=!1}p.props.page&&(p.props.page.state={}),await ct(p,e,v)}function nn(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}let ke=!1;function rn(e,t=!0){const n=document.querySelector("[autofocus]");if(n)n.focus();else{const r=ht(e);if(r&&document.getElementById(r)){const{x:i,y:o}=D();setTimeout(()=>{const s=history.state;ke=!0,location.replace(new URL(`#${r}`,location.href)),history.replaceState(s,"",e),t&&scrollTo(i,o),ke=!1})}else{const i=document.body,o=i.getAttribute("tabindex");i.tabIndex=-1,i.focus({preventScroll:!0,focusVisible:!1}),o!==null?i.setAttribute("tabindex",o):i.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const i=[];for(let o=0;o<a.rangeCount;o+=1)i.push(a.getRangeAt(o));setTimeout(()=>{if(a.rangeCount===i.length){for(let o=0;o<a.rangeCount;o+=1){const s=i[o],l=a.getRangeAt(o);if(s.commonAncestorContainer!==l.commonAncestorContainer||s.startContainer!==l.startContainer||s.endContainer!==l.endContainer||s.startOffset!==l.startOffset||s.endOffset!==l.endOffset)return}a.removeAllRanges()}})}}}function je(e,t,n,r,a=null){let i,o;const s=new Promise((c,f)=>{i=c,o=f});return s.catch(()=>{}),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:D()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:a},willUnload:!t,type:r,complete:s},fulfil:i,reject:o}}function Ne(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function an(e){const t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function ht(e){let t;if(y.hash){const[,,n]=e.hash.split("#",3);t=n??""}else t=e.hash.slice(1);return decodeURIComponent(t)}export{dn as a,ln as l,k as p,$ as s};
-1
.svelte-kit/output/client/_app/immutable/chunks/C6hdjiAW.js
··· 1 - import{o as h,v as B,w as N,t as b,x as A,D as Y,S as w,y as x,z as M,P as y,A as o,B as G,C as U,F as q,G as z,H as C,q as $,I as F,J as H,K as J,L as K,M as Z,N as j}from"./w0kPbzMq.js";let I=!1;function Q(r){var e=I;try{return I=!1,[r(),I]}finally{I=e}}function R(r,e){return r===e||r?.[w]===e}function W(r={},e,t,v){var f=h.r,u=A;return B(()=>{var d,a;return N(()=>{d=a,a=[],b(()=>{r!==t(...a)&&(e(r,...a),d&&R(t(...d),r)&&e(null,...d))})}),()=>{let i=u;for(;i!==f&&i.parent!==null&&i.parent.f&Y;)i=i.parent;const S=()=>{a&&R(t(...a),r)&&e(null,...a)},s=i.teardown;i.teardown=()=>{S(),s?.()}}}),r}function X(r,e,t,v){var f=!$||(t&F)!==0,u=(t&C)!==0,d=(t&Z)!==0,a=v,i=!0,S=()=>(i&&(i=!1,a=d?b(v):v),a);let s;if(u){var D=w in r||j in r;s=x(r,e)?.set??(D&&e in r?n=>r[e]=n:void 0)}var l,E=!1;u?[l,E]=Q(()=>r[e]):l=r[e],l===void 0&&v!==void 0&&(l=S(),s&&(f&&M(),s(l)));var _;if(f?_=()=>{var n=r[e];return n===void 0?S():(i=!0,n)}:_=()=>{var n=r[e];return n!==void 0&&(a=void 0),n===void 0?a:n},f&&(t&y)===0)return _;if(s){var L=r.$$legacy;return(function(n,P){return arguments.length>0?((!f||!P||L||E)&&s(P?_():n),n):_()})}var g=!1,c=((t&H)!==0?J:K)(()=>(g=!1,_()));u&&o(c);var T=A;return(function(n,P){if(arguments.length>0){const O=P?o(c):f&&u?G(n):n;return U(c,O),g=!0,a!==void 0&&(a=O),n}return q&&g||(T.f&z)!==0?c.v:o(c)})}export{W as b,X as p};
+1
.svelte-kit/output/client/_app/immutable/chunks/CFYBLbZM.js
··· 1 + import{d as l,f as o,p as u,g as n,h as d,i as m,j as p,k as _,m as v,s as k}from"./CkzjbUDB.js";class w{anchor;#t=new Map;#s=new Map;#e=new Map;#i=new Set;#f=!0;constructor(t,s=!0){this.anchor=t,this.#f=s}#a=t=>{if(this.#t.has(t)){var s=this.#t.get(t),e=this.#s.get(s);if(e)l(e),this.#i.delete(s);else{var f=this.#e.get(s);f&&(this.#s.set(s,f.effect),this.#e.delete(s),f.fragment.lastChild.remove(),this.anchor.before(f.fragment),e=f.effect)}for(const[i,a]of this.#t){if(this.#t.delete(i),i===t)break;const r=this.#e.get(a);r&&(o(r.effect),this.#e.delete(a))}for(const[i,a]of this.#s){if(i===s||this.#i.has(i))continue;const r=()=>{if(Array.from(this.#t.values()).includes(i)){var c=document.createDocumentFragment();v(a,c),c.append(n()),this.#e.set(i,{effect:a,fragment:c})}else o(a);this.#i.delete(i),this.#s.delete(i)};this.#f||!e?(this.#i.add(i),u(a,r,!1)):r()}}};#r=t=>{this.#t.delete(t);const s=Array.from(this.#t.values());for(const[e,f]of this.#e)s.includes(e)||(o(f.effect),this.#e.delete(e))};ensure(t,s){var e=m,f=k();if(s&&!this.#s.has(t)&&!this.#e.has(t))if(f){var i=document.createDocumentFragment(),a=n();i.append(a),this.#e.set(t,{effect:d(()=>s(a)),fragment:i})}else this.#s.set(t,d(()=>s(this.anchor)));if(this.#t.set(e,t),f){for(const[r,h]of this.#s)r===t?e.unskip_effect(h):e.skip_effect(h);for(const[r,h]of this.#e)r===t?e.unskip_effect(h.effect):e.skip_effect(h.effect);e.oncommit(this.#a),e.ondiscard(this.#r)}else p&&(this.anchor=_),this.#a(e)}}export{w as B};
-1
.svelte-kit/output/client/_app/immutable/chunks/C_B-Ij-b.js
··· 1 - import{r as v,d as c,p as b,c as u,b as _,a as g,h as o,f as m,m as k,s as y,g as w,i as A,E,j as F,k as M,l as x,n as p}from"./w0kPbzMq.js";class T{anchor;#t=new Map;#s=new Map;#e=new Map;#a=new Set;#i=!0;constructor(t,s=!0){this.anchor=t,this.#i=s}#r=t=>{if(this.#t.has(t)){var s=this.#t.get(t),e=this.#s.get(s);if(e)v(e),this.#a.delete(s);else{var r=this.#e.get(s);r&&(this.#s.set(s,r.effect),this.#e.delete(s),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),e=r.effect)}for(const[i,f]of this.#t){if(this.#t.delete(i),i===t)break;const a=this.#e.get(f);a&&(c(a.effect),this.#e.delete(f))}for(const[i,f]of this.#s){if(i===s||this.#a.has(i))continue;const a=()=>{if(Array.from(this.#t.values()).includes(i)){var h=document.createDocumentFragment();k(f,h),h.append(u()),this.#e.set(i,{effect:f,fragment:h})}else c(f);this.#a.delete(i),this.#s.delete(i)};this.#i||!e?(this.#a.add(i),b(f,a,!1)):a()}}};#f=t=>{this.#t.delete(t);const s=Array.from(this.#t.values());for(const[e,r]of this.#e)s.includes(e)||(c(r.effect),this.#e.delete(e))};ensure(t,s){var e=g,r=y();if(s&&!this.#s.has(t)&&!this.#e.has(t))if(r){var i=document.createDocumentFragment(),f=u();i.append(f),this.#e.set(t,{effect:_(()=>s(f)),fragment:i})}else this.#s.set(t,_(()=>s(this.anchor)));if(this.#t.set(e,t),r){for(const[a,n]of this.#s)a===t?e.unskip_effect(n):e.skip_effect(n);for(const[a,n]of this.#e)a===t?e.unskip_effect(n.effect):e.skip_effect(n.effect);e.oncommit(this.#r),e.ondiscard(this.#f)}else o&&(this.anchor=m),this.#r(e)}}function C(d,t,s=!1){var e;o&&(e=m,A());var r=new T(d),i=s?E:0;function f(a,n){if(o){var h=F(e);if(a!==parseInt(h.substring(1))){var l=M();x(l),r.anchor=l,p(!1),r.ensure(a,n),p(!0);return}}r.ensure(a,n)}w(()=>{var a=!1;t((n,h=0)=>{a=!0,f(h,n)}),a||f(-1,null)},i)}export{T as B,C as i};
+1
.svelte-kit/output/client/_app/immutable/chunks/CkzjbUDB.js
··· 1 + var Ht=Array.isArray,Ut=Array.prototype.indexOf,ie=Array.prototype.includes,Cn=Array.from,Mn=Object.defineProperty,ve=Object.getOwnPropertyDescriptor,Vt=Object.getOwnPropertyDescriptors,Bt=Object.prototype,zt=Array.prototype,it=Object.getPrototypeOf,Qe=Object.isExtensible;const Gt=()=>{};function Fn(e){return e()}function Kt(e){for(var t=0;t<e.length;t++)e[t]()}function ft(){var e,t,n=new Promise((r,s)=>{e=r,t=s});return{promise:n,resolve:e,reject:t}}const E=2,Q=4,we=8,ut=1<<24,q=16,F=32,ee=64,$t=128,k=512,g=1024,b=2048,j=4096,P=8192,C=16384,le=32768,et=1<<25,Ae=65536,Me=1<<17,Xt=1<<18,ye=1<<19,ot=1<<20,jn=1<<25,te=65536,Fe=1<<21,Oe=1<<22,B=1<<23,de=Symbol("$state"),Ln=Symbol("legacy props"),Yn=Symbol(""),Y=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Hn=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),Ne=3,ct=8;function Zt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Un(e,t,n){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Wt(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Jt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Qt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function en(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Vn(){throw new Error("https://svelte.dev/e/hydration_failed")}function Bn(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function tn(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function nn(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function rn(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function zn(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Gn=1,Kn=2,$n=16,Xn=1,Zn=2,Wn=4,Jn=8,Qn=16,er=1,tr=2,sn="[",ln="[!",nr="[?",an="]",Ue={},m=Symbol(),fn="http://www.w3.org/1999/xhtml";function Ve(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function rr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let ne=!1;function sr(e){ne=e}let S;function fe(e){if(e===null)throw Ve(),Ue;return S=e}function lr(){return fe($(S))}function ar(e){if(ne){if($(S)!==null)throw Ve(),Ue;S=e}}function ir(e=1){if(ne){for(var t=e,n=S;t--;)n=$(n);S=n}}function fr(e=!0){for(var t=0,n=S;;){if(n.nodeType===ct){var r=n.data;if(r===an){if(t===0)return n;t-=1}else(r===sn||r===ln||r[0]==="["&&!isNaN(Number(r.slice(1))))&&(t+=1)}var s=$(n);e&&n.remove(),n=s}}function ur(e){if(!e||e.nodeType!==ct)throw Ve(),Ue;return e.data}function _t(e){return e===this.v}function un(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function vt(e){return!un(e,this.v)}let De=!1;function or(){De=!0}let T=null;function Se(e){T=e}function cr(e,t=!1,n){T={p:T,i:!1,c:null,e:null,s:e,x:null,r:d,l:De&&!t?{s:null,u:null,$:[]}:null}}function _r(e){var t=T,n=t.e;if(n!==null){t.e=null;for(var r of n)Ot(r)}return t.i=!0,T=t.p,{}}function ge(){return!De||T!==null&&T.l===null}let X=[];function dt(){var e=X;X=[],Kt(e)}function tt(e){if(X.length===0&&!he){var t=X;queueMicrotask(()=>{t===X&&dt()})}X.push(e)}function on(){for(;X.length>0;)dt()}function cn(e){var t=d;if(t===null)return v.f|=B,e;if((t.f&le)===0&&(t.f&Q)===0)throw e;Re(e,t)}function Re(e,t){for(;t!==null;){if((t.f&$t)!==0){if((t.f&le)===0)throw e;try{t.b.error(e);return}catch(n){e=n}}t=t.parent}throw e}const _n=-7169;function y(e,t){e.f=e.f&_n|t}function Be(e){(e.f&k)!==0||e.deps===null?y(e,g):y(e,j)}function ht(e){if(e!==null)for(const t of e)(t.f&E)===0||(t.f&te)===0||(t.f^=te,ht(t.deps))}function vn(e,t,n){(e.f&b)!==0?t.add(e):(e.f&j)!==0&&n.add(e),ht(e.deps),y(e,g)}const H=new Set;let w=null,D=null,je=null,he=!1,Pe=!1,ae=null,be=null;var nt=0;let dn=1;class G{id=dn++;current=new Map;previous=new Map;#i=new Set;#f=new Set;#r=new Map;#t=new Map;#_=null;#e=[];#v=[];#l=new Set;#s=new Set;#n=new Map;is_fork=!1;#u=!1;#a=new Set;#o(){return this.is_fork||this.#t.size>0}#p(){for(const r of this.#a)for(const s of r.#t.keys()){for(var t=!1,n=s;n.parent!==null;){if(this.#n.has(n)){t=!0;break}n=n.parent}if(!t)return!0}return!1}skip_effect(t){this.#n.has(t)||this.#n.set(t,{d:[],m:[]})}unskip_effect(t){var n=this.#n.get(t);if(n){this.#n.delete(t);for(var r of n.d)y(r,b),this.schedule(r);for(r of n.m)y(r,j),this.schedule(r)}}#c(){if(nt++>1e3&&(H.delete(this),pn()),!this.#o()){for(const a of this.#l)this.#s.delete(a),y(a,b),this.schedule(a);for(const a of this.#s)y(a,j),this.schedule(a)}const t=this.#e;this.#e=[],this.apply();var n=ae=[],r=[],s=be=[];for(const a of t)try{this.#d(a,n,r)}catch(i){throw yt(a),i}if(w=null,s.length>0){var l=G.ensure();for(const a of s)l.schedule(a)}if(ae=null,be=null,this.#o()||this.#p()){this.#h(r),this.#h(n);for(const[a,i]of this.#n)wt(a,i)}else{this.#r.size===0&&H.delete(this),this.#l.clear(),this.#s.clear();for(const a of this.#i)a(this);this.#i.clear(),rt(r),rt(n),this.#_?.resolve()}var u=w;if(this.#e.length>0){const a=u??=this;a.#e.push(...this.#e.filter(i=>!a.#e.includes(i)))}u!==null&&(H.add(u),u.#c()),H.has(this)||this.#w()}#d(t,n,r){t.f^=g;for(var s=t.first;s!==null;){var l=s.f,u=(l&(F|ee))!==0,a=u&&(l&g)!==0,i=a||(l&P)!==0||this.#n.has(s);if(!i&&s.fn!==null){u?s.f^=g:(l&Q)!==0?n.push(s):Ee(s)&&((l&q)!==0&&this.#s.add(s),oe(s));var o=s.first;if(o!==null){s=o;continue}}for(;s!==null;){var f=s.next;if(f!==null){s=f;break}s=s.parent}}}#h(t){for(var n=0;n<t.length;n+=1)vn(t[n],this.#l,this.#s)}capture(t,n,r=!1){n!==m&&!this.previous.has(t)&&this.previous.set(t,n),(t.f&B)===0&&(this.current.set(t,[t.v,r]),D?.set(t,t.v))}activate(){w=this}deactivate(){w=null,D=null}flush(){try{Pe=!0,w=this,this.#c()}finally{nt=0,je=null,ae=null,be=null,Pe=!1,w=null,D=null,z.clear()}}discard(){for(const t of this.#f)t(this);this.#f.clear(),H.delete(this)}register_created_effect(t){this.#v.push(t)}#w(){for(const f of H){var t=f.id<this.id,n=[];for(const[c,[_,p]]of this.current){if(f.current.has(c)){var r=f.current.get(c)[0];if(t&&_!==r)f.current.set(c,[_,p]);else continue}n.push(c)}var s=[...f.current.keys()].filter(c=>!this.current.has(c));if(s.length===0)t&&f.discard();else if(n.length>0){f.activate();var l=new Set,u=new Map;for(var a of n)pt(a,s,l,u);u=new Map;var i=[...f.current.keys()].filter(c=>this.current.has(c)?this.current.get(c)[0]!==c:!0);for(const c of this.#v)(c.f&(C|P|Me))===0&&ze(c,i,u)&&((c.f&(Oe|q))!==0?(y(c,b),f.schedule(c)):f.#l.add(c));if(f.#e.length>0){f.apply();for(var o of f.#e)f.#d(o,[],[]);f.#e=[]}f.deactivate()}}for(const f of H)f.#a.has(this)&&(f.#a.delete(this),f.#a.size===0&&!f.#o()&&(f.activate(),f.#c()))}increment(t,n){let r=this.#r.get(n)??0;if(this.#r.set(n,r+1),t){let s=this.#t.get(n)??0;this.#t.set(n,s+1)}}decrement(t,n,r){let s=this.#r.get(n)??0;if(s===1?this.#r.delete(n):this.#r.set(n,s-1),t){let l=this.#t.get(n)??0;l===1?this.#t.delete(n):this.#t.set(n,l-1)}this.#u||r||(this.#u=!0,tt(()=>{this.#u=!1,this.flush()}))}transfer_effects(t,n){for(const r of t)this.#l.add(r);for(const r of n)this.#s.add(r);t.clear(),n.clear()}oncommit(t){this.#i.add(t)}ondiscard(t){this.#f.add(t)}settled(){return(this.#_??=ft()).promise}static ensure(){if(w===null){const t=w=new G;Pe||(H.add(w),he||tt(()=>{w===t&&t.flush()}))}return w}apply(){{D=null;return}}schedule(t){if(je=t,t.b?.is_pending&&(t.f&(Q|we|ut))!==0&&(t.f&le)===0){t.b.defer_effect(t);return}for(var n=t;n.parent!==null;){n=n.parent;var r=n.f;if(ae!==null&&n===d&&(v===null||(v.f&E)===0))return;if((r&(ee|F))!==0){if((r&g)===0)return;n.f^=g}}this.#e.push(n)}}function hn(e){var t=he;he=!0;try{for(var n;;){if(on(),w===null)return n;w.flush()}}finally{he=t}}function pn(){try{en()}catch(e){Re(e,je)}}let L=null;function rt(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if((r.f&(C|P))===0&&Ee(r)&&(L=new Set,oe(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&Dt(r),L?.size>0)){z.clear();for(const s of L){if((s.f&(C|P))!==0)continue;const l=[s];let u=s.parent;for(;u!==null;)L.has(u)&&(L.delete(u),l.push(u)),u=u.parent;for(let a=l.length-1;a>=0;a--){const i=l[a];(i.f&(C|P))===0&&oe(i)}}L.clear()}}L=null}}function pt(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(const s of e.reactions){const l=s.f;(l&E)!==0?pt(s,t,n,r):(l&(Oe|q))!==0&&(l&b)===0&&ze(s,t,r)&&(y(s,b),Ge(s))}}function ze(e,t,n){const r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(ie.call(t,s))return!0;if((s.f&E)!==0&&ze(s,t,n))return n.set(s,!0),!0}return n.set(e,!1),!1}function Ge(e){w.schedule(e)}function wt(e,t){if(!((e.f&F)!==0&&(e.f&g)!==0)){(e.f&b)!==0?t.d.push(e):(e.f&j)!==0&&t.m.push(e),y(e,g);for(var n=e.first;n!==null;)wt(n,t),n=n.next}}function yt(e){y(e,g);for(var t=e.first;t!==null;)yt(t),t=t.next}function gt(e,t,n,r){const s=ge()?$e:gn;var l=e.filter(_=>!_.settled);if(n.length===0&&l.length===0){r(t.map(s));return}var u=d,a=wn(),i=l.length===1?l[0].promise:l.length>1?Promise.all(l.map(_=>_.promise)):null;function o(_){a();try{r(_)}catch(p){(u.f&C)===0&&Re(p,u)}xe()}if(n.length===0){i.then(()=>o(t.map(s)));return}var f=Ke();function c(){Promise.all(n.map(_=>yn(_))).then(_=>o([...t.map(s),..._])).catch(_=>Re(_,u)).finally(()=>f())}i?i.then(()=>{a(),c(),xe()}):c()}function wn(){var e=d,t=v,n=T,r=w;return function(l=!0){ue(e),K(t),Se(n),l&&(e.f&C)===0&&(r?.activate(),r?.apply())}}function xe(e=!0){ue(null),K(null),Se(null),e&&w?.deactivate()}function Ke(){var e=d,t=e.b,n=w,r=t.is_rendered();return t.update_pending_count(1,n),n.increment(r,e),(s=!1)=>{t.update_pending_count(-1,n),n.decrement(r,e,s)}}function $e(e){var t=E|b,n=v!==null&&(v.f&E)!==0?v:null;return d!==null&&(d.f|=ye),{ctx:T,deps:null,effects:null,equals:_t,f:t,fn:e,reactions:null,rv:0,v:m,wv:0,parent:n??d,ac:null}}function yn(e,t,n){let r=d;r===null&&Zt();var s=void 0,l=Ze(m),u=!v,a=new Map;return kn(()=>{var i=d,o=ft();s=o.promise;try{Promise.resolve(e()).then(o.resolve,o.reject).finally(xe)}catch(p){o.reject(p),xe()}var f=w;if(u){if((i.f&le)!==0)var c=Ke();if(r.b.is_rendered())a.get(f)?.reject(Y),a.delete(f);else{for(const p of a.values())p.reject(Y);a.clear()}a.set(f,o)}const _=(p,h=void 0)=>{if(c){var N=h===Y;c(N)}if(!(h===Y||(i.f&C)!==0)){if(f.activate(),h)l.f|=B,Ye(l,h);else{(l.f&B)!==0&&(l.f^=B),Ye(l,p);for(const[ce,me]of a){if(a.delete(ce),ce===f)break;me.reject(Y)}}f.deactivate()}};o.promise.then(_,p=>_(null,p||"unknown"))}),xn(()=>{for(const i of a.values())i.reject(Y)}),new Promise(i=>{function o(f){function c(){f===s?i(l):o(s)}f.then(c,c)}o(s)})}function vr(e){const t=$e(e);return Ct(t),t}function gn(e){const t=$e(e);return t.equals=vt,t}function En(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)re(t[n])}}function mn(e){for(var t=e.parent;t!==null;){if((t.f&E)===0)return(t.f&C)===0?t:null;t=t.parent}return null}function Xe(e){var t,n=d;ue(mn(e));try{e.f&=~te,En(e),t=Lt(e)}finally{ue(n)}return t}function Et(e){var t=e.v,n=Xe(e);if(!e.equals(n)&&(e.wv=Ft(),(!w?.is_fork||e.deps===null)&&(e.v=n,w?.capture(e,t,!0),e.deps===null))){y(e,g);return}se||(D!==null?(kt()||w?.is_fork)&&D.set(e,n):Be(e))}function bn(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac?.abort(Y),t.teardown=Gt,t.ac=null,pe(t,0),Je(t))}function mt(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&oe(t)}let Le=new Set;const z=new Map;let bt=!1;function Ze(e,t){var n={f:0,v:e,reactions:null,equals:_t,rv:0,wv:0};return n}function U(e,t){const n=Ze(e);return Ct(n),n}function dr(e,t=!1,n=!0){const r=Ze(e);return t||(r.equals=vt),De&&n&&T!==null&&T.l!==null&&(T.l.s??=[]).push(r),r}function V(e,t,n=!1){v!==null&&(!I||(v.f&Me)!==0)&&ge()&&(v.f&(E|q|Oe|Me))!==0&&(O===null||!ie.call(O,e))&&rn();let r=n?_e(t):t;return Ye(e,r,be)}function Ye(e,t,n=null){if(!e.equals(t)){var r=e.v;se?z.set(e,t):z.set(e,r),e.v=t;var s=G.ensure();if(s.capture(e,r),(e.f&E)!==0){const l=e;(e.f&b)!==0&&Xe(l),D===null&&Be(l)}e.wv=Ft(),Tt(e,b,n),ge()&&d!==null&&(d.f&g)!==0&&(d.f&(F|ee))===0&&(x===null?In([e]):x.push(e)),!s.is_fork&&Le.size>0&&!bt&&Tn()}return t}function Tn(){bt=!1;for(const e of Le)(e.f&g)!==0&&y(e,j),Ee(e)&&oe(e);Le.clear()}function hr(e,t=1){var n=W(e),r=t===1?n++:n--;return V(e,n),r}function Ce(e){V(e,e.v+1)}function Tt(e,t,n){var r=e.reactions;if(r!==null)for(var s=ge(),l=r.length,u=0;u<l;u++){var a=r[u],i=a.f;if(!(!s&&a===d)){var o=(i&b)===0;if(o&&y(a,t),(i&E)!==0){var f=a;D?.delete(f),(i&te)===0&&(i&k&&(a.f|=te),Tt(f,j,n))}else if(o){var c=a;(i&q)!==0&&L!==null&&L.add(c),n!==null?n.push(c):Ge(c)}}}}function _e(e){if(typeof e!="object"||e===null||de in e)return e;const t=it(e);if(t!==Bt&&t!==zt)return e;var n=new Map,r=Ht(e),s=U(0),l=J,u=a=>{if(J===l)return a();var i=v,o=J;K(null),at(l);var f=a();return K(i),at(o),f};return r&&n.set("length",U(e.length)),new Proxy(e,{defineProperty(a,i,o){(!("value"in o)||o.configurable===!1||o.enumerable===!1||o.writable===!1)&&tn();var f=n.get(i);return f===void 0?u(()=>{var c=U(o.value);return n.set(i,c),c}):V(f,o.value,!0),!0},deleteProperty(a,i){var o=n.get(i);if(o===void 0){if(i in a){const f=u(()=>U(m));n.set(i,f),Ce(s)}}else V(o,m),Ce(s);return!0},get(a,i,o){if(i===de)return e;var f=n.get(i),c=i in a;if(f===void 0&&(!c||ve(a,i)?.writable)&&(f=u(()=>{var p=_e(c?a[i]:m),h=U(p);return h}),n.set(i,f)),f!==void 0){var _=W(f);return _===m?void 0:_}return Reflect.get(a,i,o)},getOwnPropertyDescriptor(a,i){var o=Reflect.getOwnPropertyDescriptor(a,i);if(o&&"value"in o){var f=n.get(i);f&&(o.value=W(f))}else if(o===void 0){var c=n.get(i),_=c?.v;if(c!==void 0&&_!==m)return{enumerable:!0,configurable:!0,value:_,writable:!0}}return o},has(a,i){if(i===de)return!0;var o=n.get(i),f=o!==void 0&&o.v!==m||Reflect.has(a,i);if(o!==void 0||d!==null&&(!f||ve(a,i)?.writable)){o===void 0&&(o=u(()=>{var _=f?_e(a[i]):m,p=U(_);return p}),n.set(i,o));var c=W(o);if(c===m)return!1}return f},set(a,i,o,f){var c=n.get(i),_=i in a;if(r&&i==="length")for(var p=o;p<c.v;p+=1){var h=n.get(p+"");h!==void 0?V(h,m):p in a&&(h=u(()=>U(m)),n.set(p+"",h))}if(c===void 0)(!_||ve(a,i)?.writable)&&(c=u(()=>U(void 0)),V(c,_e(o)),n.set(i,c));else{_=c.v!==m;var N=u(()=>_e(o));V(c,N)}var ce=Reflect.getOwnPropertyDescriptor(a,i);if(ce?.set&&ce.set.call(f,o),!_){if(r&&typeof i=="string"){var me=n.get("length"),Ie=Number(i);Number.isInteger(Ie)&&Ie>=me.v&&V(me,Ie+1)}Ce(s)}return!0},ownKeys(a){W(s);var i=Reflect.ownKeys(a).filter(c=>{var _=n.get(c);return _===void 0||_.v!==m});for(var[o,f]of n)f.v!==m&&!(o in a)&&i.push(o);return i},setPrototypeOf(){nn()}})}var st,An,Sn,At,St;function pr(){if(st===void 0){st=window,An=document,Sn=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;At=ve(t,"firstChild").get,St=ve(t,"nextSibling").get,Qe(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),Qe(n)&&(n.__t=void 0)}}function ke(e=""){return document.createTextNode(e)}function qe(e){return At.call(e)}function $(e){return St.call(e)}function wr(e,t){if(!ne)return qe(e);var n=qe(S);if(n===null)n=S.appendChild(ke());else if(t&&n.nodeType!==Ne){var r=ke();return n?.before(r),fe(r),r}return t&&We(n),fe(n),n}function yr(e,t=!1){if(!ne){var n=qe(e);return n instanceof Comment&&n.data===""?$(n):n}if(t){if(S?.nodeType!==Ne){var r=ke();return S?.before(r),fe(r),r}We(S)}return S}function gr(e,t=1,n=!1){let r=ne?S:e;for(var s;t--;)s=r,r=$(r);if(!ne)return r;if(n){if(r?.nodeType!==Ne){var l=ke();return r===null?s?.after(l):r.before(l),fe(l),l}We(r)}return fe(r),r}function Er(e){e.textContent=""}function mr(){return!1}function br(e,t,n){return document.createElementNS(fn,e,void 0)}function We(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===Ne;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function Rt(e){var t=v,n=d;K(null),ue(null);try{return e()}finally{K(t),ue(n)}}function xt(e){d===null&&(v===null&&Qt(),Jt()),se&&Wt()}function Rn(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function M(e,t){var n=d;n!==null&&(n.f&P)!==0&&(e|=P);var r={ctx:T,deps:null,nodes:null,f:e|b|k,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};w?.register_created_effect(r);var s=r;if((e&Q)!==0)ae!==null?ae.push(r):G.ensure().schedule(r);else if(t!==null){try{oe(r)}catch(u){throw re(r),u}s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&(s.f&ye)===0&&(s=s.first,(e&q)!==0&&(e&Ae)!==0&&s!==null&&(s.f|=Ae))}if(s!==null&&(s.parent=n,n!==null&&Rn(s,n),v!==null&&(v.f&E)!==0&&(e&ee)===0)){var l=v;(l.effects??=[]).push(s)}return r}function kt(){return v!==null&&!I}function xn(e){const t=M(we,null);return y(t,g),t.teardown=e,t}function Tr(e){xt();var t=d.f,n=!v&&(t&F)!==0&&(t&le)===0;if(n){var r=T;(r.e??=[]).push(e)}else return Ot(e)}function Ot(e){return M(Q|ot,e)}function Ar(e){return xt(),M(we|ot,e)}function Sr(e){G.ensure();const t=M(ee|ye,e);return(n={})=>new Promise(r=>{n.outro?Dn(t,()=>{re(t),r(void 0)}):(re(t),r(void 0))})}function Rr(e){return M(Q,e)}function kn(e){return M(Oe|ye,e)}function xr(e,t=0){return M(we|t,e)}function kr(e,t=[],n=[],r=[]){gt(r,t,n,s=>{M(we,()=>e(...s.map(W)))})}function Or(e,t=[],n=[],r=[]){if(n.length>0||r.length>0)var s=Ke();gt(r,t,n,l=>{M(Q,()=>e(...l.map(W))),s&&s()})}function Nr(e,t=0){var n=M(q|t,e);return n}function Dr(e){return M(F|ye,e)}function Nt(e){var t=e.teardown;if(t!==null){const n=se,r=v;lt(!0),K(null);try{t.call(null)}finally{lt(n),K(r)}}}function Je(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){const s=n.ac;s!==null&&Rt(()=>{s.abort(Y)});var r=n.next;(n.f&ee)!==0?n.parent=null:re(n,t),n=r}}function On(e){for(var t=e.first;t!==null;){var n=t.next;(t.f&F)===0&&re(t),t=n}}function re(e,t=!0){var n=!1;(t||(e.f&Xt)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Nn(e.nodes.start,e.nodes.end),n=!0),y(e,et),Je(e,t&&!n),pe(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(const l of r)l.stop();Nt(e),e.f^=et,e.f|=C;var s=e.parent;s!==null&&s.first!==null&&Dt(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Nn(e,t){for(;e!==null;){var n=e===t?null:$(e);e.remove(),e=n}}function Dt(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Dn(e,t,n=!0){var r=[];It(e,r,!0);var s=()=>{n&&re(e),t&&t()},l=r.length;if(l>0){var u=()=>--l||s();for(var a of r)a.out(u)}else s()}function It(e,t,n){if((e.f&P)===0){e.f^=P;var r=e.nodes&&e.nodes.t;if(r!==null)for(const a of r)(a.is_global||n)&&t.push(a);for(var s=e.first;s!==null;){var l=s.next,u=(s.f&Ae)!==0||(s.f&F)!==0&&(e.f&q)!==0;It(s,t,u?n:!1),s=l}}}function Ir(e){Pt(e,!0)}function Pt(e,t){if((e.f&P)!==0){e.f^=P,(e.f&g)===0&&(y(e,b),G.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,s=(n.f&Ae)!==0||(n.f&F)!==0;Pt(n,s?t:!1),n=r}var l=e.nodes&&e.nodes.t;if(l!==null)for(const u of l)(u.is_global||t)&&u.in()}}function Pr(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var s=n===r?null:$(n);t.append(n),n=s}}let Te=!1,se=!1;function lt(e){se=e}let v=null,I=!1;function K(e){v=e}let d=null;function ue(e){d=e}let O=null;function Ct(e){v!==null&&(O===null?O=[e]:O.push(e))}let A=null,R=0,x=null;function In(e){x=e}let Mt=1,Z=0,J=Z;function at(e){J=e}function Ft(){return++Mt}function Ee(e){var t=e.f;if((t&b)!==0)return!0;if(t&E&&(e.f&=~te),(t&j)!==0){for(var n=e.deps,r=n.length,s=0;s<r;s++){var l=n[s];if(Ee(l)&&Et(l),l.wv>e.wv)return!0}(t&k)!==0&&D===null&&y(e,g)}return!1}function jt(e,t,n=!0){var r=e.reactions;if(r!==null&&!(O!==null&&ie.call(O,e)))for(var s=0;s<r.length;s++){var l=r[s];(l.f&E)!==0?jt(l,t,!1):t===l&&(n?y(l,b):(l.f&g)!==0&&y(l,j),Ge(l))}}function Lt(e){var t=A,n=R,r=x,s=v,l=O,u=T,a=I,i=J,o=e.f;A=null,R=0,x=null,v=(o&(F|ee))===0?e:null,O=null,Se(e.ctx),I=!1,J=++Z,e.ac!==null&&(Rt(()=>{e.ac.abort(Y)}),e.ac=null);try{e.f|=Fe;var f=e.fn,c=f();e.f|=le;var _=e.deps,p=w?.is_fork;if(A!==null){var h;if(p||pe(e,R),_!==null&&R>0)for(_.length=R+A.length,h=0;h<A.length;h++)_[R+h]=A[h];else e.deps=_=A;if(kt()&&(e.f&k)!==0)for(h=R;h<_.length;h++)(_[h].reactions??=[]).push(e)}else!p&&_!==null&&R<_.length&&(pe(e,R),_.length=R);if(ge()&&x!==null&&!I&&_!==null&&(e.f&(E|j|b))===0)for(h=0;h<x.length;h++)jt(x[h],e);if(s!==null&&s!==e){if(Z++,s.deps!==null)for(let N=0;N<n;N+=1)s.deps[N].rv=Z;if(t!==null)for(const N of t)N.rv=Z;x!==null&&(r===null?r=x:r.push(...x))}return(e.f&B)!==0&&(e.f^=B),c}catch(N){return cn(N)}finally{e.f^=Fe,A=t,R=n,x=r,v=s,O=l,Se(u),I=a,J=i}}function Pn(e,t){let n=t.reactions;if(n!==null){var r=Ut.call(n,e);if(r!==-1){var s=n.length-1;s===0?n=t.reactions=null:(n[r]=n[s],n.pop())}}if(n===null&&(t.f&E)!==0&&(A===null||!ie.call(A,t))){var l=t;(l.f&k)!==0&&(l.f^=k,l.f&=~te),Be(l),bn(l),pe(l,0)}}function pe(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)Pn(e,n[r])}function oe(e){var t=e.f;if((t&C)===0){y(e,g);var n=d,r=Te;d=e,Te=!0;try{(t&(q|ut))!==0?On(e):Je(e),Nt(e);var s=Lt(e);e.teardown=typeof s=="function"?s:null,e.wv=Mt;var l}finally{Te=r,d=n}}}async function Cr(){await Promise.resolve(),hn()}function Mr(){return G.ensure().settled()}function W(e){var t=e.f,n=(t&E)!==0;if(v!==null&&!I){var r=d!==null&&(d.f&C)!==0;if(!r&&(O===null||!ie.call(O,e))){var s=v.deps;if((v.f&Fe)!==0)e.rv<Z&&(e.rv=Z,A===null&&s!==null&&s[R]===e?R++:A===null?A=[e]:A.push(e));else{(v.deps??=[]).push(e);var l=e.reactions;l===null?e.reactions=[v]:ie.call(l,v)||l.push(v)}}}if(se&&z.has(e))return z.get(e);if(n){var u=e;if(se){var a=u.v;return((u.f&g)===0&&u.reactions!==null||qt(u))&&(a=Xe(u)),z.set(u,a),a}var i=(u.f&k)===0&&!I&&v!==null&&(Te||(v.f&k)!==0),o=(u.f&le)===0;Ee(u)&&(i&&(u.f|=k),Et(u)),i&&!o&&(mt(u),Yt(u))}if(D?.has(e))return D.get(e);if((e.f&B)!==0)throw e.v;return e.v}function Yt(e){if(e.f|=k,e.deps!==null)for(const t of e.deps)(t.reactions??=[]).push(e),(t.f&E)!==0&&(t.f&k)===0&&(mt(t),Yt(t))}function qt(e){if(e.v===m)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(z.has(t)||(t.f&E)!==0&&qt(t))return!0;return!1}function Fr(e){var t=I;try{return I=!0,e()}finally{I=t}}function jr(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(de in e)He(e);else if(!Array.isArray(e))for(let t in e){const n=e[t];typeof n=="object"&&n&&de in n&&He(n)}}}function He(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let r in e)try{He(e[r],t)}catch{}const n=it(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){const r=Vt(n);for(let s in r){const l=r[s].get;if(l)try{l.call(e)}catch{}}}}}export{Fn as $,W as A,V as B,ct as C,et as D,Ae as E,lr as F,ur as G,Xt as H,fr as I,ve as J,Bn as K,_e as L,se as M,C as N,Jn as O,Wn as P,De as Q,Zn as R,de as S,Xn as T,$e as U,gn as V,Qn as W,Ln as X,Ar as Y,Tr as Z,Kt as _,Rr as a,Hn as a$,jr as a0,cr as a1,yr as a2,kr as a3,_r as a4,wr as a5,ar as a6,gr as a7,Or as a8,An as a9,Re as aA,zn as aB,rr as aC,Rt as aD,pr as aE,sn as aF,Ue as aG,Vn as aH,Er as aI,Sr as aJ,Cn as aK,an as aL,Ve as aM,hn as aN,Cr as aO,jn as aP,Un as aQ,Ht as aR,Gn as aS,$n as aT,Kn as aU,P as aV,F as aW,st as aX,hr as aY,Yn as aZ,fn as a_,ir as aa,U as ab,vr as ac,un as ad,br as ae,Sn as af,er as ag,tr as ah,le as ai,Ne as aj,We as ak,kt as al,Ze as am,Ce as an,tt as ao,$t as ap,ln as aq,nr as ar,vn as as,ue as at,K as au,Se as av,G as aw,cn as ax,v as ay,Ye as az,d as b,it as b0,Vt as b1,Mr as b2,T as c,Ir as d,or as e,re as f,ke as g,Dr as h,w as i,ne as j,S as k,Nr as l,Pr as m,ye as n,$ as o,Dn as p,sr as q,xr as r,mr as s,fe as t,Fr as u,qe as v,xn as w,Mn as x,Gt as y,dr as z};
-1
.svelte-kit/output/client/_app/immutable/chunks/D9RahMPT.js
··· 1 - import{aZ as ge,a_ as mt,aJ as L,A as U,C as T,aI as ne,a$ as wt}from"./w0kPbzMq.js";import{o as Ve}from"./B43_79mg.js";const D=[];function Re(e,t=ge){let n=null;const r=new Set;function a(o){if(mt(e,o)&&(e=o,n)){const l=!D.length;for(const c of r)c[1](),D.push(c,e);if(l){for(let c=0;c<D.length;c+=2)D[c][0](D[c+1]);D.length=0}}}function i(o){a(o(e))}function s(o,l=ge){const c=[o,l];return r.add(c),r.size===1&&(n=t(a,i)||ge),o(e),()=>{r.delete(c),r.size===0&&n&&(n(),n=null)}}return{set:a,update:i,subscribe:s}}class xe{constructor(t,n){this.status=t,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${t}`}}toString(){return JSON.stringify(this.body)}}class Ae{constructor(t,n){this.status=t,this.location=n}}class Le extends Error{constructor(t,n,r){super(r),this.status=t,this.text=n}}new URL("sveltekit-internal://");function vt(e,t){return e==="/"||t==="ignore"?e:t==="never"?e.endsWith("/")?e.slice(0,-1):e:t==="always"&&!e.endsWith("/")?e+"/":e}function yt(e){return e.split("%25").map(decodeURI).join("%25")}function bt(e){for(const t in e)e[t]=decodeURIComponent(e[t]);return e}function _e({href:e}){return e.split("#")[0]}function kt(...e){let t=5381;for(const n of e)if(typeof n=="string"){let r=n.length;for(;r;)t=t*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)t=t*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(t>>>0).toString(36)}new TextEncoder;new TextDecoder;function St(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}const Et=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||"GET")!=="GET"&&W.delete(Ue(e)),Et(e,t));const W=new Map;function Rt(e,t){const n=Ue(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:a,...i}=JSON.parse(r.textContent);const s=r.getAttribute("data-ttl");return s&&W.set(n,{body:a,init:i,ttl:1e3*Number(s)}),r.getAttribute("data-b64")!==null&&(a=St(a)),Promise.resolve(new Response(a,i))}return window.fetch(e,t)}function xt(e,t,n){if(W.size>0){const r=Ue(e,n),a=W.get(r);if(a){if(performance.now()<a.ttl&&["default","force-cache","only-if-cached",void 0].includes(n?.cache))return new Response(a.body,a.init);W.delete(r)}}return window.fetch(t,n)}function Ue(e,t){let r=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){const a=[];t.headers&&a.push([...new Headers(t.headers)].join(",")),t.body&&(typeof t.body=="string"||ArrayBuffer.isView(t.body))&&a.push(t.body),r+=`[data-hash="${kt(...a)}"]`}return r}const At=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;function Lt(e){const t=[];return{pattern:e==="/"?/^\/$/:new RegExp(`^${Tt(e).map(r=>{const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return t.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const i=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(i)return t.push({name:i[1],matcher:i[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const s=r.split(/\[(.+?)\](?!\])/);return"/"+s.map((l,c)=>{if(c%2){if(l.startsWith("x+"))return me(String.fromCharCode(parseInt(l.slice(2),16)));if(l.startsWith("u+"))return me(String.fromCharCode(...l.slice(2).split("-").map(_=>parseInt(_,16))));const f=At.exec(l),[,p,w,h,u]=f;return t.push({name:h,matcher:u,optional:!!p,rest:!!w,chained:w?c===1&&s[0]==="":!1}),w?"([^]*?)":p?"([^/]*)?":"([^/]+?)"}return me(l)}).join("")}).join("")}/?$`),params:t}}function Ut(e){return e!==""&&!/^\([^)]+\)$/.test(e)}function Tt(e){return e.slice(1).split("/").filter(Ut)}function It(e,t,n){const r={},a=e.slice(1),i=a.filter(o=>o!==void 0);let s=0;for(let o=0;o<t.length;o+=1){const l=t[o];let c=a[o-s];if(l.chained&&l.rest&&s&&(c=a.slice(o-s,o+1).filter(f=>f).join("/"),s=0),c===void 0)if(l.rest)c="";else continue;if(!l.matcher||n[l.matcher](c)){r[l.name]=c;const f=t[o+1],p=a[o+1];f&&!f.rest&&f.optional&&p&&l.chained&&(s=0),!f&&!p&&Object.keys(r).length===i.length&&(s=0);continue}if(l.optional&&l.chained){s++;continue}return}if(!s)return r}function me(e){return e.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function Ot({nodes:e,server_loads:t,dictionary:n,matchers:r}){const a=new Set(t);return Object.entries(n).map(([o,[l,c,f]])=>{const{pattern:p,params:w}=Lt(o),h={id:o,exec:u=>{const _=p.exec(u);if(_)return It(_,w,r)},errors:[1,...f||[]].map(u=>e[u]),layouts:[0,...c||[]].map(s),leaf:i(l)};return h.errors.length=h.layouts.length=Math.max(h.errors.length,h.layouts.length),h});function i(o){const l=o<0;return l&&(o=~o),[l,e[o]]}function s(o){return o===void 0?o:[a.has(o),e[o]]}}function Ye(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function Be(e,t,n=JSON.stringify){const r=n(t);try{sessionStorage[e]=r}catch{}}const x=globalThis.__sveltekit_1uytokf?.base??"",Pt=globalThis.__sveltekit_1uytokf?.assets??x??"",$t="1774903841109",He="sveltekit:snapshot",Xe="sveltekit:scroll",Ze="sveltekit:states",Ct="sveltekit:pageurl",B="sveltekit:history",Y="sveltekit:navigation",j={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Te=location.origin;function Qe(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){const n=document.getElementsByTagName("base");t=n.length?n[0].href:document.URL}return new URL(e,t)}function q(){return{x:pageXOffset,y:pageYOffset}}function V(e,t){return e.getAttribute(`data-sveltekit-${t}`)}const Ke={...j,"":j.hover};function et(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function tt(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()==="A"&&e.hasAttribute("href"))return e;e=et(e)}}function ye(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const o=location.hash.split("#")[1]||"/";r.hash=`#${o}${r.hash}`}}catch{}const a=e instanceof SVGAElement?e.target.baseVal:e.target,i=!r||!!a||fe(r,t,n)||(e.getAttribute("rel")||"").split(/\s+/).includes("external"),s=r?.origin===Te&&e.hasAttribute("download");return{url:r,external:i,target:a,download:s}}function re(e){let t=null,n=null,r=null,a=null,i=null,s=null,o=e;for(;o&&o!==document.documentElement;)r===null&&(r=V(o,"preload-code")),a===null&&(a=V(o,"preload-data")),t===null&&(t=V(o,"keepfocus")),n===null&&(n=V(o,"noscroll")),i===null&&(i=V(o,"reload")),s===null&&(s=V(o,"replacestate")),o=et(o);function l(c){switch(c){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:Ke[r??"off"],preload_data:Ke[a??"off"],keepfocus:l(t),noscroll:l(n),reload:l(i),replace_state:l(s)}}function Me(e){const t=Re(e);let n=!0;function r(){n=!0,t.update(s=>s)}function a(s){n=!1,t.set(s)}function i(s){let o;return t.subscribe(l=>{(o===void 0||n&&l!==o)&&s(o=l)})}return{notify:r,set:a,subscribe:i}}const nt={v:()=>{}};function jt(){const{set:e,subscribe:t}=Re(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Pt}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const s=(await a.json()).version!==$t;return s&&(e(!0),nt.v(),clearTimeout(n)),s}catch{return!1}}return{subscribe:t,check:r}}function fe(e,t,n){return e.origin!==Te||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function fn(e){}const rt=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...rt];const Nt=new Set([...rt]);[...Nt];function qt(e){return e.filter(t=>t!=null)}function Ie(e){return e instanceof xe||e instanceof Le?e.status:500}function Dt(e){return e instanceof Le?e.text:"Internal Error"}let k,H,we;const Vt=Ve.toString().includes("$$")||/function \w+\(\) \{\}/.test(Ve.toString()),ze="a:";Vt?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(ze)},H={current:null},we={current:!1}):(k=new class{#e=L({});get data(){return U(this.#e)}set data(t){T(this.#e,t)}#t=L(null);get form(){return U(this.#t)}set form(t){T(this.#t,t)}#n=L(null);get error(){return U(this.#n)}set error(t){T(this.#n,t)}#r=L({});get params(){return U(this.#r)}set params(t){T(this.#r,t)}#a=L({id:null});get route(){return U(this.#a)}set route(t){T(this.#a,t)}#o=L({});get state(){return U(this.#o)}set state(t){T(this.#o,t)}#s=L(-1);get status(){return U(this.#s)}set status(t){T(this.#s,t)}#i=L(new URL(ze));get url(){return U(this.#i)}set url(t){T(this.#i,t)}},H=new class{#e=L(null);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},we=new class{#e=L(!1);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},nt.v=()=>we.current=!0);function Bt(e){Object.assign(k,e)}const Kt=new Set(["icon","shortcut icon","apple-touch-icon"]);let F=null;const C=Ye(Xe)??{},X=Ye(He)??{},$={url:Me({}),page:Me({}),navigating:Re(null),updated:jt()};function Oe(e){C[e]=q()}function Mt(e,t){let n=e+1;for(;C[n];)delete C[n],n+=1;for(n=t+1;X[n];)delete X[n],n+=1}function Z(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(()=>{})}async function at(){if("serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration(x||"/");e&&await e.update()}}function Fe(){}let Pe,be,ae,I,ke,y;const oe=[],se=[];let A=null;function Se(){A?.fork?.then(e=>e?.discard()),A=null}const te=new Map,ot=new Set,zt=new Set,J=new Set;let m={branch:[],error:null,url:null},st=!1,ie=!1,Ge=!0,Q=!1,G=!1,it=!1,$e=!1,lt,v,R,N;const le=new Set,We=new Map;async function gn(e,t,n){globalThis.__sveltekit_1uytokf?.data&&globalThis.__sveltekit_1uytokf.data,document.URL!==location.href&&(location.href=location.href),y=e,await e.hooks.init?.(),Pe=Ot(e),I=document.documentElement,ke=t,be=e.nodes[0],ae=e.nodes[1],be(),ae(),v=history.state?.[B],R=history.state?.[Y],v||(v=R=Date.now(),history.replaceState({...history.state,[B]:v,[Y]:R},""));const r=C[v];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await an(ke,n)):(await K({type:"enter",url:Qe(y.hash?ln(new URL(location.href)):location.href),replace_state:!0}),a()),rn()}function Ft(){oe.length=0,$e=!1}function ct(e){se.some(t=>t?.snapshot)&&(X[e]=se.map(t=>t?.snapshot?.capture()))}function ut(e){X[e]?.forEach((t,n)=>{se[n]?.snapshot?.restore(t)})}function Je(){Oe(v),Be(Xe,C),ct(R),Be(He,X)}async function Gt(e,t,n,r){let a;t.invalidateAll&&Se(),await K({type:"goto",url:Qe(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:n,nav_token:r,accept:()=>{t.invalidateAll&&($e=!0,a=[...We.keys()]),t.invalidate&&t.invalidate.forEach(nn)}}),t.invalidateAll&&ne().then(ne).then(()=>{We.forEach(({resource:i},s)=>{a?.includes(s)&&i.refresh?.()})})}async function Wt(e){if(e.id!==A?.id){Se();const t={};le.add(t),A={id:e.id,token:t,promise:dt({...e,preload:t}).then(n=>(le.delete(t),n.type==="loaded"&&n.state.error&&Se(),n)),fork:null}}return A.promise}async function ve(e){const t=(await de(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(n=>n[1]()))}async function ft(e,t,n){const r={params:m.params,route:{id:m.route?.id??null},url:new URL(location.href)};m={...e.state,nav:r};const a=document.querySelector("style[data-sveltekit]");if(a&&a.remove(),Object.assign(k,e.props.page),lt=new y.root({target:t,props:{...e.props,stores:$,components:se},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),ut(R),n){const i={from:null,to:{...r,scroll:C[v]??q()},willUnload:!1,type:"enter",complete:Promise.resolve()};J.forEach(s=>s(i))}ie=!0}async function ce({url:e,params:t,branch:n,errors:r,status:a,error:i,route:s,form:o}){let l="never";if(x&&(e.pathname===x||e.pathname===x+"/"))l="always";else for(const u of n)u?.slash!==void 0&&(l=u.slash);e.pathname=vt(e.pathname,l),e.search=e.search;const c={type:"loaded",state:{url:e,params:t,branch:n,error:i,route:s},props:{constructors:qt(n).map(u=>u.node.component),page:De(k)}};o!==void 0&&(c.props.form=o);let f={},p=!k,w=0;for(let u=0;u<Math.max(n.length,m.branch.length);u+=1){const _=n[u],g=m.branch[u];_?.data!==g?.data&&(p=!0),_&&(f={...f,..._.data},p&&(c.props[`data_${w}`]=f),w+=1)}return(!m.url||e.href!==m.url.href||m.error!==i||o!==void 0&&o!==k.form||p)&&(c.props.page={error:i,params:t,route:{id:s?.id??null},state:{},status:a,url:new URL(e),form:o??null,data:p?f:k.data}),c}async function Ce({loader:e,parent:t,url:n,params:r,route:a,server_data_node:i}){let s=null;const o={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();return{node:l,loader:e,server:i,universal:l.universal?.load?{type:"data",data:s,uses:o}:null,data:s??i?.data??null,slash:l.universal?.trailingSlash??i?.slash}}function Jt(e,t,n){let r=e instanceof Request?e.url:e;const a=new URL(r,n);a.origin===n.origin&&(r=a.href.slice(n.origin.length));const i=ie?xt(r,a.href,t):Rt(r,t);return{resolved:a,promise:i}}function Yt(e,t,n,r,a,i){if($e)return!0;if(!a)return!1;if(a.parent&&e||a.route&&t||a.url&&n)return!0;for(const s of a.search_params)if(r.has(s))return!0;for(const s of a.params)if(i[s]!==m.params[s])return!0;for(const s of a.dependencies)if(oe.some(o=>o(new URL(s))))return!0;return!1}function je(e,t){return e?.type==="data"?e:e?.type==="skip"?t??null:null}function Ht(e,t){if(!e)return new Set(t.searchParams.keys());const n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(const r of n){const a=e.searchParams.getAll(r),i=t.searchParams.getAll(r);a.every(s=>i.includes(s))&&i.every(s=>a.includes(s))&&n.delete(r)}return n}function Xt({error:e,url:t,route:n,params:r}){return{type:"loaded",state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:De(k),constructors:[]}}}async function dt({id:e,invalidating:t,url:n,params:r,route:a,preload:i}){if(A?.id===e)return le.delete(A.token),A.promise;const{errors:s,layouts:o,leaf:l}=a,c=[...o,l];s.forEach(g=>g?.().catch(()=>{})),c.forEach(g=>g?.[1]().catch(()=>{}));const f=m.url?e!==ue(m.url):!1,p=m.route?a.id!==m.route.id:!1,w=Ht(m.url,n);let h=!1;const u=c.map(async(g,d)=>{if(!g)return;const S=m.branch[d];return g[1]===S?.loader&&!Yt(h,p,f,w,S.universal?.uses,r)?S:(h=!0,Ce({loader:g[1],url:n,params:r,route:a,parent:async()=>{const O={};for(let P=0;P<d;P+=1)Object.assign(O,(await u[P])?.data);return O},server_data_node:je(g[0]?{type:"skip"}:null,g[0]?S?.server:void 0)}))});for(const g of u)g.catch(()=>{});const _=[];for(let g=0;g<c.length;g+=1)if(c[g])try{_.push(await u[g])}catch(d){if(d instanceof Ae)return{type:"redirect",location:d.location};if(le.has(i))return Xt({error:await ee(d,{params:r,url:n,route:{id:a.id}}),url:n,params:r,route:a});let S=Ie(d),E;if(d instanceof xe)E=d.body;else{if(await $.updated.check())return await at(),await Z(n);E=await ee(d,{params:r,url:n,route:{id:a.id}})}const O=await Zt(g,_,s);return O?ce({url:n,params:r,branch:_.slice(0,O.idx).concat(O.node),errors:s,status:S,error:E,route:a}):await pt(n,{id:a.id},E,S)}else _.push(void 0);return ce({url:n,params:r,branch:_,errors:s,status:200,error:null,route:a,form:t?void 0:null})}async function Zt(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)r-=1;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function Ne({status:e,error:t,url:n,route:r}){const a={};let i=null;try{const s=await Ce({loader:be,url:n,params:a,route:r,parent:()=>Promise.resolve({}),server_data_node:je(i)}),o={node:await ae(),loader:ae,universal:null,server:null,data:null};return ce({url:n,params:a,branch:[s,o],status:e,error:t,errors:[],route:null})}catch(s){if(s instanceof Ae)return Gt(new URL(s.location,location.href),{},0);throw s}}async function Qt(e){const t=e.href;if(te.has(t))return te.get(t);let n;try{const r=(async()=>{let a=await y.hooks.reroute({url:new URL(e),fetch:async(i,s)=>Jt(i,s,e).promise})??e;if(typeof a=="string"){const i=new URL(e);y.hash?i.hash=a:i.pathname=a,a=i}return a})();te.set(t,r),n=await r}catch{te.delete(t);return}return n}async function de(e,t){if(e&&!fe(e,x,y.hash)){const n=await Qt(e);if(!n)return;const r=en(n);for(const a of Pe){const i=a.exec(r);if(i)return{id:ue(e),invalidating:t,route:a,params:bt(i),url:e}}}}function en(e){return yt(y.hash?e.hash.replace(/^#/,"").replace(/[?#].+/,""):e.pathname.slice(x.length))||"/"}function ue(e){return(y.hash?e.hash.replace(/^#/,""):e.pathname)+e.search}function ht({url:e,type:t,intent:n,delta:r,event:a,scroll:i}){let s=!1;const o=qe(m,n,e,t,i??null);r!==void 0&&(o.navigation.delta=r),a!==void 0&&(o.navigation.event=a);const l={...o.navigation,cancel:()=>{s=!0,o.reject(new Error("navigation cancelled"))}};return Q||ot.forEach(c=>c(l)),s?null:o}async function K({type:e,url:t,popped:n,keepfocus:r,noscroll:a,replace_state:i,state:s={},redirect_count:o=0,nav_token:l={},accept:c=Fe,block:f=Fe,event:p}){const w=N;N=l;const h=await de(t,!1),u=e==="enter"?qe(m,h,t,e):ht({url:t,type:e,delta:n?.delta,intent:h,scroll:n?.scroll,event:p});if(!u){f(),N===l&&(N=w);return}const _=v,g=R;c(),Q=!0,ie&&u.navigation.type!=="enter"&&$.navigating.set(H.current=u.navigation);let d=h&&await dt(h);if(!d){if(fe(t,x,y.hash))return await Z(t,i);d=await pt(t,{id:null},await ee(new Le(404,"Not Found",`Not found: ${t.pathname}`),{url:t,params:{},route:{id:null}}),404,i)}if(t=h?.url||t,N!==l)return u.reject(new Error("navigation aborted")),!1;if(d.type==="redirect"){if(o<20){await K({type:e,url:new URL(d.location,t),popped:n,keepfocus:r,noscroll:a,replace_state:i,state:s,redirect_count:o+1,nav_token:l}),u.fulfil(void 0);return}d=await Ne({status:500,error:await ee(new Error("Redirect loop"),{url:t,params:{},route:{id:null}}),url:t,route:{id:null}})}else d.props.page.status>=400&&await $.updated.check()&&(await at(),await Z(t,i));if(Ft(),Oe(_),ct(g),d.props.page.url.pathname!==t.pathname&&(t.pathname=d.props.page.url.pathname),s=n?n.state:s,!n){const b=i?0:1,M={[B]:v+=b,[Y]:R+=b,[Ze]:s};(i?history.replaceState:history.pushState).call(history,M,"",t),i||Mt(v,R)}const S=h&&A?.id===h.id?A.fork:null;A=null,d.props.page.state=s;let E;if(ie){const b=(await Promise.all(Array.from(zt,z=>z(u.navigation)))).filter(z=>typeof z=="function");if(b.length>0){let z=function(){b.forEach(pe=>{J.delete(pe)})};b.push(z),b.forEach(pe=>{J.add(pe)})}const M=u.navigation.to;m={...d.state,nav:{params:M.params,route:M.route,url:M.url}},d.props.page&&(d.props.page.url=t);const he=S&&await S;he?E=he.commit():(F=null,lt.$set(d.props),F&&Object.assign(d.props.page,F),Bt(d.props.page),E=wt?.()),it=!0}else await ft(d,ke,!1);const{activeElement:O}=document;await E,await ne(),await ne();let P=null;if(Ge){const b=n?n.scroll:a?q():null;b?scrollTo(b.x,b.y):(P=t.hash&&document.getElementById(gt(t)))?P.scrollIntoView():scrollTo(0,0)}const _t=document.activeElement!==O&&document.activeElement!==document.body;!r&&!_t&&sn(t,!P),Ge=!0,d.props.page&&(F&&Object.assign(d.props.page,F),Object.assign(k,d.props.page)),Q=!1,e==="popstate"&&ut(R),u.fulfil(void 0),u.navigation.to&&(u.navigation.to.scroll=q()),J.forEach(b=>b(u.navigation)),$.navigating.set(H.current=null)}async function pt(e,t,n,r,a){return e.origin===Te&&e.pathname===location.pathname&&!st?await Ne({status:r,error:n,url:e,route:t}):await Z(e,a)}function tn(){let e,t={element:void 0,href:void 0},n;I.addEventListener("mousemove",o=>{const l=o.target;clearTimeout(e),e=setTimeout(()=>{i(l,j.hover)},20)});function r(o){o.defaultPrevented||i(o.composedPath()[0],j.tap)}I.addEventListener("mousedown",r),I.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(o=>{for(const l of o)l.isIntersecting&&(ve(new URL(l.target.href)),a.unobserve(l.target))},{threshold:0});async function i(o,l){const c=tt(o,I),f=c===t.element&&c?.href===t.href&&l>=n;if(!c||f)return;const{url:p,external:w,download:h}=ye(c,x,y.hash);if(w||h)return;const u=re(c),_=p&&ue(m.url)===ue(p);if(!(u.reload||_))if(l<=u.preload_data){t={element:c,href:c.href},n=j.tap;const g=await de(p,!1);if(!g)return;Wt(g)}else l<=u.preload_code&&(t={element:c,href:c.href},n=l,ve(p))}function s(){a.disconnect();for(const o of I.querySelectorAll("a")){const{url:l,external:c,download:f}=ye(o,x,y.hash);if(c||f)continue;const p=re(o);p.reload||(p.preload_code===j.viewport&&a.observe(o),p.preload_code===j.eager&&ve(l))}}J.add(s),s()}function ee(e,t){if(e instanceof xe)return e.body;const n=Ie(e),r=Dt(e);return y.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function nn(e){if(typeof e=="function")oe.push(e);else{const{href:t}=new URL(e,location.href);oe.push(n=>n.href===t)}}function rn(){history.scrollRestoration="manual",addEventListener("beforeunload",t=>{let n=!1;if(Je(),!Q){const r=qe(m,void 0,null,"leave"),a={...r.navigation,cancel:()=>{n=!0,r.reject(new Error("navigation cancelled"))}};ot.forEach(i=>i(a))}n?(t.preventDefault(),t.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Je()}),navigator.connection?.saveData||tn(),I.addEventListener("click",async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;const n=tt(t.composedPath()[0],I);if(!n)return;const{url:r,external:a,target:i,download:s}=ye(n,x,y.hash);if(!r)return;if(i==="_parent"||i==="_top"){if(window.parent!==window)return}else if(i&&i!=="_self")return;const o=re(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&!(r.protocol==="https:"||r.protocol==="http:")||s)return;const[c,f]=(y.hash?r.hash.replace(/^#/,""):r.href).split("#"),p=c===_e(location);if(a||o.reload&&(!p||!f)){ht({url:r,type:"link",event:t})?Q=!0:t.preventDefault();return}if(f!==void 0&&p){const[,w]=m.url.href.split("#");if(w===f){if(t.preventDefault(),f===""||f==="top"&&n.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=n.ownerDocument.getElementById(decodeURIComponent(f));h&&(h.scrollIntoView(),h.focus())}return}if(G=!0,Oe(v),e(r),!o.replace_state)return;G=!1}t.preventDefault(),await new Promise(w=>{requestAnimationFrame(()=>{setTimeout(w,0)}),setTimeout(w,100)}),await K({type:"link",url:r,keepfocus:o.keepfocus,noscroll:o.noscroll,replace_state:o.replace_state??r.href===location.href,event:t})}),I.addEventListener("submit",t=>{if(t.defaultPrevented)return;const n=HTMLFormElement.prototype.cloneNode.call(t.target),r=t.submitter;if((r?.formTarget||n.target)==="_blank"||(r?.formMethod||n.method)!=="get")return;const s=new URL(r?.hasAttribute("formaction")&&r?.formAction||n.action);if(fe(s,x,!1))return;const o=t.target,l=re(o);if(l.reload)return;t.preventDefault(),t.stopPropagation();const c=new FormData(o,r);s.search=new URLSearchParams(c).toString(),K({type:"form",url:s,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??s.href===location.href,event:t})}),addEventListener("popstate",async t=>{if(!Ee){if(t.state?.[B]){const n=t.state[B];if(N={},n===v)return;const r=C[n],a=t.state[Ze]??{},i=new URL(t.state[Ct]??location.href),s=t.state[Y],o=m.url?_e(location)===_e(m.url):!1;if(s===R&&(it||o)){a!==k.state&&(k.state=a),e(i),C[v]=q(),r&&scrollTo(r.x,r.y),v=n;return}const c=n-v;await K({type:"popstate",url:i,popped:{state:a,scroll:r,delta:c},accept:()=>{v=n,R=s},block:()=>{history.go(-c)},nav_token:N,event:t})}else if(!G){const n=new URL(location.href);e(n),y.hash&&location.reload()}}}),addEventListener("hashchange",()=>{G&&(G=!1,history.replaceState({...history.state,[B]:++v,[Y]:R},"",location.href))});for(const t of document.querySelectorAll("link"))Kt.has(t.rel)&&(t.href=t.href);addEventListener("pageshow",t=>{t.persisted&&$.navigating.set(H.current=null)});function e(t){m.url=k.url=t,$.page.set(De(k)),$.page.notify()}}async function an(e,{status:t=200,error:n,node_ids:r,params:a,route:i,server_route:s,data:o,form:l}){st=!0;const c=new URL(location.href);let f;({params:a={},route:i={id:null}}=await de(c,!1)||{}),f=Pe.find(({id:h})=>h===i.id);let p,w=!0;try{const h=r.map(async(_,g)=>{const d=o[g];return d?.uses&&(d.uses=on(d.uses)),Ce({loader:y.nodes[_],url:c,params:a,route:i,parent:async()=>{const S={};for(let E=0;E<g;E+=1)Object.assign(S,(await h[E]).data);return S},server_data_node:je(d)})}),u=await Promise.all(h);if(f){const _=f.layouts;for(let g=0;g<_.length;g++)_[g]||u.splice(g,0,void 0)}p=await ce({url:c,params:a,branch:u,status:t,error:n,errors:f?.errors,form:l,route:f??null})}catch(h){if(h instanceof Ae){await Z(new URL(h.location,location.href));return}p=await Ne({status:Ie(h),error:await ee(h,{url:c,params:a,route:i}),url:c,route:i}),e.textContent="",w=!1}p.props.page&&(p.props.page.state={}),await ft(p,e,w)}function on(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}let Ee=!1;function sn(e,t=!0){const n=document.querySelector("[autofocus]");if(n)n.focus();else{const r=gt(e);if(r&&document.getElementById(r)){const{x:i,y:s}=q();setTimeout(()=>{const o=history.state;Ee=!0,location.replace(new URL(`#${r}`,location.href)),history.replaceState(o,"",e),t&&scrollTo(i,s),Ee=!1})}else{const i=document.body,s=i.getAttribute("tabindex");i.tabIndex=-1,i.focus({preventScroll:!0,focusVisible:!1}),s!==null?i.setAttribute("tabindex",s):i.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const i=[];for(let s=0;s<a.rangeCount;s+=1)i.push(a.getRangeAt(s));setTimeout(()=>{if(a.rangeCount===i.length){for(let s=0;s<a.rangeCount;s+=1){const o=i[s],l=a.getRangeAt(s);if(o.commonAncestorContainer!==l.commonAncestorContainer||o.startContainer!==l.startContainer||o.endContainer!==l.endContainer||o.startOffset!==l.startOffset||o.endOffset!==l.endOffset)return}a.removeAllRanges()}})}}}function qe(e,t,n,r,a=null){let i,s;const o=new Promise((c,f)=>{i=c,s=f});return o.catch(()=>{}),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:q()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:a},willUnload:!t,type:r,complete:o},fulfil:i,reject:s}}function De(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function ln(e){const t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function gt(e){let t;if(y.hash){const[,,n]=e.hash.split("#",3);t=n??""}else t=e.hash.slice(1);return decodeURIComponent(t)}export{gn as a,fn as l,k as p,$ as s};
+1
.svelte-kit/output/client/_app/immutable/chunks/DGbOEUpF.js
··· 1 + import{ae as v,v as u,af as T,ag as p,ah as h,b as l,j as i,k as s,ai as g,F as E,g as d,aj as y,t as w,ak as N}from"./CkzjbUDB.js";const M=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:t=>t});function b(t){return M?.createHTML(t)??t}function x(t){var r=v("template");return r.innerHTML=b(t.replaceAll("<!>","<!---->")),r.content}function n(t,r){var e=l;e.nodes===null&&(e.nodes={start:t,end:r,a:null,t:null})}function O(t,r){var e=(r&p)!==0,f=(r&h)!==0,a,_=!t.startsWith("<!>");return()=>{if(i)return n(s,null),s;a===void 0&&(a=x(_?t:"<!>"+t),e||(a=u(a)));var o=f||T?document.importNode(a,!0):a.cloneNode(!0);if(e){var c=u(o),m=o.lastChild;n(c,m)}else n(o,o);return o}}function P(t=""){if(!i){var r=d(t+"");return n(r,r),r}var e=s;return e.nodeType!==y?(e.before(e=d()),w(e)):N(e),n(e,e),e}function R(){if(i)return n(s,null),s;var t=document.createDocumentFragment(),r=document.createComment(""),e=d();return t.append(r,e),n(r,e),t}function C(t,r){if(i){var e=l;((e.f&g)===0||e.nodes.end===null)&&(e.nodes.end=s),E();return}t!==null&&t.before(r)}const A="5";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add(A);export{C as a,n as b,R as c,O as f,P as t};
+2
.svelte-kit/output/client/_app/immutable/chunks/D_t83wNY.js
··· 1 + import{a as Z,f as z}from"./DGbOEUpF.js";import{j as B,aZ as at,a_ as ct,a$ as it,b0 as lt,b1 as pt,a1 as J,a5 as y,a7 as Y,a6 as w,a3 as ft,a4 as Q,aa as V}from"./CkzjbUDB.js";import{s as ut}from"./DmyE0d-6.js";import{p as $}from"./XE2G8ySY.js";import{d as ht,a as gt}from"./BsDbD4Ku.js";const G=[...` 2 + \r\f \v\uFEFF`];function Tt(t,e,s){var r=t==null?"":""+t;if(s){for(var n of Object.keys(s))if(s[n])r=r?r+" "+n:n;else if(r.length)for(var a=n.length,p=0;(p=r.indexOf(n,p))>=0;){var g=p+a;(p===0||G.includes(r[p-1]))&&(g===r.length||G.includes(r[g]))?r=(p===0?"":r.substring(0,p))+r.substring(g+1):p=g}}return r===""?null:r}function dt(t,e){return t==null?null:String(t)}function E(t,e,s,r){var n=t.__style;if(B||n!==e){var a=dt(e);(!B||a!==t.getAttribute("style"))&&(a==null?t.removeAttribute("style"):t.style.cssText=a),t.__style=e}return r}const vt=Symbol("is custom element"),mt=Symbol("is html"),kt=it?"link":"LINK";function j(t,e,s,r){var n=yt(t);B&&(n[e]=t.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&t.nodeName===kt)||n[e]!==(n[e]=s)&&(e==="loading"&&(t[at]=s),s==null?t.removeAttribute(e):typeof s!="string"&&wt(t).includes(e)?t[e]=s:t.setAttribute(e,s))}function yt(t){return t.__attributes??={[vt]:t.nodeName.includes("-"),[mt]:t.namespaceURI===ct}}var X=new Map;function wt(t){var e=t.getAttribute("is")||t.nodeName,s=X.get(e);if(s)return s;X.set(e,s=[]);for(var r,n=t,a=Element.prototype;a!==n;){r=pt(n);for(var p in r)r[p].set&&s.push(p);n=lt(n)}return s}const xt="https://iameli.com",_t="did:plc:rbvrr34edl5ddpuwcubjiost",bt="place.stream.video",St="https://vod-beta.stream.place/xrpc/place.stream.playback.getVideoPlaylist";async function Dt(t,e=20){const s=new URLSearchParams({repo:_t,collection:bt,limit:String(e)});t&&s.set("cursor",t);const r=await fetch(`${xt}/xrpc/com.atproto.repo.listRecords?${s}`);if(!r.ok)throw new Error(`Failed to fetch records: ${r.status}`);return r.json()}function Bt(t){return`${St}?uri=${encodeURIComponent(t)}`}function Nt(t){const e=Math.floor(t/1e9),s=Math.floor(e/3600),r=Math.floor(e%3600/60),n=e%60;return s>0?`${s}:${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${r}:${String(n).padStart(2,"0")}`}function Ot(t){return new Date(t).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const Pt="https://public.api.bsky.app";async function Ht(t){const e=new URLSearchParams({actor:t}),s=await fetch(`${Pt}/xrpc/app.bsky.actor.getProfile?${e}`);if(!s.ok)throw new Error(`Failed to fetch profile: ${s.status}`);return s.json()}const T=new Map;async function Kt(t){if(T.has(t))return T.get(t);try{const e=await fetch(`https://plc.directory/${t}`);if(!e.ok)return t;const r=(await e.json()).alsoKnownAs?.[0],n=r?r.replace("at://","@"):t;return T.set(t,n),n}catch{return t}}const D=new Map;async function $t(t){if(D.has(t))return D.get(t);try{const e=await fetch(`https://plc.directory/${t}`);if(!e.ok)return null;const n=(await e.json()).service?.find(a=>a.id==="#atproto_pds"||a.type==="AtprotoPersonalDataServer")?.serviceEndpoint??null;return n&&D.set(t,n),n}catch{return null}}function At(t){const e=t.match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);return e?{repo:e[1],collection:e[2],rkey:e[3]}:null}const A=new Map;async function Wt(t){const e=t.value.livestream?.uri;if(!e)return null;if(A.has(e))return A.get(e);try{const s=At(e);if(!s)return null;const r=await $t(s.repo);if(!r)return null;const n=new URLSearchParams({repo:s.repo,collection:s.collection,rkey:s.rkey}),a=await fetch(`${r}/xrpc/com.atproto.repo.getRecord?${n}`);if(!a.ok)return null;const g=(await a.json()).value?.thumb?.ref?.$link;if(!g)return null;const _=`${r}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(s.repo)}&cid=${encodeURIComponent(g)}`;return A.set(e,_),_}catch{return A.set(e,null),null}}function v(t,e=0){let s=0;const r=t+String(e);for(let n=0;n<r.length;n++){const a=r.charCodeAt(n);s=(s<<5)-s+a|0}return(s%65536+65536)%65536/65536}function qt(t){const e=v(t,0),s=v(t,1),r=v(t,2);return{rotation:(e-.5)*6,translateX:(s-.5)*12,translateY:(r-.5)*60}}var Mt=z('<div class="wavy-container svelte-7frlgw"><div class="wavy-clipped svelte-7frlgw"><div class="wavy-fill svelte-7frlgw"></div> <div class="wavy-content svelte-7frlgw"><!></div></div> <svg class="wavy-stroke svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" overflow="visible"><path fill="none" stroke-linejoin="round" stroke-linecap="round"></path></svg></div>');function Yt(t,e){J(e,!0);let s=$(e,"fill",3,"#39FF44"),r=$(e,"strokeColor",3,"#0A182B"),n=$(e,"strokeWidth",3,3),a=$(e,"padding",3,"16px");const p=typeof a()=="number"?`${a()}px`:a(),{pts:g,svgPath:_}=et(e.seed),tt=`polygon(${g.map(([m,K])=>`${m.toFixed(2)}% ${K.toFixed(2)}%`).join(", ")})`;function et(m){const rt=[0,1,2,3].map(o=>({phase1:v(m,o*10+1)*Math.PI*2,phase2:v(m,o*10+2)*Math.PI*2,freq1:1.5+v(m,o*10+3)*1.5,freq2:3+v(m,o*10+4)*2,ampScale:.7+v(m,o*10+5)*.6}));function P(o,i){const l=rt[o],f=Math.sin(i*l.freq1*Math.PI*2+l.phase1)*2.5*.7,k=Math.sin(i*l.freq2*Math.PI*2+l.phase2)*2.5*.3;return(f+k)*l.ampScale}const c=[];for(let o=0;o<=16;o++){const i=o/16;c.push([1+i*98,1+P(0,i)])}for(let o=1;o<=16;o++){const i=o/16;c.push([99+P(1,i),1+i*98])}for(let o=1;o<=16;o++){const i=o/16;c.push([99-i*98,99+P(2,i)])}for(let o=1;o<16;o++){const i=o/16;c.push([1+P(3,i),99-i*98])}let C=`M ${c[0][0].toFixed(1)} ${c[0][1].toFixed(1)}`;for(let o=0;o<c.length;o++){const i=c[(o-1+c.length)%c.length],l=c[o],f=c[(o+1)%c.length],k=c[(o+2)%c.length],d=.3,I=l[0]+(f[0]-i[0])*d,L=l[1]+(f[1]-i[1])*d,F=f[0]-(k[0]-l[0])*d,U=f[1]-(k[1]-l[1])*d;C+=` C ${I.toFixed(1)} ${L.toFixed(1)}, ${F.toFixed(1)} ${U.toFixed(1)}, ${f[0].toFixed(1)} ${f[1].toFixed(1)}`}C+=" Z";const W=[],x=c.length,q=10;for(let o=0;o<x;o++){const i=c[(o-1+x)%x],l=c[o],f=c[(o+1)%x],k=c[(o+2)%x],d=.3,I=l[0]+(f[0]-i[0])*d,L=l[1]+(f[1]-i[1])*d,F=f[0]-(k[0]-l[0])*d,U=f[1]-(k[1]-l[1])*d;for(let R=0;R<q;R++){const u=R/q,h=1-u,nt=h*h*h*l[0]+3*h*h*u*I+3*h*u*u*F+u*u*u*f[0],ot=h*h*h*l[1]+3*h*h*u*L+3*h*u*u*U+u*u*u*f[1];W.push([nt,ot])}}return{pts:W,svgPath:C}}var b=Mt(),S=y(b),N=y(S),O=Y(N,2),st=y(O);ut(st,()=>e.children),w(O),w(S);var H=Y(S,2),M=y(H);w(H),w(b),ft(()=>{E(b,`--padding: ${p??""};`),E(S,`clip-path: ${tt};`),E(N,`background: ${s()??""};`),j(M,"d",_),j(M,"stroke",r()),j(M,"stroke-width",n())}),Z(t,b),Q()}var Ct=z('<header class="frog-header svelte-1kxia9k"><div class="title-area svelte-1kxia9k"><a href="/" class="logo-link svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1></a> <img src="/froggie.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k"><a href="https://witchsky.app/profile/goose.art" target="_blank" class="subtitle-link svelte-1kxia9k">@goose.art</a> using <a href="https://witchsky.app/profile/stream.place" target="_blank" class="subtitle-link svelte-1kxia9k">@stream.place</a></p></div></header>');function Vt(t,e){J(e,!0);function s(p){e.onHomeClick&&(p.preventDefault(),e.onHomeClick())}var r=Ct(),n=y(r),a=y(n);V(2),w(n),V(2),w(r),gt("click",a,s),Z(t,r),Q()}ht(["click"]);export{Vt as F,Yt as W,E as a,qt as b,Wt as c,Ot as d,Bt as e,Nt as f,Ht as g,Dt as l,Kt as r,j as s,Tt as t};
+1
.svelte-kit/output/client/_app/immutable/chunks/DmyE0d-6.js
··· 1 + import{l as o,E as p,g as u,H as y,n as _,j as l,C as g,o as r,q as E,t as d,k as m,v}from"./CkzjbUDB.js";import{B as T}from"./CFYBLbZM.js";function c(a,n,...s){var i=new T(a);o(()=>{const t=n()??null;i.ensure(t,t&&(e=>t(e,...s)))},p)}function N(a,n){let s=null,i=l;var t;if(l){s=m;for(var e=v(document.head);e!==null&&(e.nodeType!==g||e.data!==a);)e=r(e);if(e===null)E(!1);else{var f=r(e);e.remove(),d(f)}}l||(t=document.head.appendChild(u()));try{o(()=>n(t),y|_)}finally{i&&(E(!0),d(s))}}export{N as h,c as s};
+1
.svelte-kit/output/client/_app/immutable/chunks/Dr80VTgO.js
··· 1 + import{c as w,a as S,r as b,u as h,b as o,D as T,S as e}from"./CkzjbUDB.js";function n(r,s){return r===s||r?.[e]===s}function x(r={},s,i,l){var c=w.r,d=o;return S(()=>{var f,a;return b(()=>{f=a,a=[],h(()=>{r!==i(...a)&&(s(r,...a),f&&n(i(...f),r)&&s(null,...f))})}),()=>{let t=d;for(;t!==c&&t.parent!==null&&t.parent.f&T;)t=t.parent;const p=()=>{a&&n(i(...a),r)&&s(null,...a)},u=t.teardown;t.teardown=()=>{p(),u?.()}}}),r}export{x as b};
-1
.svelte-kit/output/client/_app/immutable/chunks/DsupRLPE.js
··· 1 - import{e}from"./w0kPbzMq.js";e();
+1
.svelte-kit/output/client/_app/immutable/chunks/DxGD2b0U.js
··· 1 + import{y as i,u as a,ad as d,Z as m,c as r,Q as g}from"./CkzjbUDB.js";function _(n){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function h(n,e,s){if(n==null)return e(void 0),i;const u=a(()=>n.subscribe(e,s));return u.unsubscribe?()=>u.unsubscribe():u}const c=[];function k(n,e=i){let s=null;const u=new Set;function f(o){if(d(n,o)&&(n=o,s)){const l=!c.length;for(const t of u)t[1](),c.push(t,n);if(l){for(let t=0;t<c.length;t+=2)c[t][0](c[t+1]);c.length=0}}}function b(o){f(o(n))}function p(o,l=i){const t=[o,l];return u.add(t),u.size===1&&(s=e(f,b)||i),o(n),()=>{u.delete(t),u.size===0&&s&&(s(),s=null)}}return{set:f,update:b,subscribe:p}}function x(n){let e;return h(n,s=>e=s)(),e}function y(n){r===null&&_(),g&&r.l!==null?w(r).m.push(n):m(()=>{const e=a(n);if(typeof e=="function")return e})}function z(n){r===null&&_(),y(()=>()=>a(n))}function w(n){var e=n.l;return e.u??={a:[],b:[],m:[]}}export{z as a,x as g,y as o,h as s,k as w};
+1
.svelte-kit/output/client/_app/immutable/chunks/XE2G8ySY.js
··· 1 + import{w as B,x as L,y as m,z as D,A as S,B as A,l as M,j as R,F as U,E as p,G as w,I as x,t as Y,q as T,k as F,J as $,K as q,P as z,L as C,M as G,b as j,N as J,O as K,u as Q,Q as V,R as W,T as X,U as Z,V as H,W as k,S as ee,X as re}from"./CkzjbUDB.js";import{B as ne}from"./CFYBLbZM.js";import{s as ae,g as se}from"./DxGD2b0U.js";let g=!1,E=Symbol();function _e(e,n,s){const r=s[n]??={store:null,source:D(void 0),unsubscribe:m};if(r.store!==e&&!(E in s))if(r.unsubscribe(),r.store=e??null,e==null)r.source.v=void 0,r.unsubscribe=m;else{var i=!0;r.unsubscribe=ae(e,u=>{i?r.source.v=u:A(r.source,u)}),i=!1}return e&&E in s?se(e):S(r.source)}function de(){const e={};function n(){B(()=>{for(var s in e)e[s].unsubscribe();L(e,E,{enumerable:!1,value:!0})})}return[e,n]}function te(e){var n=g;try{return g=!1,[e(),g]}finally{g=n}}function le(e,n,s=!1){var r;R&&(r=F,U());var i=new ne(e),u=s?p:0;function v(t,f){if(R){var d=w(r);if(t!==parseInt(d.substring(1))){var _=x();Y(_),i.anchor=_,T(!1),i.ensure(t,f),T(!0);return}}i.ensure(t,f)}M(()=>{var t=!1;n((f,d=0)=>{t=!0,v(d,f)}),t||v(-1,null)},u)}function oe(e,n,s,r){var i=!V||(s&W)!==0,u=(s&K)!==0,v=(s&k)!==0,t=r,f=!0,d=()=>(f&&(f=!1,t=v?Q(r):r),t);let _;if(u){var O=ee in e||re in e;_=$(e,n)?.set??(O&&n in e?a=>e[n]=a:void 0)}var o,I=!1;u?[o,I]=te(()=>e[n]):o=e[n],o===void 0&&r!==void 0&&(o=d(),_&&(i&&q(),_(o)));var l;if(i?l=()=>{var a=e[n];return a===void 0?d():(f=!0,a)}:l=()=>{var a=e[n];return a!==void 0&&(t=void 0),a===void 0?t:a},i&&(s&z)===0)return l;if(_){var y=e.$$legacy;return(function(a,b){return arguments.length>0?((!i||!b||y||I)&&_(b?l():a),a):l()})}var P=!1,c=((s&X)!==0?Z:H)(()=>(P=!1,l()));u&&S(c);var N=j;return(function(a,b){if(arguments.length>0){const h=b?S(c):i&&u?C(a):a;return A(c,h),P=!0,t!==void 0&&(t=h),a}return G&&P||(N.f&J)!==0?c.v:S(c)})}export{_e as a,le as i,oe as p,de as s};
-1
.svelte-kit/output/client/_app/immutable/chunks/mmStoiki.js
··· 1 - import{a4 as T,a3 as d,a5 as g,a6 as w,a7 as E,x as m,h as l,f as s,a8 as y,i as N,c as _,a9 as x,l as M,aa as A}from"./w0kPbzMq.js";const C=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function L(e){return C?.createHTML(e)??e}function v(e){var t=T("template");return t.innerHTML=L(e.replaceAll("<!>","<!---->")),t.content}function a(e,t){var r=m;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function R(e,t){var r=(t&w)!==0,c=(t&E)!==0,n,i=!e.startsWith("<!>");return()=>{if(l)return a(s,null),s;n===void 0&&(n=v(i?e:"<!>"+e),r||(n=d(n)));var o=c||g?document.importNode(n,!0):n.cloneNode(!0);if(r){var f=d(o),u=o.lastChild;a(f,u)}else a(o,o);return o}}function b(e,t,r="svg"){var c=!e.startsWith("<!>"),n=`<${r}>${c?e:"<!>"+e}</${r}>`,i;return()=>{if(l)return a(s,null),s;if(!i){var o=v(n),f=d(o);for(i=document.createDocumentFragment();d(f);)i.appendChild(d(f))}var u=i.cloneNode(!0);{var p=d(u),h=u.lastChild;a(p,h)}return u}}function D(e,t){return b(e,t,"svg")}function I(e=""){if(!l){var t=_(e+"");return a(t,t),t}var r=s;return r.nodeType!==x?(r.before(r=_()),M(r)):A(r),a(r,r),r}function F(){if(l)return a(s,null),s;var e=document.createDocumentFragment(),t=document.createComment(""),r=_();return e.append(t,r),a(t,r),e}function H(e,t){if(l){var r=m;((r.f&y)===0||r.nodes.end===null)&&(r.nodes.end=s),N();return}e!==null&&e.before(t)}const O="5";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add(O);export{H as a,a as b,F as c,D as d,R as f,I as t};
-1
.svelte-kit/output/client/_app/immutable/chunks/w0kPbzMq.js
··· 1 - var qt=Array.isArray,Ht=Array.prototype.indexOf,le=Array.prototype.includes,Cn=Array.from,Mn=Object.defineProperty,ve=Object.getOwnPropertyDescriptor,Ut=Object.getOwnPropertyDescriptors,Vt=Object.prototype,Bt=Array.prototype,it=Object.getPrototypeOf,Je=Object.isExtensible;const zt=()=>{};function Fn(e){return e()}function Gt(e){for(var t=0;t<e.length;t++)e[t]()}function at(){var e,t,n=new Promise((r,s)=>{e=r,t=s});return{promise:n,resolve:e,reject:t}}const E=2,ie=4,we=8,ft=1<<24,q=16,M=32,J=64,Kt=128,k=512,g=1024,b=2048,F=4096,P=8192,C=16384,re=32768,Qe=1<<25,Ae=65536,Me=1<<17,$t=1<<18,ye=1<<19,ut=1<<20,jn=1<<25,Q=65536,Fe=1<<21,Oe=1<<22,V=1<<23,de=Symbol("$state"),Ln=Symbol("legacy props"),Yn=Symbol(""),Y=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Hn=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),Ne=3,ot=8;function Xt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Un(e,t,n){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Zt(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Wt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Jt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function Qt(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Vn(){throw new Error("https://svelte.dev/e/hydration_failed")}function Bn(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function en(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function tn(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function nn(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function zn(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Gn=1,Kn=2,$n=16,Xn=1,Zn=2,Wn=4,Jn=8,Qn=16,er=1,tr=2,rn="[",sn="[!",nr="[?",ln="]",Ue={},m=Symbol(),an="http://www.w3.org/1999/xhtml";function Ve(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function rr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let ee=!1;function sr(e){ee=e}let S;function ae(e){if(e===null)throw Ve(),Ue;return S=e}function lr(){return ae(K(S))}function ir(e){if(ee){if(K(S)!==null)throw Ve(),Ue;S=e}}function ar(e=1){if(ee){for(var t=e,n=S;t--;)n=K(n);S=n}}function fr(e=!0){for(var t=0,n=S;;){if(n.nodeType===ot){var r=n.data;if(r===ln){if(t===0)return n;t-=1}else(r===rn||r===sn||r[0]==="["&&!isNaN(Number(r.slice(1))))&&(t+=1)}var s=K(n);e&&n.remove(),n=s}}function ur(e){if(!e||e.nodeType!==ot)throw Ve(),Ue;return e.data}function ct(e){return e===this.v}function fn(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function _t(e){return!fn(e,this.v)}let De=!1;function or(){De=!0}let T=null;function Se(e){T=e}function cr(e,t=!1,n){T={p:T,i:!1,c:null,e:null,s:e,x:null,r:d,l:De&&!t?{s:null,u:null,$:[]}:null}}function _r(e){var t=T,n=t.e;if(n!==null){t.e=null;for(var r of n)kt(r)}return t.i=!0,T=t.p,{}}function ge(){return!De||T!==null&&T.l===null}let X=[];function vt(){var e=X;X=[],Gt(e)}function et(e){if(X.length===0&&!he){var t=X;queueMicrotask(()=>{t===X&&vt()})}X.push(e)}function un(){for(;X.length>0;)vt()}function on(e){var t=d;if(t===null)return v.f|=V,e;if((t.f&re)===0&&(t.f&ie)===0)throw e;Re(e,t)}function Re(e,t){for(;t!==null;){if((t.f&Kt)!==0){if((t.f&re)===0)throw e;try{t.b.error(e);return}catch(n){e=n}}t=t.parent}throw e}const cn=-7169;function y(e,t){e.f=e.f&cn|t}function Be(e){(e.f&k)!==0||e.deps===null?y(e,g):y(e,F)}function dt(e){if(e!==null)for(const t of e)(t.f&E)===0||(t.f&Q)===0||(t.f^=Q,dt(t.deps))}function _n(e,t,n){(e.f&b)!==0?t.add(e):(e.f&F)!==0&&n.add(e),dt(e.deps),y(e,g)}const H=new Set;let w=null,D=null,je=null,he=!1,Pe=!1,se=null,be=null;var tt=0;let vn=1;class z{id=vn++;current=new Map;previous=new Map;#a=new Set;#f=new Set;#r=new Map;#t=new Map;#_=null;#e=[];#v=[];#l=new Set;#s=new Set;#n=new Map;is_fork=!1;#u=!1;#i=new Set;#o(){return this.is_fork||this.#t.size>0}#p(){for(const r of this.#i)for(const s of r.#t.keys()){for(var t=!1,n=s;n.parent!==null;){if(this.#n.has(n)){t=!0;break}n=n.parent}if(!t)return!0}return!1}skip_effect(t){this.#n.has(t)||this.#n.set(t,{d:[],m:[]})}unskip_effect(t){var n=this.#n.get(t);if(n){this.#n.delete(t);for(var r of n.d)y(r,b),this.schedule(r);for(r of n.m)y(r,F),this.schedule(r)}}#c(){if(tt++>1e3&&(H.delete(this),hn()),!this.#o()){for(const i of this.#l)this.#s.delete(i),y(i,b),this.schedule(i);for(const i of this.#s)y(i,F),this.schedule(i)}const t=this.#e;this.#e=[],this.apply();var n=se=[],r=[],s=be=[];for(const i of t)try{this.#d(i,n,r)}catch(a){throw wt(i),a}if(w=null,s.length>0){var l=z.ensure();for(const i of s)l.schedule(i)}if(se=null,be=null,this.#o()||this.#p()){this.#h(r),this.#h(n);for(const[i,a]of this.#n)pt(i,a)}else{this.#r.size===0&&H.delete(this),this.#l.clear(),this.#s.clear();for(const i of this.#a)i(this);this.#a.clear(),nt(r),nt(n),this.#_?.resolve()}var u=w;if(this.#e.length>0){const i=u??=this;i.#e.push(...this.#e.filter(a=>!i.#e.includes(a)))}u!==null&&(H.add(u),u.#c()),H.has(this)||this.#w()}#d(t,n,r){t.f^=g;for(var s=t.first;s!==null;){var l=s.f,u=(l&(M|J))!==0,i=u&&(l&g)!==0,a=i||(l&P)!==0||this.#n.has(s);if(!a&&s.fn!==null){u?s.f^=g:(l&ie)!==0?n.push(s):Ee(s)&&((l&q)!==0&&this.#s.add(s),ue(s));var o=s.first;if(o!==null){s=o;continue}}for(;s!==null;){var f=s.next;if(f!==null){s=f;break}s=s.parent}}}#h(t){for(var n=0;n<t.length;n+=1)_n(t[n],this.#l,this.#s)}capture(t,n,r=!1){n!==m&&!this.previous.has(t)&&this.previous.set(t,n),(t.f&V)===0&&(this.current.set(t,[t.v,r]),D?.set(t,t.v))}activate(){w=this}deactivate(){w=null,D=null}flush(){try{Pe=!0,w=this,this.#c()}finally{tt=0,je=null,se=null,be=null,Pe=!1,w=null,D=null,B.clear()}}discard(){for(const t of this.#f)t(this);this.#f.clear(),H.delete(this)}register_created_effect(t){this.#v.push(t)}#w(){for(const f of H){var t=f.id<this.id,n=[];for(const[c,[_,p]]of this.current){if(f.current.has(c)){var r=f.current.get(c)[0];if(t&&_!==r)f.current.set(c,[_,p]);else continue}n.push(c)}var s=[...f.current.keys()].filter(c=>!this.current.has(c));if(s.length===0)t&&f.discard();else if(n.length>0){f.activate();var l=new Set,u=new Map;for(var i of n)ht(i,s,l,u);u=new Map;var a=[...f.current.keys()].filter(c=>this.current.has(c)?this.current.get(c)[0]!==c:!0);for(const c of this.#v)(c.f&(C|P|Me))===0&&ze(c,a,u)&&((c.f&(Oe|q))!==0?(y(c,b),f.schedule(c)):f.#l.add(c));if(f.#e.length>0){f.apply();for(var o of f.#e)f.#d(o,[],[]);f.#e=[]}f.deactivate()}}for(const f of H)f.#i.has(this)&&(f.#i.delete(this),f.#i.size===0&&!f.#o()&&(f.activate(),f.#c()))}increment(t,n){let r=this.#r.get(n)??0;if(this.#r.set(n,r+1),t){let s=this.#t.get(n)??0;this.#t.set(n,s+1)}}decrement(t,n,r){let s=this.#r.get(n)??0;if(s===1?this.#r.delete(n):this.#r.set(n,s-1),t){let l=this.#t.get(n)??0;l===1?this.#t.delete(n):this.#t.set(n,l-1)}this.#u||r||(this.#u=!0,et(()=>{this.#u=!1,this.flush()}))}transfer_effects(t,n){for(const r of t)this.#l.add(r);for(const r of n)this.#s.add(r);t.clear(),n.clear()}oncommit(t){this.#a.add(t)}ondiscard(t){this.#f.add(t)}settled(){return(this.#_??=at()).promise}static ensure(){if(w===null){const t=w=new z;Pe||(H.add(w),he||et(()=>{w===t&&t.flush()}))}return w}apply(){{D=null;return}}schedule(t){if(je=t,t.b?.is_pending&&(t.f&(ie|we|ft))!==0&&(t.f&re)===0){t.b.defer_effect(t);return}for(var n=t;n.parent!==null;){n=n.parent;var r=n.f;if(se!==null&&n===d&&(v===null||(v.f&E)===0))return;if((r&(J|M))!==0){if((r&g)===0)return;n.f^=g}}this.#e.push(n)}}function dn(e){var t=he;he=!0;try{for(var n;;){if(un(),w===null)return n;w.flush()}}finally{he=t}}function hn(){try{Qt()}catch(e){Re(e,je)}}let L=null;function nt(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if((r.f&(C|P))===0&&Ee(r)&&(L=new Set,ue(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&Nt(r),L?.size>0)){B.clear();for(const s of L){if((s.f&(C|P))!==0)continue;const l=[s];let u=s.parent;for(;u!==null;)L.has(u)&&(L.delete(u),l.push(u)),u=u.parent;for(let i=l.length-1;i>=0;i--){const a=l[i];(a.f&(C|P))===0&&ue(a)}}L.clear()}}L=null}}function ht(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(const s of e.reactions){const l=s.f;(l&E)!==0?ht(s,t,n,r):(l&(Oe|q))!==0&&(l&b)===0&&ze(s,t,r)&&(y(s,b),Ge(s))}}function ze(e,t,n){const r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(le.call(t,s))return!0;if((s.f&E)!==0&&ze(s,t,n))return n.set(s,!0),!0}return n.set(e,!1),!1}function Ge(e){w.schedule(e)}function pt(e,t){if(!((e.f&M)!==0&&(e.f&g)!==0)){(e.f&b)!==0?t.d.push(e):(e.f&F)!==0&&t.m.push(e),y(e,g);for(var n=e.first;n!==null;)pt(n,t),n=n.next}}function wt(e){y(e,g);for(var t=e.first;t!==null;)wt(t),t=t.next}function pn(e,t,n,r){const s=ge()?Ke:gn;var l=e.filter(_=>!_.settled);if(n.length===0&&l.length===0){r(t.map(s));return}var u=d,i=wn(),a=l.length===1?l[0].promise:l.length>1?Promise.all(l.map(_=>_.promise)):null;function o(_){i();try{r(_)}catch(p){(u.f&C)===0&&Re(p,u)}xe()}if(n.length===0){a.then(()=>o(t.map(s)));return}var f=yt();function c(){Promise.all(n.map(_=>yn(_))).then(_=>o([...t.map(s),..._])).catch(_=>Re(_,u)).finally(()=>f())}a?a.then(()=>{i(),c(),xe()}):c()}function wn(){var e=d,t=v,n=T,r=w;return function(l=!0){fe(e),G(t),Se(n),l&&(e.f&C)===0&&(r?.activate(),r?.apply())}}function xe(e=!0){fe(null),G(null),Se(null),e&&w?.deactivate()}function yt(){var e=d,t=e.b,n=w,r=t.is_rendered();return t.update_pending_count(1,n),n.increment(r,e),(s=!1)=>{t.update_pending_count(-1,n),n.decrement(r,e,s)}}function Ke(e){var t=E|b,n=v!==null&&(v.f&E)!==0?v:null;return d!==null&&(d.f|=ye),{ctx:T,deps:null,effects:null,equals:ct,f:t,fn:e,reactions:null,rv:0,v:m,wv:0,parent:n??d,ac:null}}function yn(e,t,n){let r=d;r===null&&Xt();var s=void 0,l=Xe(m),u=!v,i=new Map;return kn(()=>{var a=d,o=at();s=o.promise;try{Promise.resolve(e()).then(o.resolve,o.reject).finally(xe)}catch(p){o.reject(p),xe()}var f=w;if(u){if((a.f&re)!==0)var c=yt();if(r.b.is_rendered())i.get(f)?.reject(Y),i.delete(f);else{for(const p of i.values())p.reject(Y);i.clear()}i.set(f,o)}const _=(p,h=void 0)=>{if(c){var N=h===Y;c(N)}if(!(h===Y||(a.f&C)!==0)){if(f.activate(),h)l.f|=V,Ye(l,h);else{(l.f&V)!==0&&(l.f^=V),Ye(l,p);for(const[oe,me]of i){if(i.delete(oe),oe===f)break;me.reject(Y)}}f.deactivate()}};o.promise.then(_,p=>_(null,p||"unknown"))}),xn(()=>{for(const a of i.values())a.reject(Y)}),new Promise(a=>{function o(f){function c(){f===s?a(l):o(s)}f.then(c,c)}o(s)})}function vr(e){const t=Ke(e);return Pt(t),t}function gn(e){const t=Ke(e);return t.equals=_t,t}function En(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)te(t[n])}}function mn(e){for(var t=e.parent;t!==null;){if((t.f&E)===0)return(t.f&C)===0?t:null;t=t.parent}return null}function $e(e){var t,n=d;fe(mn(e));try{e.f&=~Q,En(e),t=jt(e)}finally{fe(n)}return t}function gt(e){var t=e.v,n=$e(e);if(!e.equals(n)&&(e.wv=Mt(),(!w?.is_fork||e.deps===null)&&(e.v=n,w?.capture(e,t,!0),e.deps===null))){y(e,g);return}ne||(D!==null?(xt()||w?.is_fork)&&D.set(e,n):Be(e))}function bn(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac?.abort(Y),t.teardown=zt,t.ac=null,pe(t,0),We(t))}function Et(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&ue(t)}let Le=new Set;const B=new Map;let mt=!1;function Xe(e,t){var n={f:0,v:e,reactions:null,equals:ct,rv:0,wv:0};return n}function U(e,t){const n=Xe(e);return Pt(n),n}function dr(e,t=!1,n=!0){const r=Xe(e);return t||(r.equals=_t),De&&n&&T!==null&&T.l!==null&&(T.l.s??=[]).push(r),r}function $(e,t,n=!1){v!==null&&(!I||(v.f&Me)!==0)&&ge()&&(v.f&(E|q|Oe|Me))!==0&&(O===null||!le.call(O,e))&&nn();let r=n?ce(t):t;return Ye(e,r,be)}function Ye(e,t,n=null){if(!e.equals(t)){var r=e.v;ne?B.set(e,t):B.set(e,r),e.v=t;var s=z.ensure();if(s.capture(e,r),(e.f&E)!==0){const l=e;(e.f&b)!==0&&$e(l),D===null&&Be(l)}e.wv=Mt(),bt(e,b,n),ge()&&d!==null&&(d.f&g)!==0&&(d.f&(M|J))===0&&(x===null?In([e]):x.push(e)),!s.is_fork&&Le.size>0&&!mt&&Tn()}return t}function Tn(){mt=!1;for(const e of Le)(e.f&g)!==0&&y(e,F),Ee(e)&&ue(e);Le.clear()}function Ce(e){$(e,e.v+1)}function bt(e,t,n){var r=e.reactions;if(r!==null)for(var s=ge(),l=r.length,u=0;u<l;u++){var i=r[u],a=i.f;if(!(!s&&i===d)){var o=(a&b)===0;if(o&&y(i,t),(a&E)!==0){var f=i;D?.delete(f),(a&Q)===0&&(a&k&&(i.f|=Q),bt(f,F,n))}else if(o){var c=i;(a&q)!==0&&L!==null&&L.add(c),n!==null?n.push(c):Ge(c)}}}}function ce(e){if(typeof e!="object"||e===null||de in e)return e;const t=it(e);if(t!==Vt&&t!==Bt)return e;var n=new Map,r=qt(e),s=U(0),l=W,u=i=>{if(W===l)return i();var a=v,o=W;G(null),lt(l);var f=i();return G(a),lt(o),f};return r&&n.set("length",U(e.length)),new Proxy(e,{defineProperty(i,a,o){(!("value"in o)||o.configurable===!1||o.enumerable===!1||o.writable===!1)&&en();var f=n.get(a);return f===void 0?u(()=>{var c=U(o.value);return n.set(a,c),c}):$(f,o.value,!0),!0},deleteProperty(i,a){var o=n.get(a);if(o===void 0){if(a in i){const f=u(()=>U(m));n.set(a,f),Ce(s)}}else $(o,m),Ce(s);return!0},get(i,a,o){if(a===de)return e;var f=n.get(a),c=a in i;if(f===void 0&&(!c||ve(i,a)?.writable)&&(f=u(()=>{var p=ce(c?i[a]:m),h=U(p);return h}),n.set(a,f)),f!==void 0){var _=_e(f);return _===m?void 0:_}return Reflect.get(i,a,o)},getOwnPropertyDescriptor(i,a){var o=Reflect.getOwnPropertyDescriptor(i,a);if(o&&"value"in o){var f=n.get(a);f&&(o.value=_e(f))}else if(o===void 0){var c=n.get(a),_=c?.v;if(c!==void 0&&_!==m)return{enumerable:!0,configurable:!0,value:_,writable:!0}}return o},has(i,a){if(a===de)return!0;var o=n.get(a),f=o!==void 0&&o.v!==m||Reflect.has(i,a);if(o!==void 0||d!==null&&(!f||ve(i,a)?.writable)){o===void 0&&(o=u(()=>{var _=f?ce(i[a]):m,p=U(_);return p}),n.set(a,o));var c=_e(o);if(c===m)return!1}return f},set(i,a,o,f){var c=n.get(a),_=a in i;if(r&&a==="length")for(var p=o;p<c.v;p+=1){var h=n.get(p+"");h!==void 0?$(h,m):p in i&&(h=u(()=>U(m)),n.set(p+"",h))}if(c===void 0)(!_||ve(i,a)?.writable)&&(c=u(()=>U(void 0)),$(c,ce(o)),n.set(a,c));else{_=c.v!==m;var N=u(()=>ce(o));$(c,N)}var oe=Reflect.getOwnPropertyDescriptor(i,a);if(oe?.set&&oe.set.call(f,o),!_){if(r&&typeof a=="string"){var me=n.get("length"),Ie=Number(a);Number.isInteger(Ie)&&Ie>=me.v&&$(me,Ie+1)}Ce(s)}return!0},ownKeys(i){_e(s);var a=Reflect.ownKeys(i).filter(c=>{var _=n.get(c);return _===void 0||_.v!==m});for(var[o,f]of n)f.v!==m&&!(o in i)&&a.push(o);return a},setPrototypeOf(){tn()}})}var rt,An,Sn,Tt,At;function hr(){if(rt===void 0){rt=window,An=document,Sn=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;Tt=ve(t,"firstChild").get,At=ve(t,"nextSibling").get,Je(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),Je(n)&&(n.__t=void 0)}}function ke(e=""){return document.createTextNode(e)}function qe(e){return Tt.call(e)}function K(e){return At.call(e)}function pr(e,t){if(!ee)return qe(e);var n=qe(S);if(n===null)n=S.appendChild(ke());else if(t&&n.nodeType!==Ne){var r=ke();return n?.before(r),ae(r),r}return t&&Ze(n),ae(n),n}function wr(e,t=!1){if(!ee){var n=qe(e);return n instanceof Comment&&n.data===""?K(n):n}if(t){if(S?.nodeType!==Ne){var r=ke();return S?.before(r),ae(r),r}Ze(S)}return S}function yr(e,t=1,n=!1){let r=ee?S:e;for(var s;t--;)s=r,r=K(r);if(!ee)return r;if(n){if(r?.nodeType!==Ne){var l=ke();return r===null?s?.after(l):r.before(l),ae(l),l}Ze(r)}return ae(r),r}function gr(e){e.textContent=""}function Er(){return!1}function mr(e,t,n){return document.createElementNS(an,e,void 0)}function Ze(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===Ne;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function St(e){var t=v,n=d;G(null),fe(null);try{return e()}finally{G(t),fe(n)}}function Rt(e){d===null&&(v===null&&Jt(),Wt()),ne&&Zt()}function Rn(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function j(e,t){var n=d;n!==null&&(n.f&P)!==0&&(e|=P);var r={ctx:T,deps:null,nodes:null,f:e|b|k,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};w?.register_created_effect(r);var s=r;if((e&ie)!==0)se!==null?se.push(r):z.ensure().schedule(r);else if(t!==null){try{ue(r)}catch(u){throw te(r),u}s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&(s.f&ye)===0&&(s=s.first,(e&q)!==0&&(e&Ae)!==0&&s!==null&&(s.f|=Ae))}if(s!==null&&(s.parent=n,n!==null&&Rn(s,n),v!==null&&(v.f&E)!==0&&(e&J)===0)){var l=v;(l.effects??=[]).push(s)}return r}function xt(){return v!==null&&!I}function xn(e){const t=j(we,null);return y(t,g),t.teardown=e,t}function br(e){Rt();var t=d.f,n=!v&&(t&M)!==0&&(t&re)===0;if(n){var r=T;(r.e??=[]).push(e)}else return kt(e)}function kt(e){return j(ie|ut,e)}function Tr(e){return Rt(),j(we|ut,e)}function Ar(e){z.ensure();const t=j(J|ye,e);return(n={})=>new Promise(r=>{n.outro?Dn(t,()=>{te(t),r(void 0)}):(te(t),r(void 0))})}function Sr(e){return j(ie,e)}function kn(e){return j(Oe|ye,e)}function Rr(e,t=0){return j(we|t,e)}function xr(e,t=[],n=[],r=[]){pn(r,t,n,s=>{j(we,()=>e(...s.map(_e)))})}function kr(e,t=0){var n=j(q|t,e);return n}function Or(e){return j(M|ye,e)}function Ot(e){var t=e.teardown;if(t!==null){const n=ne,r=v;st(!0),G(null);try{t.call(null)}finally{st(n),G(r)}}}function We(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){const s=n.ac;s!==null&&St(()=>{s.abort(Y)});var r=n.next;(n.f&J)!==0?n.parent=null:te(n,t),n=r}}function On(e){for(var t=e.first;t!==null;){var n=t.next;(t.f&M)===0&&te(t),t=n}}function te(e,t=!0){var n=!1;(t||(e.f&$t)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Nn(e.nodes.start,e.nodes.end),n=!0),y(e,Qe),We(e,t&&!n),pe(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(const l of r)l.stop();Ot(e),e.f^=Qe,e.f|=C;var s=e.parent;s!==null&&s.first!==null&&Nt(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Nn(e,t){for(;e!==null;){var n=e===t?null:K(e);e.remove(),e=n}}function Nt(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Dn(e,t,n=!0){var r=[];Dt(e,r,!0);var s=()=>{n&&te(e),t&&t()},l=r.length;if(l>0){var u=()=>--l||s();for(var i of r)i.out(u)}else s()}function Dt(e,t,n){if((e.f&P)===0){e.f^=P;var r=e.nodes&&e.nodes.t;if(r!==null)for(const i of r)(i.is_global||n)&&t.push(i);for(var s=e.first;s!==null;){var l=s.next,u=(s.f&Ae)!==0||(s.f&M)!==0&&(e.f&q)!==0;Dt(s,t,u?n:!1),s=l}}}function Nr(e){It(e,!0)}function It(e,t){if((e.f&P)!==0){e.f^=P,(e.f&g)===0&&(y(e,b),z.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,s=(n.f&Ae)!==0||(n.f&M)!==0;It(n,s?t:!1),n=r}var l=e.nodes&&e.nodes.t;if(l!==null)for(const u of l)(u.is_global||t)&&u.in()}}function Dr(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var s=n===r?null:K(n);t.append(n),n=s}}let Te=!1,ne=!1;function st(e){ne=e}let v=null,I=!1;function G(e){v=e}let d=null;function fe(e){d=e}let O=null;function Pt(e){v!==null&&(O===null?O=[e]:O.push(e))}let A=null,R=0,x=null;function In(e){x=e}let Ct=1,Z=0,W=Z;function lt(e){W=e}function Mt(){return++Ct}function Ee(e){var t=e.f;if((t&b)!==0)return!0;if(t&E&&(e.f&=~Q),(t&F)!==0){for(var n=e.deps,r=n.length,s=0;s<r;s++){var l=n[s];if(Ee(l)&&gt(l),l.wv>e.wv)return!0}(t&k)!==0&&D===null&&y(e,g)}return!1}function Ft(e,t,n=!0){var r=e.reactions;if(r!==null&&!(O!==null&&le.call(O,e)))for(var s=0;s<r.length;s++){var l=r[s];(l.f&E)!==0?Ft(l,t,!1):t===l&&(n?y(l,b):(l.f&g)!==0&&y(l,F),Ge(l))}}function jt(e){var t=A,n=R,r=x,s=v,l=O,u=T,i=I,a=W,o=e.f;A=null,R=0,x=null,v=(o&(M|J))===0?e:null,O=null,Se(e.ctx),I=!1,W=++Z,e.ac!==null&&(St(()=>{e.ac.abort(Y)}),e.ac=null);try{e.f|=Fe;var f=e.fn,c=f();e.f|=re;var _=e.deps,p=w?.is_fork;if(A!==null){var h;if(p||pe(e,R),_!==null&&R>0)for(_.length=R+A.length,h=0;h<A.length;h++)_[R+h]=A[h];else e.deps=_=A;if(xt()&&(e.f&k)!==0)for(h=R;h<_.length;h++)(_[h].reactions??=[]).push(e)}else!p&&_!==null&&R<_.length&&(pe(e,R),_.length=R);if(ge()&&x!==null&&!I&&_!==null&&(e.f&(E|F|b))===0)for(h=0;h<x.length;h++)Ft(x[h],e);if(s!==null&&s!==e){if(Z++,s.deps!==null)for(let N=0;N<n;N+=1)s.deps[N].rv=Z;if(t!==null)for(const N of t)N.rv=Z;x!==null&&(r===null?r=x:r.push(...x))}return(e.f&V)!==0&&(e.f^=V),c}catch(N){return on(N)}finally{e.f^=Fe,A=t,R=n,x=r,v=s,O=l,Se(u),I=i,W=a}}function Pn(e,t){let n=t.reactions;if(n!==null){var r=Ht.call(n,e);if(r!==-1){var s=n.length-1;s===0?n=t.reactions=null:(n[r]=n[s],n.pop())}}if(n===null&&(t.f&E)!==0&&(A===null||!le.call(A,t))){var l=t;(l.f&k)!==0&&(l.f^=k,l.f&=~Q),Be(l),bn(l),pe(l,0)}}function pe(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)Pn(e,n[r])}function ue(e){var t=e.f;if((t&C)===0){y(e,g);var n=d,r=Te;d=e,Te=!0;try{(t&(q|ft))!==0?On(e):We(e),Ot(e);var s=jt(e);e.teardown=typeof s=="function"?s:null,e.wv=Ct;var l}finally{Te=r,d=n}}}async function Ir(){await Promise.resolve(),dn()}function Pr(){return z.ensure().settled()}function _e(e){var t=e.f,n=(t&E)!==0;if(v!==null&&!I){var r=d!==null&&(d.f&C)!==0;if(!r&&(O===null||!le.call(O,e))){var s=v.deps;if((v.f&Fe)!==0)e.rv<Z&&(e.rv=Z,A===null&&s!==null&&s[R]===e?R++:A===null?A=[e]:A.push(e));else{(v.deps??=[]).push(e);var l=e.reactions;l===null?e.reactions=[v]:le.call(l,v)||l.push(v)}}}if(ne&&B.has(e))return B.get(e);if(n){var u=e;if(ne){var i=u.v;return((u.f&g)===0&&u.reactions!==null||Yt(u))&&(i=$e(u)),B.set(u,i),i}var a=(u.f&k)===0&&!I&&v!==null&&(Te||(v.f&k)!==0),o=(u.f&re)===0;Ee(u)&&(a&&(u.f|=k),gt(u)),a&&!o&&(Et(u),Lt(u))}if(D?.has(e))return D.get(e);if((e.f&V)!==0)throw e.v;return e.v}function Lt(e){if(e.f|=k,e.deps!==null)for(const t of e.deps)(t.reactions??=[]).push(e),(t.f&E)!==0&&(t.f&k)===0&&(Et(t),Lt(t))}function Yt(e){if(e.v===m)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(B.has(t)||(t.f&E)!==0&&Yt(t))return!0;return!1}function Cr(e){var t=I;try{return I=!0,e()}finally{I=t}}function Mr(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(de in e)He(e);else if(!Array.isArray(e))for(let t in e){const n=e[t];typeof n=="object"&&n&&de in n&&He(n)}}}function He(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let r in e)try{He(e[r],t)}catch{}const n=it(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){const r=Ut(n);for(let s in r){const l=r[s].get;if(l)try{l.call(e)}catch{}}}}}export{$t as $,_e as A,ce as B,$ as C,Qe as D,Ae as E,ne as F,C as G,Jn as H,Zn as I,Xn as J,Ke as K,gn as L,Qn as M,Ln as N,Tr as O,Wn as P,Gt as Q,Fn as R,de as S,Mr as T,cr as U,wr as V,xr as W,_r as X,pr as Y,ir as Z,yr as _,w as a,Pr as a$,ye as a0,ot as a1,K as a2,qe as a3,mr as a4,Sn as a5,er as a6,tr as a7,re as a8,Ne as a9,Vn as aA,gr as aB,Ar as aC,Cn as aD,ln as aE,Ve as aF,dn as aG,dr as aH,Ir as aI,U as aJ,vr as aK,jn as aL,Un as aM,qt as aN,Gn as aO,$n as aP,Kn as aQ,P as aR,M as aS,Yn as aT,an as aU,Hn as aV,it as aW,Ut as aX,An as aY,zt as aZ,fn as a_,Ze as aa,xt as ab,Xe as ac,Ce as ad,et as ae,Kt as af,sn as ag,nr as ah,_n as ai,fe as aj,G as ak,Se as al,z as am,on as an,v as ao,Ye as ap,ar as aq,Re as ar,zn as as,rr as at,Mn as au,xn as av,St as aw,hr as ax,rn as ay,Ue as az,Or as b,ke as c,te as d,or as e,S as f,kr as g,ee as h,lr as i,ur as j,fr as k,ae as l,Dr as m,sr as n,T as o,Dn as p,De as q,Nr as r,Er as s,Cr as t,br as u,Sr as v,Rr as w,d as x,ve as y,Bn as z};
-2
.svelte-kit/output/client/_app/immutable/entry/app.BiVWJwsp.js
··· 1 - const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.D6CLfhqK.js","../chunks/mmStoiki.js","../chunks/w0kPbzMq.js","../chunks/8u-mThFx.js","../chunks/C_B-Ij-b.js","../chunks/DsupRLPE.js","../assets/0.CyGpFWYY.css","../nodes/1.xyjmz21p.js","../chunks/BcVkVDn_.js","../chunks/D9RahMPT.js","../chunks/B43_79mg.js","../nodes/2.D4xyri_M.js","../chunks/C6hdjiAW.js","../assets/2.BKmFmlcI.css"])))=>i.map(i=>d[i]); 2 - import{h as I,i as G,g as H,E as W,j as J,k as K,l as X,n as D,ay as Z,f as z,C as O,N as Q,A as f,aG as $,au as ee,aH as te,U as re,O as se,u as ae,aI as ne,V as w,_ as oe,X as ce,aJ as p,Y as ie,Z as le,W as ue,aK as x}from"../chunks/w0kPbzMq.js";import{h as de,m as fe,u as me,s as he}from"../chunks/BcVkVDn_.js";import{a as P,c as A,f as V,t as _e}from"../chunks/mmStoiki.js";import{o as ve}from"../chunks/B43_79mg.js";import{B as ge,i as S}from"../chunks/C_B-Ij-b.js";import{p as T,b as j}from"../chunks/C6hdjiAW.js";function C(o,e,s){var l;I&&(l=z,G());var c=new ge(o);H(()=>{var t=e()??null;if(I){var r=J(l),a=r===Z,E=t!==null;if(a!==E){var m=K();X(m),c.anchor=m,D(!1),c.ensure(t,t&&(n=>s(n,t))),D(!0);return}}c.ensure(t,t&&(n=>s(n,t)))},W)}function ye(o){return class extends Ee{constructor(e){super({component:o,...e})}}}class Ee{#t;#e;constructor(e){var s=new Map,l=(t,r)=>{var a=te(r,!1,!1);return s.set(t,a),a};const c=new Proxy({...e.props||{},$$events:{}},{get(t,r){return f(s.get(r)??l(r,Reflect.get(t,r)))},has(t,r){return r===Q?!0:(f(s.get(r)??l(r,Reflect.get(t,r))),Reflect.has(t,r))},set(t,r,a){return O(s.get(r)??l(r,a),a),Reflect.set(t,r,a)}});this.#e=(e.hydrate?de:fe)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),(!e?.props?.$$host||e.sync===!1)&&$(),this.#t=c.$$events;for(const t of Object.keys(this.#e))t==="$set"||t==="$destroy"||t==="$on"||ee(this,t,{get(){return this.#e[t]},set(r){this.#e[t]=r},enumerable:!0});this.#e.$set=t=>{Object.assign(c,t)},this.#e.$destroy=()=>{me(this.#e)}}$set(e){this.#e.$set(e)}$on(e,s){this.#t[e]=this.#t[e]||[];const l=(...c)=>s.call(this,...c);return this.#t[e].push(l),()=>{this.#t[e]=this.#t[e].filter(c=>c!==l)}}$destroy(){this.#e.$destroy()}}const be="modulepreload",Pe=function(o,e){return new URL(o,e).href},M={},L=function(e,s,l){let c=Promise.resolve();if(s&&s.length>0){let m=function(n){return Promise.all(n.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),E=a?.nonce||a?.getAttribute("nonce");c=m(s.map(n=>{if(n=Pe(n,l),n in M)return;M[n]=!0;const d=n.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(l)for(let _=r.length-1;_>=0;_--){const i=r[_];if(i.href===n&&(!d||i.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":be,d||(u.as="script"),u.crossOrigin="",u.href=n,E&&u.setAttribute("nonce",E),document.head.appendChild(u),d)return new Promise((_,i)=>{u.addEventListener("load",_),u.addEventListener("error",()=>i(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return c.then(r=>{for(const a of r||[])a.status==="rejected"&&t(a.reason);return e().catch(t)})},Le={};var Re=V('<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px"><!></div>'),ke=V("<!> <!>",1);function we(o,e){re(e,!0);let s=T(e,"components",23,()=>[]),l=T(e,"data_0",3,null),c=T(e,"data_1",3,null);se(()=>e.stores.page.set(e.page)),ae(()=>{e.stores,e.page,e.constructors,s(),e.form,l(),c(),e.stores.page.notify()});let t=p(!1),r=p(!1),a=p(null);ve(()=>{const i=e.stores.page.subscribe(()=>{f(t)&&(O(r,!0),ne().then(()=>{O(a,document.title||"untitled page",!0)}))});return O(t,!0),i});const E=x(()=>e.constructors[1]);var m=ke(),n=w(m);{var d=i=>{const v=x(()=>e.constructors[0]);var g=A(),R=w(g);C(R,()=>f(v),(y,b)=>{j(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params},children:(k,pe)=>{var N=A(),U=w(N);C(U,()=>f(E),(Y,q)=>{j(q(Y,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),F=>s()[1]=F,()=>s()?.[1])}),P(k,N)},$$slots:{default:!0}}),k=>s()[0]=k,()=>s()?.[0])}),P(i,g)},h=i=>{const v=x(()=>e.constructors[0]);var g=A(),R=w(g);C(R,()=>f(v),(y,b)=>{j(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params}}),k=>s()[0]=k,()=>s()?.[0])}),P(i,g)};S(n,i=>{e.constructors[1]?i(d):i(h,-1)})}var u=oe(n,2);{var _=i=>{var v=Re(),g=ie(v);{var R=y=>{var b=_e();ue(()=>he(b,f(a))),P(y,b)};S(g,y=>{f(r)&&y(R)})}le(v),P(i,v)};S(u,i=>{f(t)&&i(_)})}P(o,m),ce()}const Ne=ye(we),Ie=[()=>L(()=>import("../nodes/0.D6CLfhqK.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url),()=>L(()=>import("../nodes/1.xyjmz21p.js"),__vite__mapDeps([7,1,2,5,8,9,10]),import.meta.url),()=>L(()=>import("../nodes/2.D4xyri_M.js"),__vite__mapDeps([11,1,2,10,8,4,3,12,5,13]),import.meta.url)],De=[],Me={"/":[2]},B={handleError:(({error:o})=>{console.error(o)}),reroute:(()=>{}),transport:{}},Oe=Object.fromEntries(Object.entries(B.transport).map(([o,e])=>[o,e.decode])),Ve=Object.fromEntries(Object.entries(B.transport).map(([o,e])=>[o,e.encode])),Be=!1,Ue=(o,e)=>Oe[o](e);export{Ue as decode,Oe as decoders,Me as dictionary,Ve as encoders,Be as hash,B as hooks,Le as matchers,Ie as nodes,Ne as root,De as server_loads};
+2
.svelte-kit/output/client/_app/immutable/entry/app.CwuxgLSd.js
··· 1 + const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.Cq8Xsn4J.js","../chunks/DGbOEUpF.js","../chunks/CkzjbUDB.js","../chunks/DmyE0d-6.js","../chunks/CFYBLbZM.js","../chunks/B46dcLgj.js","../assets/0.DIlgUleF.css","../nodes/1.BfJAtU5y.js","../chunks/BsDbD4Ku.js","../chunks/C0nNmPgn.js","../chunks/DxGD2b0U.js","../nodes/2.DCJPxWEg.js","../chunks/XE2G8ySY.js","../chunks/D_t83wNY.js","../assets/FrogHeader.8kzFzgPu.css","../chunks/Dr80VTgO.js","../assets/2.CHt1yucP.css","../nodes/3.CW9t1woG.js","../assets/3.CjGf6tQE.css"])))=>i.map(i=>d[i]); 2 + import{j as I,F as U,l as z,E as H,G as W,I as X,t as Z,q as D,aF as J,k as K,B as O,X as Q,A as f,aN as $,x as ee,z as te,a1 as re,Y as se,Z as ae,aO as ne,a2 as k,a7 as oe,a4 as ce,ab as x,a5 as ie,a6 as le,a3 as ue,ac as A}from"../chunks/CkzjbUDB.js";import{h as de,m as fe,u as me,s as he}from"../chunks/BsDbD4Ku.js";import{a as P,c as S,f as F,t as _e}from"../chunks/DGbOEUpF.js";import{o as ve}from"../chunks/DxGD2b0U.js";import{p as T,i as j}from"../chunks/XE2G8ySY.js";import{B as ge}from"../chunks/CFYBLbZM.js";import{b as L}from"../chunks/Dr80VTgO.js";function C(o,e,s){var l;I&&(l=K,U());var c=new ge(o);z(()=>{var t=e()??null;if(I){var r=W(l),a=r===J,E=t!==null;if(a!==E){var m=X();Z(m),c.anchor=m,D(!1),c.ensure(t,t&&(n=>s(n,t))),D(!0);return}}c.ensure(t,t&&(n=>s(n,t)))},H)}function ye(o){return class extends Ee{constructor(e){super({component:o,...e})}}}class Ee{#t;#e;constructor(e){var s=new Map,l=(t,r)=>{var a=te(r,!1,!1);return s.set(t,a),a};const c=new Proxy({...e.props||{},$$events:{}},{get(t,r){return f(s.get(r)??l(r,Reflect.get(t,r)))},has(t,r){return r===Q?!0:(f(s.get(r)??l(r,Reflect.get(t,r))),Reflect.has(t,r))},set(t,r,a){return O(s.get(r)??l(r,a),a),Reflect.set(t,r,a)}});this.#e=(e.hydrate?de:fe)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),(!e?.props?.$$host||e.sync===!1)&&$(),this.#t=c.$$events;for(const t of Object.keys(this.#e))t==="$set"||t==="$destroy"||t==="$on"||ee(this,t,{get(){return this.#e[t]},set(r){this.#e[t]=r},enumerable:!0});this.#e.$set=t=>{Object.assign(c,t)},this.#e.$destroy=()=>{me(this.#e)}}$set(e){this.#e.$set(e)}$on(e,s){this.#t[e]=this.#t[e]||[];const l=(...c)=>s.call(this,...c);return this.#t[e].push(l),()=>{this.#t[e]=this.#t[e].filter(c=>c!==l)}}$destroy(){this.#e.$destroy()}}const be="modulepreload",Pe=function(o,e){return new URL(o,e).href},B={},w=function(e,s,l){let c=Promise.resolve();if(s&&s.length>0){let m=function(n){return Promise.all(n.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),E=a?.nonce||a?.getAttribute("nonce");c=m(s.map(n=>{if(n=Pe(n,l),n in B)return;B[n]=!0;const d=n.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(l)for(let _=r.length-1;_>=0;_--){const i=r[_];if(i.href===n&&(!d||i.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":be,d||(u.as="script"),u.crossOrigin="",u.href=n,E&&u.setAttribute("nonce",E),document.head.appendChild(u),d)return new Promise((_,i)=>{u.addEventListener("load",_),u.addEventListener("error",()=>i(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return c.then(r=>{for(const a of r||[])a.status==="rejected"&&t(a.reason);return e().catch(t)})},Ne={};var Re=F('<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px"><!></div>'),pe=F("<!> <!>",1);function ke(o,e){re(e,!0);let s=T(e,"components",23,()=>[]),l=T(e,"data_0",3,null),c=T(e,"data_1",3,null);se(()=>e.stores.page.set(e.page)),ae(()=>{e.stores,e.page,e.constructors,s(),e.form,l(),c(),e.stores.page.notify()});let t=x(!1),r=x(!1),a=x(null);ve(()=>{const i=e.stores.page.subscribe(()=>{f(t)&&(O(r,!0),ne().then(()=>{O(a,document.title||"untitled page",!0)}))});return O(t,!0),i});const E=A(()=>e.constructors[1]);var m=pe(),n=k(m);{var d=i=>{const v=A(()=>e.constructors[0]);var g=S(),R=k(g);C(R,()=>f(v),(y,b)=>{L(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params},children:(p,Oe)=>{var N=S(),V=k(N);C(V,()=>f(E),(q,Y)=>{L(Y(q,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),G=>s()[1]=G,()=>s()?.[1])}),P(p,N)},$$slots:{default:!0}}),p=>s()[0]=p,()=>s()?.[0])}),P(i,g)},h=i=>{const v=A(()=>e.constructors[0]);var g=S(),R=k(g);C(R,()=>f(v),(y,b)=>{L(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params}}),p=>s()[0]=p,()=>s()?.[0])}),P(i,g)};j(n,i=>{e.constructors[1]?i(d):i(h,-1)})}var u=oe(n,2);{var _=i=>{var v=Re(),g=ie(v);{var R=y=>{var b=_e();ue(()=>he(b,f(a))),P(y,b)};j(g,y=>{f(r)&&y(R)})}le(v),P(i,v)};j(u,i=>{f(t)&&i(_)})}P(o,m),ce()}const Ie=ye(ke),De=[()=>w(()=>import("../nodes/0.Cq8Xsn4J.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url),()=>w(()=>import("../nodes/1.BfJAtU5y.js"),__vite__mapDeps([7,1,2,5,8,9,10]),import.meta.url),()=>w(()=>import("../nodes/2.DCJPxWEg.js"),__vite__mapDeps([11,1,2,10,8,12,4,3,13,14,15,16]),import.meta.url),()=>w(()=>import("../nodes/3.CW9t1woG.js"),__vite__mapDeps([17,1,2,10,8,12,4,3,13,14,9,18]),import.meta.url)],Be=[],Fe={"/":[2],"/profile/[handle]":[3]},M={handleError:(({error:o})=>{console.error(o)}),reroute:(()=>{}),transport:{}},we=Object.fromEntries(Object.entries(M.transport).map(([o,e])=>[o,e.decode])),Me=Object.fromEntries(Object.entries(M.transport).map(([o,e])=>[o,e.encode])),Ve=!1,qe=(o,e)=>we[o](e);export{qe as decode,we as decoders,Fe as dictionary,Me as encoders,Ve as hash,M as hooks,Ne as matchers,De as nodes,Ie as root,Be as server_loads};
+1
.svelte-kit/output/client/_app/immutable/entry/start.BUzUbSG3.js
··· 1 + import{l as o,a as r}from"../chunks/C0nNmPgn.js";export{o as load_css,r as start};
-1
.svelte-kit/output/client/_app/immutable/entry/start.YsP-T6iU.js
··· 1 - import{l as o,a as r}from"../chunks/D9RahMPT.js";export{o as load_css,r as start};
+7
.svelte-kit/output/client/_app/immutable/nodes/0.Cq8Xsn4J.js
··· 1 + import{a as s,f as r}from"../chunks/DGbOEUpF.js";import{a2 as f,aa as d,a7 as p}from"../chunks/CkzjbUDB.js";import{h as g,s as h}from"../chunks/DmyE0d-6.js";import"../chunks/B46dcLgj.js";const v=!0,m=!1,A=Object.freeze(Object.defineProperty({__proto__:null,prerender:v,ssr:m},Symbol.toStringTag,{value:"Module"}));var y=r('<div class="mesh-bg svelte-17k46oa"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" preserveAspectRatio="none" class="mesh-svg svelte-17k46oa"><defs><radialGradient id="g1" cx="50%" cy="40%" r="70%"><stop offset="0%" stop-color="#39FF44"></stop><stop offset="60%" stop-color="#2BBF33"></stop><stop offset="100%" stop-color="#1A8C22"></stop></radialGradient><radialGradient id="g2" cx="90%" cy="5%" r="45%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.9"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.4"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g3" cx="5%" cy="95%" r="40%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.7"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g4" cx="15%" cy="10%" r="50%"><stop offset="0%" stop-color="#5FFF66" stop-opacity="0.6"></stop><stop offset="100%" stop-color="#39FF44" stop-opacity="0"></stop></radialGradient><radialGradient id="g5" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#4AFF54" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#2BBF33" stop-opacity="0"></stop></radialGradient></defs><rect width="1000" height="1000" fill="url(#g1)"></rect><rect width="1000" height="1000" fill="url(#g2)"></rect><rect width="1000" height="1000" fill="url(#g3)"></rect><rect width="1000" height="1000" fill="url(#g4)"></rect><rect width="1000" height="1000" fill="url(#g5)"></rect></svg></div>');function u(t){var o=y();s(t,o)}var F=r('<div class="plant-overlay svelte-11afcec"><img src="/leaves.png" alt="" class="leaves svelte-11afcec"/></div>');function w(t){var o=F();s(t,o)}var _=r(`<link rel="icon" href="/frogicon.png"/> <link rel="preconnect" href="https://fonts.googleapis.com"/> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"/> <link href="https://fonts.googleapis.com/css2?family=Shrikhand&amp;family=Nunito:wght@400;700&amp;display=swap" rel="stylesheet"/> <style>/* Cursor must be in global head style to override everything */ 2 + *, *::before, *::after { 3 + cursor: url('/frogcursor-small.png') 8 4, auto !important; 4 + } 5 + a, button, [role="button"], input[type="submit"], select, summary { 6 + cursor: url('/frogcursor-small.png') 8 4, pointer !important; 7 + }</style>`,1),b=r("<!> <!> <!>",1);function O(t,o){var e=b();g("12qhfyh",c=>{var n=_();d(8),s(c,n)});var a=f(e);u(a);var i=p(a,2);w(i);var l=p(i,2);h(l,()=>o.children),s(t,e)}export{O as component,A as universal};
-7
.svelte-kit/output/client/_app/immutable/nodes/0.D6CLfhqK.js
··· 1 - import{a as o,f as c,d as v}from"../chunks/mmStoiki.js";import{W as g,Y as d,Z as x,aq as y,V as h,_ as n}from"../chunks/w0kPbzMq.js";import{s as u,h as B,a as A}from"../chunks/8u-mThFx.js";import"../chunks/DsupRLPE.js";import{i as F}from"../chunks/C_B-Ij-b.js";const _=!0,w=!1,z=Object.freeze(Object.defineProperty({__proto__:null,prerender:_,ssr:w},Symbol.toStringTag,{value:"Module"}));var b=c('<div class="mesh-bg svelte-17k46oa"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" preserveAspectRatio="none" class="mesh-svg svelte-17k46oa"><defs><radialGradient id="g1" cx="50%" cy="40%" r="70%"><stop offset="0%" stop-color="#39FF44"></stop><stop offset="60%" stop-color="#2BBF33"></stop><stop offset="100%" stop-color="#1A8C22"></stop></radialGradient><radialGradient id="g2" cx="90%" cy="5%" r="45%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.9"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.4"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g3" cx="5%" cy="95%" r="40%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.7"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g4" cx="15%" cy="10%" r="50%"><stop offset="0%" stop-color="#5FFF66" stop-opacity="0.6"></stop><stop offset="100%" stop-color="#39FF44" stop-opacity="0"></stop></radialGradient><radialGradient id="g5" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#4AFF54" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#2BBF33" stop-opacity="0"></stop></radialGradient></defs><rect width="1000" height="1000" fill="url(#g1)"></rect><rect width="1000" height="1000" fill="url(#g2)"></rect><rect width="1000" height="1000" fill="url(#g3)"></rect><rect width="1000" height="1000" fill="url(#g4)"></rect><rect width="1000" height="1000" fill="url(#g5)"></rect></svg></div>');function k(l){var e=b();o(l,e)}var G=v('<path d="M 50 900 Q 55 780 42 660 Q 35 540 48 420 Q 55 300 40 180 Q 30 80 50 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="42" cy="140" rx="40" ry="14" fill="#0A182B" transform="rotate(-35 42 140)"></ellipse><ellipse cx="48" cy="290" rx="44" ry="15" fill="#0A182B" transform="rotate(25 48 290)"></ellipse><ellipse cx="38" cy="440" rx="38" ry="13" fill="#0A182B" transform="rotate(-30 38 440)"></ellipse><ellipse cx="52" cy="570" rx="42" ry="14" fill="#0A182B" transform="rotate(20 52 570)"></ellipse><ellipse cx="44" cy="710" rx="40" ry="14" fill="#0A182B" transform="rotate(-22 44 710)"></ellipse><ellipse cx="48" cy="830" rx="36" ry="12" fill="#0A182B" transform="rotate(18 48 830)"></ellipse><ellipse cx="55" cy="210" rx="28" ry="10" fill="#0A182B" transform="rotate(40 55 210)"></ellipse><ellipse cx="50" cy="370" rx="24" ry="9" fill="#0A182B" transform="rotate(35 50 370)"></ellipse><ellipse cx="45" cy="510" rx="30" ry="11" fill="#0A182B" transform="rotate(-28 45 510)"></ellipse><ellipse cx="52" cy="650" rx="26" ry="9" fill="#0A182B" transform="rotate(30 52 650)"></ellipse><ellipse cx="40" cy="780" rx="22" ry="8" fill="#0A182B" transform="rotate(-25 40 780)"></ellipse>',1),Q=v('<path d="M 110 900 Q 105 780 118 660 Q 125 540 112 420 Q 105 300 120 180 Q 130 80 110 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="118" cy="170" rx="40" ry="14" fill="#0A182B" transform="rotate(35 118 170)"></ellipse><ellipse cx="112" cy="320" rx="44" ry="15" fill="#0A182B" transform="rotate(-25 112 320)"></ellipse><ellipse cx="122" cy="470" rx="38" ry="13" fill="#0A182B" transform="rotate(30 122 470)"></ellipse><ellipse cx="108" cy="610" rx="42" ry="14" fill="#0A182B" transform="rotate(-20 108 610)"></ellipse><ellipse cx="116" cy="750" rx="40" ry="14" fill="#0A182B" transform="rotate(22 116 750)"></ellipse><ellipse cx="112" cy="860" rx="36" ry="12" fill="#0A182B" transform="rotate(-18 112 860)"></ellipse><ellipse cx="105" cy="240" rx="28" ry="10" fill="#0A182B" transform="rotate(-40 105 240)"></ellipse><ellipse cx="110" cy="400" rx="24" ry="9" fill="#0A182B" transform="rotate(-35 110 400)"></ellipse><ellipse cx="115" cy="540" rx="30" ry="11" fill="#0A182B" transform="rotate(28 115 540)"></ellipse><ellipse cx="108" cy="680" rx="26" ry="9" fill="#0A182B" transform="rotate(-30 108 680)"></ellipse>',1),M=c('<div><svg viewBox="0 0 160 900" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" class="svelte-11afcec"><!></svg></div>');function m(l,e){var t=M(),s=d(t),a=d(s);{var p=r=>{var i=G();y(11),o(r,i)},f=r=>{var i=Q();y(10),o(r,i)};F(a,r=>{e.side==="left"?r(p):r(f,-1)})}x(s),x(t),g(()=>u(t,1,`plant-overlay ${e.side??""}`,"svelte-11afcec")),o(l,t)}var O=c(`<link rel="icon" href="/frogcursor.png"/> <style>/* Cursor must be in global head style to override everything */ 2 - *, *::before, *::after { 3 - cursor: url('/frogcursor-small.png') 8 4, auto !important; 4 - } 5 - a, button, [role="button"], input[type="submit"], select, summary { 6 - cursor: url('/frogcursor-small.png') 8 4, pointer !important; 7 - }</style>`,1),j=c("<!> <!> <!> <!>",1);function T(l,e){var t=j();B("12qhfyh",r=>{var i=O();y(2),o(r,i)});var s=h(t);k(s);var a=n(s,2);m(a,{side:"left"});var p=n(a,2);m(p,{side:"right"});var f=n(p,2);A(f,()=>e.children),o(l,t)}export{T as component,z as universal};
+1
.svelte-kit/output/client/_app/immutable/nodes/1.BfJAtU5y.js
··· 1 + import{a as b,f as k}from"../chunks/DGbOEUpF.js";import"../chunks/B46dcLgj.js";import{c as x,Y as $,Z as i,u as y,_ as l,$ as A,A as v,a0 as E,U,a1 as Y,a2 as Z,a3 as j,a4 as q,a5 as u,a6 as m,a7 as w}from"../chunks/CkzjbUDB.js";import{s as _}from"../chunks/BsDbD4Ku.js";import{s as z,p as g}from"../chunks/C0nNmPgn.js";function B(r=!1){const e=x,t=e.l.u;if(!t)return;let a=()=>E(e.s);if(r){let o=0,s={};const f=U(()=>{let p=!1;const c=e.s;for(const n in c)c[n]!==s[n]&&(s[n]=c[n],p=!0);return p&&o++,o});a=()=>v(f)}t.b.length&&$(()=>{h(e,a),l(t.b)}),i(()=>{const o=y(()=>t.m.map(A));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{h(e,a),l(t.a)})}function h(r,e){if(r.l.s)for(const t of r.l.s)v(t);e()}const C={get error(){return g.error},get status(){return g.status}};z.updated.check;const d=C;var D=k("<h1> </h1> <p> </p>",1);function K(r,e){Y(e,!1),B();var t=D(),a=Z(t),o=u(a,!0);m(a);var s=w(a,2),f=u(s,!0);m(s),j(()=>{_(o,d.status),_(f,d.error?.message)}),b(r,t),q()}export{K as component};
-1
.svelte-kit/output/client/_app/immutable/nodes/1.xyjmz21p.js
··· 1 - import{a as b,f as k}from"../chunks/mmStoiki.js";import"../chunks/DsupRLPE.js";import{o as x,O as $,u as i,t as y,Q as l,R as A,A as v,T as E,K,U as O,V as Q,W as R,X as T,Y as u,Z as m,_ as U}from"../chunks/w0kPbzMq.js";import{s as _}from"../chunks/BcVkVDn_.js";import{s as V,p as g}from"../chunks/D9RahMPT.js";function W(a=!1){const e=x,t=e.l.u;if(!t)return;let r=()=>E(e.s);if(a){let o=0,s={};const f=K(()=>{let c=!1;const p=e.s;for(const n in p)p[n]!==s[n]&&(s[n]=p[n],c=!0);return c&&o++,o});r=()=>v(f)}t.b.length&&$(()=>{h(e,r),l(t.b)}),i(()=>{const o=y(()=>t.m.map(A));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{h(e,r),l(t.a)})}function h(a,e){if(a.l.s)for(const t of a.l.s)v(t);e()}const X={get error(){return g.error},get status(){return g.status}};V.updated.check;const d=X;var Y=k("<h1> </h1> <p> </p>",1);function B(a,e){O(e,!1),W();var t=Y(),r=Q(t),o=u(r,!0);m(r);var s=U(r,2),f=u(s,!0);m(s),R(()=>{_(o,d.status),_(f,d.error?.message)}),b(a,t),T()}export{B as component};
-40
.svelte-kit/output/client/_app/immutable/nodes/2.D4xyri_M.js
··· 1 - import{a as we,f as Fe}from"../chunks/mmStoiki.js";import{o as zn,a as $o}from"../chunks/B43_79mg.js";import{c as Xs,g as Go,h as ct,l as zs,a3 as Ko,i as Vo,A as H,j as Ho,ag as Yo,k as Lr,n as Qs,f as ns,a1 as Wo,aE as qo,ap as Rr,a as jo,aL as ht,b as Li,aM as Xo,s as zo,L as Qo,aN as Zo,aD as Xi,aO as Jo,aP as el,aH as tl,ac as br,aQ as sl,G as il,r as Qn,p as Zn,aR as Zs,aS as rl,aB as nl,m as al,d as ol,a2 as ll,aT as cl,aU as hl,aV as ul,aW as dl,aX as fl,U as Vs,Y as he,aq as Jn,Z as oe,_ as ye,W as Ze,X as Hs,u as gl,C as se,aJ as xe,B as ea,V as ml,aK as ta,v as pl,aY as yl}from"../chunks/w0kPbzMq.js";import{s as qe,d as sa,e as _r,a as Ps}from"../chunks/BcVkVDn_.js";import{i as It}from"../chunks/C_B-Ij-b.js";import{t as El,a as vl,s as Dr,h as Tl}from"../chunks/8u-mThFx.js";import{p as as,b as Ri}from"../chunks/C6hdjiAW.js";import"../chunks/DsupRLPE.js";function Sl(a,e,t){for(var s=[],i=e.length,r,n=e.length,o=0;o<i;o++){let u=e[o];Zn(u,()=>{if(r){if(r.pending.delete(u),r.done.add(u),r.pending.size===0){var d=a.outrogroups;bi(a,Xi(r.done)),d.delete(r),d.size===0&&(a.outrogroups=null)}}else n-=1},!1)}if(n===0){var c=s.length===0&&t!==null;if(c){var l=t,h=l.parentNode;nl(h),h.append(l),a.items.clear()}bi(a,e,!c)}else r={pending:new Set(e),done:new Set},(a.outrogroups??=new Set).add(r)}function bi(a,e,t=!0){var s;if(a.pending.size>0){s=new Set;for(const n of a.pending.values())for(const o of n)s.add(a.items.get(o).e)}for(var i=0;i<e.length;i++){var r=e[i];if(s?.has(r)){r.f|=ht;const n=document.createDocumentFragment();al(r,n)}else ol(e[i],t)}}var Cr;function xl(a,e,t,s,i,r=null){var n=a,o=new Map;{var c=a;n=ct?zs(Ko(c)):c.appendChild(Xs())}ct&&Vo();var l=null,h=Qo(()=>{var v=t();return Zo(v)?v:v==null?[]:Xi(v)}),u,d=new Map,g=!0;function f(v){(E.effect.f&il)===0&&(E.pending.delete(v),E.fallback=l,Al(E,u,n,e,s),l!==null&&(u.length===0?(l.f&ht)===0?Qn(l):(l.f^=ht,Yt(l,null,n)):Zn(l,()=>{l=null})))}function p(v){E.pending.delete(v)}var y=Go(()=>{u=H(h);var v=u.length;let T=!1;if(ct){var x=Ho(n)===Yo;x!==(v===0)&&(n=Lr(),zs(n),Qs(!1),T=!0)}for(var S=new Set,R=jo,A=zo(),I=0;I<v;I+=1){ct&&ns.nodeType===Wo&&ns.data===qo&&(n=ns,T=!0,Qs(!1));var b=u[I],L=s(b,I),C=g?null:o.get(L);C?(C.v&&Rr(C.v,b),C.i&&Rr(C.i,I),A&&R.unskip_effect(C.e)):(C=Il(o,g?n:Cr??=Xs(),b,L,I,i,e,t),g||(C.e.f|=ht),o.set(L,C)),S.add(L)}if(v===0&&r&&!l&&(g?l=Li(()=>r(n)):(l=Li(()=>r(Cr??=Xs())),l.f|=ht)),v>S.size&&Xo(),ct&&v>0&&zs(Lr()),!g)if(d.set(R,S),A){for(const[w,U]of o)S.has(w)||R.skip_effect(U.e);R.oncommit(f),R.ondiscard(p)}else f(R);T&&Qs(!0),H(h)}),E={effect:y,items:o,pending:d,outrogroups:null,fallback:l};g=!1,ct&&(n=ns)}function Vt(a){for(;a!==null&&(a.f&rl)===0;)a=a.next;return a}function Al(a,e,t,s,i){var r=e.length,n=a.items,o=Vt(a.effect.first),c,l=null,h=[],u=[],d,g,f,p;for(p=0;p<r;p+=1){if(d=e[p],g=i(d,p),f=n.get(g).e,a.outrogroups!==null)for(const I of a.outrogroups)I.pending.delete(f),I.done.delete(f);if((f.f&Zs)!==0&&Qn(f),(f.f&ht)!==0)if(f.f^=ht,f===o)Yt(f,null,t);else{var y=l?l.next:o;f===a.effect.last&&(a.effect.last=f.prev),f.prev&&(f.prev.next=f.next),f.next&&(f.next.prev=f.prev),ut(a,l,f),ut(a,f,y),Yt(f,y,t),l=f,h=[],u=[],o=Vt(l.next);continue}if(f!==o){if(c!==void 0&&c.has(f)){if(h.length<u.length){var E=u[0],v;l=E.prev;var T=h[0],x=h[h.length-1];for(v=0;v<h.length;v+=1)Yt(h[v],E,t);for(v=0;v<u.length;v+=1)c.delete(u[v]);ut(a,T.prev,x.next),ut(a,l,T),ut(a,x,E),o=E,l=x,p-=1,h=[],u=[]}else c.delete(f),Yt(f,o,t),ut(a,f.prev,f.next),ut(a,f,l===null?a.effect.first:l.next),ut(a,l,f),l=f;continue}for(h=[],u=[];o!==null&&o!==f;)(c??=new Set).add(o),u.push(o),o=Vt(o.next);if(o===null)continue}(f.f&ht)===0&&h.push(f),l=f,o=Vt(f.next)}if(a.outrogroups!==null){for(const I of a.outrogroups)I.pending.size===0&&(bi(a,Xi(I.done)),a.outrogroups?.delete(I));a.outrogroups.size===0&&(a.outrogroups=null)}if(o!==null||c!==void 0){var S=[];if(c!==void 0)for(f of c)(f.f&Zs)===0&&S.push(f);for(;o!==null;)(o.f&Zs)===0&&o!==a.fallback&&S.push(o),o=Vt(o.next);var R=S.length;if(R>0){var A=r===0?t:null;Sl(a,S,A)}}}function Il(a,e,t,s,i,r,n,o){var c=(n&Jo)!==0?(n&el)===0?tl(t,!1,!1):br(t):null,l=(n&sl)!==0?br(i):null;return{v:c,i:l,e:Li(()=>(r(e,c??t,l??i,o),()=>{a.delete(s)}))}}function Yt(a,e,t){if(a.nodes)for(var s=a.nodes.start,i=a.nodes.end,r=e&&(e.f&ht)===0?e.nodes.start:t;s!==null;){var n=ll(s);if(r.before(s),s===i)return;s=n}}function ut(a,e,t){e===null?a.effect.first=t:e.next=t,t===null?a.effect.last=e:t.prev=e}function _i(a,e,t,s){var i=a.__style;if(ct||i!==e){var r=El(e);(!ct||r!==a.getAttribute("style"))&&(r==null?a.removeAttribute("style"):a.style.cssText=r),a.__style=e}return s}const Ll=Symbol("is custom element"),Rl=Symbol("is html"),bl=ul?"link":"LINK";function at(a,e,t,s){var i=_l(a);ct&&(i[e]=a.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&a.nodeName===bl)||i[e]!==(i[e]=t)&&(e==="loading"&&(a[cl]=t),t==null?a.removeAttribute(e):typeof t!="string"&&Dl(a).includes(e)?a[e]=t:a.setAttribute(e,t))}function _l(a){return a.__attributes??={[Ll]:a.nodeName.includes("-"),[Rl]:a.namespaceURI===hl}}var Pr=new Map;function Dl(a){var e=a.getAttribute("is")||a.nodeName,t=Pr.get(e);if(t)return t;Pr.set(e,t=[]);for(var s,i=a,r=Element.prototype;r!==i;){s=fl(i);for(var n in s)s[n].set&&t.push(n);i=dl(i)}return t}const Cl="https://iameli.com",Pl="did:plc:rbvrr34edl5ddpuwcubjiost",kl="place.stream.video",wl="https://vod-beta.stream.place/xrpc/place.stream.playback.getVideoPlaylist";async function Ol(a,e=20){const t=new URLSearchParams({repo:Pl,collection:kl,limit:String(e)});a&&t.set("cursor",a);const s=await fetch(`${Cl}/xrpc/com.atproto.repo.listRecords?${t}`);if(!s.ok)throw new Error(`Failed to fetch records: ${s.status}`);return s.json()}function ia(a){return`${wl}?uri=${encodeURIComponent(a)}`}function ra(a){const e=Math.floor(a/1e9),t=Math.floor(e/3600),s=Math.floor(e%3600/60),i=e%60;return t>0?`${t}:${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`:`${s}:${String(i).padStart(2,"0")}`}function na(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const Js=new Map;async function aa(a){if(Js.has(a))return Js.get(a);try{const e=await fetch(`https://plc.directory/${a}`);if(!e.ok)return a;const s=(await e.json()).alsoKnownAs?.[0],i=s?s.replace("at://","@"):a;return Js.set(a,i),i}catch{return a}}const ei=new Map;async function Fl(a){if(ei.has(a))return ei.get(a);try{const e=await fetch(`https://plc.directory/${a}`);if(!e.ok)return null;const i=(await e.json()).service?.find(r=>r.id==="#atproto_pds"||r.type==="AtprotoPersonalDataServer")?.serviceEndpoint??null;return i&&ei.set(a,i),i}catch{return null}}function Ml(a){const e=a.match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);return e?{repo:e[1],collection:e[2],rkey:e[3]}:null}const os=new Map;async function Nl(a){const e=a.value.livestream?.uri;if(!e)return null;if(os.has(e))return os.get(e);try{const t=Ml(e);if(!t)return null;const s=await Fl(t.repo);if(!s)return null;const i=new URLSearchParams({repo:t.repo,collection:t.collection,rkey:t.rkey}),r=await fetch(`${s}/xrpc/com.atproto.repo.getRecord?${i}`);if(!r.ok)return null;const o=(await r.json()).value?.thumb?.ref?.$link;if(!o)return null;const c=`${s}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(t.repo)}&cid=${encodeURIComponent(o)}`;return os.set(e,c),c}catch{return os.set(e,null),null}}const G=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Bl=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Ul},Ul=Number.MAX_SAFE_INTEGER||9007199254740991;let Y=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),D=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a})({}),m=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a})({});var J={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class bt{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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 $l{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new bt(e),this.fast_=new bt(t),this.defaultTTFB_=i,this.ttfb_=new bt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new bt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new bt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new bt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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 Gl(a,e,t){return(e=Vl(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ne(){return ne=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ne.apply(null,arguments)}function kr(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function ie(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kr(Object(t),!0).forEach(function(s){Gl(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):kr(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Kl(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Vl(a){var e=Kl(a,"string");return typeof e=="symbol"?e:e+""}class Ve{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=gt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const gt=function(){},Hl={trace:gt,debug:gt,log:gt,warn:gt,info:gt,error:gt};function Di(){return ne({},Hl)}function Yl(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):gt}function wr(a,e,t){return e[a]?e[a].bind(e):Yl(a,t)}const Ci=Di();function Wl(a,e,t){const s=Di();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=wr(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Di()}i.forEach(r=>{Ci[r]=wr(r,a)})}else ne(Ci,s);return s}const re=Ci;function Et(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ql(a){return typeof self<"u"&&a===self.ManagedMediaSource}function oa(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function $e(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function Le(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function la(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function jl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ti={exports:{}},Or;function Xl(){return Or||(Or=1,(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var y=g.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()})(ti)),ti.exports}var zi=Xl();class Qi{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ca{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ql(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[le.AUDIO]:null,[le.VIDEO]:null,[le.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Qi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=zi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}}function me(a){return a.sn!=="initSegment"}class si extends ca{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(G(e)&&G(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=G(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return me(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 s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class zl extends ca{constructor(e,t,s,i,r){super(s),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=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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 ha(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||ha(t,e)}}function Ql(a,e){const t=ha(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Fr=Math.pow(2,32)-1,Zl=[].push,ua={video:1,audio:2,id3:3,text:4};function pe(a){return String.fromCharCode.apply(null,a)}function da(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function q(a,e){const t=fa(a,e);return t<0?4294967296+t:t}function Mr(a,e){let t=q(a,e);return t*=Math.pow(2,32),t+=q(a,e+4),t}function fa(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Jl(a){const e=a.byteLength;for(let t=0;t<e;){const s=q(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Q(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=q(a,i),n=pe(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=Q(a.subarray(i+8,o),e.slice(1));c.length&&Zl.apply(t,c)}i=o}return t}function ec(a){const e=[],t=a[0];let s=8;const i=q(a,s);s+=4;let r=0,n=0;t===0?(r=q(a,s),n=q(a,s+4),s+=8):(r=Mr(a,s),n=Mr(a,s+8),s+=16),s+=2;let o=a.length+n;const c=da(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=q(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return re.warn("SIDX has hierarchical references (not supported)"),null;const f=q(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function ga(a){const e=[],t=Q(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=Q(r,["tkhd"])[0];if(n){let o=n[0];const c=q(n,o===0?12:20),l=Q(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=q(l,o===0?12:20),u=Q(r,["mdia","hdlr"])[0];if(u){const d=pe(u.subarray(8,12)),g={soun:le.AUDIO,vide:le.VIDEO}[d],f=Q(r,["mdia","minf","stbl","stsd"])[0],p=tc(f);g?(e[c]={timescale:h,type:g,stsd:p},e[g]=ie({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return Q(a,["moov","mvex","trex"]).forEach(i=>{const r=q(i,4),n=e[r];n&&(n.default={duration:q(i,12),flags:q(i,20)})}),e}function tc(a){const e=a.subarray(8),t=e.subarray(86),s=pe(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=Q(e,[s])[0].subarray(s==="enca"?28:78);Q(l,["sinf"]).forEach(u=>{const d=Q(u,["schm"])[0];if(d){const g=pe(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=Q(u,["frma"])[0];f&&(i=pe(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Q(t,["avcC"])[0];c&&c.length>3&&(i+="."+cs(c[1])+cs(c[2])+cs(c[3]),r=ls(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Q(e,[s])[0],l=Q(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=ii(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=ii(l,h);const d=l[h++];if(d===64)i+="."+cs(d);else break;if(h+=12,l[h++]!==5)break;h=ii(l,h);const g=l[h++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[h]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=Q(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=q(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+sc(d).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let E=p.length;E--;){const v=p[E];(v||y)&&(y="."+v.toString(16).toUpperCase()+y)}i+=y}r=ls(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=ls(i,t)||i;break}case"vp09":{const c=Q(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+ze(l)+"."+ze(h)+"."+ze(u)}break}case"av01":{const c=Q(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&d?g?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,v=c[2]&3;i+="."+l+"."+ze(h)+u+"."+ze(f)+"."+p+"."+y+E+v+"."+ze(1)+"."+ze(1)+"."+ze(1)+"."+0,r=ls("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function ls(a,e){const t=Q(e,["dvvC"]),s=t.length?t[0]:Q(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+ze(i)+"."+ze(r)}}function sc(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function ii(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function cs(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function ze(a){return(a<10?"0":"")+a}function ic(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&ma(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(re.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Le(r)} -> ${Le(t)}`),s.set(t,8))})}function rc(a){const e=[];return ma(a,t=>e.push(t.subarray(8,24))),e}function ma(a,e){Q(a,["moov","trak"]).forEach(s=>{const i=Q(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=Q(r,["enca"]);const o=n.length>0;o||(n=Q(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);Q(l,["sinf"]).forEach(u=>{const d=pa(u);d&&e(d,o)})})})}function pa(a){const e=Q(a,["schm"])[0];if(e){const t=pe(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=Q(a,["schi","tenc"])[0];if(s)return s}}}function nc(a,e,t){const s={},i=Q(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=Q(n,["tfhd"])[0],c=q(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=Q(n,["tfdt"])[0];if(u){const T=u[0];let x=q(u,4);T===1&&(x===Fr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(x*=Fr+1,x+=q(u,8))),G(x)&&(!G(h.start)||x<h.start)&&(h.start=x)}const d=l.default,g=q(o,0)|d?.flags;let f=d?.duration||0;g&8&&(g&2?f=q(o,12):f=q(o,8));const p=Q(n,["trun"]);let y=h.start||0,E=0,v=f;for(let T=0;T<p.length;T++){const x=p[T],S=q(x,4),R=h.sampleCount;h.sampleCount+=S;const A=x[3]&1,I=x[3]&4,b=x[2]&1,L=x[2]&2,C=x[2]&4,w=x[2]&8;let U=8,F=S;for(A&&(U+=4),I&&S&&(!(x[U+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=R),U+=4,b?(v=q(x,U),U+=4):v=f,L&&(U+=4),w&&(U+=4),y+=v,E+=v,F--);F--;)b?(v=q(x,U),U+=4):v=f,L&&(U+=4),C&&(x[U+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(F+1),h.keyFrameStart=y),U+=4),w&&(U+=4),y+=v,E+=v;!E&&f&&(E+=f*S)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=Q(a,["sidx"]);for(let c=0;c<o.length;c++){const l=ec(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&G(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function ac(a){const e={valid:null,remainder:null},t=Q(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function Ke(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Nr(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return Q(s,["moof"]).map(c=>{const l=c.byteOffset-8;Q(c,["traf"]).map(u=>{const d=Q(u,["tfdt"]).map(g=>{const f=g[0];let p=q(g,4);return f===1&&(p*=Math.pow(2,32),p+=q(g,8)),p/i})[0];return d!==void 0&&(a=d),Q(u,["tfhd"]).map(g=>{const f=q(g,4),p=q(g,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,v=(p&8)!==0;let T=0;const x=(p&16)!==0;let S=0;const R=(p&32)!==0;let A=8;f===r&&(y&&(A+=8),E&&(A+=4),v&&(T=q(g,A),A+=4),x&&(S=q(g,A),A+=4),R&&(A+=4),e.type==="video"&&(n=Ys(e.codec)),Q(u,["trun"]).map(I=>{const b=I[0],L=q(I,0)&16777215,C=(L&1)!==0;let w=0;const U=(L&4)!==0,F=(L&256)!==0;let N=0;const k=(L&512)!==0;let $=0;const B=(L&1024)!==0,K=(L&2048)!==0;let W=0;const M=q(I,4);let O=8;C&&(w=q(I,O),O+=4),U&&(O+=4);let X=w+l;for(let te=0;te<M;te++){if(F?(N=q(I,O),O+=4):N=T,k?($=q(I,O),O+=4):$=S,B&&(O+=4),K&&(b===0?W=q(I,O):W=fa(I,O),O+=4),e.type===le.VIDEO){let z=0;for(;z<$;){const Z=q(s,X);if(X+=4,oc(n,s[X])){const ve=s.subarray(X,X+Z);Zi(ve,n?2:1,a+W/i,t)}X+=Z,z+=Z+4}}a+=N/i}}))})})}),t}function Ys(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function oc(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Zi(a,e,t,s){const i=ya(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){re.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=da(i,h);if(h+=2,d===49){const g=q(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const p=i[h++],y=31&p,E=64&p,v=E?2+y*3:0,T=new Uint8Array(v);if(E){T[0]=p;for(let x=1;x<v;x++)T[x]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:T})}}}}}else if(n===5&&o>16){const u=[];for(let f=0;f<16;f++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:$e(g),userDataBytes:g})}}}function ya(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function lc(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;pe(a.subarray(l,l+1))!=="\0";)t+=pe(a.subarray(l,l+1)),l+=1;for(t+=pe(a.subarray(l,l+1)),l+=1;pe(a.subarray(l,l+1))!=="\0";)s+=pe(a.subarray(l,l+1)),l+=1;s+=pe(a.subarray(l,l+1)),l+=1,i=q(a,12),r=q(a,16),o=q(a,20),c=q(a,24),l=28}else if(e===1){l+=4,i=q(a,l),l+=4;const u=q(a,l);l+=4;const d=q(a,l);for(l+=4,n=2**32*u+d,Bl(n)||(n=Number.MAX_SAFE_INTEGER,re.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=q(a,l),l+=4,c=q(a,l),l+=4;pe(a.subarray(l,l+1))!=="\0";)t+=pe(a.subarray(l,l+1)),l+=1;for(t+=pe(a.subarray(l,l+1)),l+=1;pe(a.subarray(l,l+1))!=="\0";)s+=pe(a.subarray(l,l+1)),l+=1;s+=pe(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function cc(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function hc(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),cc([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function uc(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=dc(i);e.push(r),s+=r.size}}return e}function dc(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=Le(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let g=0;g<d;g++)c.push(new Uint8Array(n,t+32+g*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const Ea=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Bt={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 Ji(a,e){const t=Bt[e];return!!t&&!!t[a.slice(0,4)]}function zt(a,e,t=!0){return!a.split(",").some(s=>!er(s,e,t))}function er(a,e,t=!0){var s;const i=Et(t);return(s=i?.isTypeSupported(Qt(a,e)))!=null?s:!1}function Qt(a,e){return`${e}/mp4;codecs=${a}`}function Br(a){if(a){const e=a.substring(0,4);return Bt.video[e]}return 2}function ks(a){const e=Ea();return a.split(",").reduce((t,s)=>{const r=e&&Ys(s)?9:Bt.video[s];return r?(r*2+t)/(t?3:2):(Bt.audio[s]+t)/(t?2:1)},0)}const ri={};function fc(a,e=!0){if(ri[a])return ri[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(er(t[i],"audio",e))return ri[a]=t[i],t[i];if(t[i]==="mp3"&&(s=Et(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const gc=/flac|opus|mp4a\.40\.34/i;function ws(a,e=!0){return a.replace(gc,t=>fc(t.toLowerCase(),e))}function mc(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)Ji(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function As(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Ur(a,"audio")||Ur(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function Ur(a,e){return Ji(a,e)&&er(a,e)}function pc(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function yc(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function $r(a){const e=Et(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Pi(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ec={supported:!0,powerEfficient:!0,smooth:!0},vc={supported:!1,smooth:!1,powerEfficient:!1},va={supported:!0,configurations:[],decodingInfoResults:[Ec]};function Ta(a,e){return{supported:!1,configurations:e,decodingInfoResults:[vc],error:a}}function Tc(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>Ys(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&G(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Sa(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(va);const r=[],n=Sc(a),o=n.length,c=xc(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Ys(u))&&Ea())return Promise.resolve(Ta(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=Ic(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Sc(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=xa(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:Qt(yc(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function xc(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=xa(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(g=>{const f={contentType:Qt(g,"audio"),bitrate:t?Ac(g,r):r};d&&(f.channels=""+d),h.push(f)})}return h},n):n},[]):[]}function Ac(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function xa(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function Ic(a){let e="";const{audio:t,video:s}=a;if(s){const i=Pi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Pi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const ki=["NONE","TYPE-0","TYPE-1",null];function Lc(a){return ki.indexOf(a)>-1}const Os=["SDR","PQ","HLG"];function Rc(a){return!!a&&Os.indexOf(a)>-1}var Is={No:"",Yes:"YES",v2:"v2"};function Gr(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?Is.v2:Is.Yes:Is.No}class Kr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Zt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Vr(this._audioGroups,e)}hasSubtitleGroup(e){return Vr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Vr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function bc(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function _c(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||Os.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&bc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Dc=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ce=(a,e)=>JSON.stringify(a,Dc(e));function Cc(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,g=1/0,f=1/0,p=1/0,y=0,E=[];const{preferHDR:v,allowedVideoRanges:T}=_c(e,i);for(let I=r.length;I--;){const b=a[r[I]];h||(h=b.channels[2]>0),d=Math.min(d,b.minHeight),g=Math.min(g,b.minFramerate),f=Math.min(f,b.minBitrate),T.filter(C=>b.videoRanges[C]>0).length>0&&(u=!0)}d=G(d)?d:0,g=G(g)?g:0;const x=Math.max(1080,d),S=Math.max(30,g);f=G(f)?f:t,t=Math.max(f,t),u||(e=void 0);const R=r.length>1;return{codecSet:r.reduce((I,b)=>{const L=a[b];if(b===I)return I;if(E=u?T.filter(C=>L.videoRanges[C]>0):[],R){if(L.minBitrate>t)return je(b,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),I;if(!L.hasDefaultAudio)return je(b,"no renditions with default or auto-select sound found"),I;if(o&&b.indexOf(o.substring(0,4))%5!==0)return je(b,`audio codec preference "${o}" not found`),I;if(n&&!l){if(!L.channels[n])return je(b,`no renditions with ${n} channel sound found (channels options: ${Object.keys(L.channels)})`),I}else if((!o||l)&&h&&L.channels[2]===0)return je(b,"no renditions with stereo sound found"),I;if(L.minHeight>x)return je(b,`min resolution of ${L.minHeight} > maximum of ${x}`),I;if(L.minFramerate>S)return je(b,`min framerate of ${L.minFramerate} > maximum of ${S}`),I;if(!E.some(C=>L.videoRanges[C]>0))return je(b,`no variants with VIDEO-RANGE of ${ce(E)} found`),I;if(c&&b.indexOf(c.substring(0,4))%5!==0)return je(b,`video codec preference "${c}" not found`),I;if(L.maxScore<y)return je(b,`max score of ${L.maxScore} < selected max of ${y}`),I}return I&&(ks(b)>=ks(I)||L.fragmentError>a[I].fragmentError)?I:(p=L.minIndex,y=L.maxScore,b)},void 0),videoRanges:E,preferHDR:v,minFramerate:g,minBitrate:f,minIndex:p}}function je(a,e){re.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Aa(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pc(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Hr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function Je(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(Lt(a,i,t))return s}return-1}function Lt(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||kc(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||wc(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function kc(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function wc(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function At(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Oc(a,e,t,s,i){const r=e[s],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=Yr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Je(a,f,i)>-1});return u>-1?u:Yr(e,s,d=>{const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Je(a,f,i)>-1})}function Yr(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function Fs(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Fc extends Ve{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,g=n.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const v=n.mainForwardBufferInfo;if(!E&&v===null)return;const T=this.bwEstimator.getEstimateTTFB(),x=Math.abs(c.playbackRate);if(d<=Math.max(T,1e3*(u/(x*2))))return;const S=v?v.len/x:0,R=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&R>-1,I=this.getBwEstimate(),b=n.levels,L=b[f],C=Math.max(h.loaded,Math.round(u*(i.bitrate||L.averageBitrate)/8));let w=A?d-R:d;w<1&&A&&(w=Math.min(d,h.loaded*8/I));const U=A?h.loaded*1e3/w:0,F=T/1e3,N=U?(C-h.loaded)/U:C*8/I+F;if(N<=S)return;const k=U?U*8:I,$=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,B=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,W;for(W=f-1;W>g;W--){const te=b[W].maxBitrate,z=!b[W].details||$;if(K=this.getTimeToLoadFrag(F,k,u*te,z),K<Math.min(S,u+F))break}if(K>=N||K>u*10)return;A?this.bwEstimator.sample(d-Math.min(T,R),h.loaded):this.bwEstimator.sampleTTFB(d);const M=b[W].maxBitrate;this.getBwEstimate()*B>M&&this.resetEstimator(M);const O=this.findBestLevel(M,g,W,0,S,1,1);O>-1&&(W=O),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly; 2 - Fragment duration: ${i.duration.toFixed(3)} 3 - Time to underbuffer: ${S.toFixed(3)} s 4 - Estimated load time for current fragment: ${N.toFixed(3)} s 5 - Estimated load time for down switch fragment: ${K.toFixed(3)} s 6 - TTFB estimate: ${R|0} ms 7 - Current BW estimate: ${G(I)?I|0:"Unknown"} bps 8 - New BW estimate: ${this.getBwEstimate()|0} bps 9 - Switching to level ${W} @ ${M|0} bps`),n.nextLoadLevel=n.nextAutoLevel=W,this.clearTimer();const X=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===W&&W>0){const te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""} 10 - Fragment duration: ${i.duration.toFixed(3)} s 11 - Time to underbuffer: ${te.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>g){let z=this.findBestLevel(this.hls.levels[g].bitrate,g,W,0,te,1,1);z===-1&&(z=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=z,this.resetEstimator(this.hls.levels[z].bitrate)}}};y||N>K*2?X():this.timer=self.setInterval(X,K*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},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 $l(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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;G(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===V.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==V.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[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:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,n,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const g=this.findBestLevel(c,n,i,l,d,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[n],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(f.length===1)return 0;const v=f[u],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),x=y===-1||h===-1;let S,R="SDR",A=v?.frameRate||0;const{audioPreference:I,videoPreference:b}=E,L=this.audioTracksByGroup||(this.audioTracksByGroup=Aa(p));let C=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;const k=this.codecTiers||(this.codecTiers=Pc(f,L,t,s)),$=Cc(k,R,e,I,b),{codecSet:B,videoRanges:K,minFramerate:W,minBitrate:M,minIndex:O,preferHDR:X}=$;C=O,S=B,R=X?K[K.length-1]:K[0],A=W,e=Math.max(e,M),this.log(`picked start tier ${ce($)}`)}else S=v?.codecSet,R=v?.videoRange;const w=g?g.duration:d?d.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,F=[];for(let k=s;k>=t;k--){var N;const $=f[k],B=k>u;if(!$)continue;if(E.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){const z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&Tc($,L,R,A,e,I)?($.supportedPromise=Sa($,L,z,this.supportedCache),$.supportedPromise.then(Z=>{if(!this.hls)return;$.supportedResult=Z;const ve=this.hls.levels,ge=ve.indexOf($);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${ge} ${ce(Z)}`):Z.supported?Z.decodingInfoResults.some(_e=>_e.smooth===!1||_e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ge} not smooth or powerEfficient: ${ce(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ge} ${ce(Z)}`),ge>-1&&ve.length>1&&(this.log(`Removing unsupported level ${ge}`),this.hls.removeLevel(ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):$.supportedResult=va}if((S&&$.codecSet!==S||R&&$.videoRange!==R||B&&A>$.frameRate||!B&&A>0&&A<$.frameRate||(N=$.supportedResult)!=null&&(N=N.decodingInfoResults)!=null&&N.some(z=>z.smooth===!1))&&(!x||k!==C)){F.push(k);continue}const K=$.details,W=(g?K?.partTarget:K?.averagetargetduration)||w;let M;B?M=o*e:M=n*e;const O=w&&i>=w*2&&r===0?$.averageBitrate:$.maxBitrate,X=this.getTimeToLoadFrag(U,M,O*W,K===void 0);if(M>=O&&(k===h||$.loadError===0&&$.fragmentError===0)&&(X<=U||!G(X)||T&&!this.bitrateTestDelay||X<l)){const z=this.forcedAutoLevel;return k!==y&&(z===-1||z!==y)&&(F.length&&this.trace(`Skipped level(s) ${F.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[F[0]].codecs}" ${f[F[0]].videoRange}; not compatible with "${S}" ${R}`),this.info(`switch candidate:${u}->${k} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-O)} ttfb:${U.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${x} codecSet:${$.codecSet} videoRange:${$.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=k),k}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Ia={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Mc(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!G(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(Bc(e,t,n))return n}return null}function Rt(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&Wr(t,s,r)===0||Nc(r,a,Math.min(i,s))))return r;const n=Ia.search(e,Wr.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Nc(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function Wr(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function Bc(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function La(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return Ia.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function Ms(a){switch(a.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ra(a){return a.details.startsWith("key")}function ba(a){return Ra(a)&&!!a.frag&&!a.frag.decryptdata}function qr(a,e){const t=Ms(e);return a.default[`${t?"timeout":"error"}Retry`]}function tr(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function jr(a){return ie(ie({},a),{errorRetry:null,timeoutRetry:null})}function Ns(a,e,t,s){if(!a)return!1;const i=s?.code,r=e<a.maxNumRetry&&(Uc(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function Uc(a){return wi(a)||!!a&&(a<400||a>499)}function wi(a){return a===0&&navigator.onLine===!1}var Ie={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ne={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class $c extends Ve{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===V.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Ot();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ie.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var n;const c=t.parent===V.MAIN?t.level:i.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===J.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===J.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ie.SendAlternateToPenaltyBox,t.errorAction.flags=Ne.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction=Ot();return}t.type===Y.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Ot())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=qr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ns(i,r,Ms(e),e.response))return{action:Ie.RetryRequest,flags:Ne.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=qr(Ra(e)?n:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==D.FRAG_GAP&&i.fragmentError++,!ba(e)&&Ns(o,c,Ms(e),e.response)))return{action:Ie.RetryRequest,flags:Ne.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===D.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===V.AUDIO&&l===D.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:R})=>i.audioCodec!==R),T=e.sourceBufferName==="video"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR)&&u.some(({codecSet:R,audioCodec:A})=>i.codecSet!==R&&i.audioCodec===A),{type:x,groupId:S}=(n=e.context)!=null?n:{};for(let R=u.length;R--;){const A=(R+d)%u.length;if(A!==d&&A>=g&&A<=f&&u[A].loadError===0){var o,c;const I=u[A];if(l===D.FRAG_GAP&&p===V.MAIN&&e.frag){const b=u[A].details;if(b){const L=Rt(e.frag,b.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(x===J.AUDIO_TRACK&&I.hasAudioGroup(S)||x===J.SUBTITLE_TRACK&&I.hasSubtitleGroup(S))continue;if(p===V.AUDIO&&(o=i.audioGroups)!=null&&o.some(b=>I.hasAudioGroup(b))||p===V.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(b=>I.hasSubtitleGroup(b))||E&&i.audioCodec===I.audioCodec||T&&i.codecSet===I.codecSet||!E&&i.codecSet!==I.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ie.SendAlternateToPenaltyBox,flags:Ne.None,nextAutoLevel:h}}return{action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ie.DoNothing:break;case Ie.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.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,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ne.None:this.switchLevel(e,r);break;case Ne.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=ki[ki.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ne.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var n,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(n=l[d].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Le(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==V.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===D.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Pi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Ot(a){const e={action:Ie.DoNothing,flags:Ne.None};return a&&(e.resolved=!0),e}var Ee={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Gc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if(o?.body.type===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=_t(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),hs(r)||this.removeParts(s.sn-1,s.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 s=this.activePartLists[t];s&&(this.activePartLists[t]=Xr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=_t(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<d&&o>u){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&hs(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||hs(t))}getState(e){const t=_t(e),s=this.fragments[t];return s?s.buffered?hs(s)?Ee.PARTIAL:Ee.OK:Ee.APPENDING:Ee.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=_t(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_t(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=_t(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Xr(s,r=>r.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}}function hs(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function _t(a){return`${a.type}_${a.level}_${a.sn}`}function Xr(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var vt={cbc:0,ctr:1};class Kc{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case vt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case vt.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 Vc(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Hc{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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[f]=E,t[E]=f;const v=g[f],T=g[v],x=g[T];let S=g[E]*257^E*16843008;i[f]=S<<24|S>>>8,r[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,o[f]=S,S=x*16843009^T*65537^v*257^f*16843008,l[E]=S<<24|S>>>8,h[E]=S<<16|S>>>16,u[E]=S<<8|S>>>24,d[E]=S,f?(f=v^g[g[g[x^v]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],E=g[3];let v,T;for(o=0;o<n;o++){if(o<r){v=l[o]=t[o];continue}T=v,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),l[o]=v=(l[o-r]^T)>>>0}for(c=0;c<n;c++)o=n-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?h[c]=T:h[c]=f[u[T>>>24]]^p[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],p=d[2],y=d[3];const E=new Int32Array(e),v=new Int32Array(E.length);let T,x,S,R,A,I,b,L,C,w,U,F,N,k;const $=this.networkToHostOrderSwap;for(;t<E.length;){for(C=$(E[t]),w=$(E[t+1]),U=$(E[t+2]),F=$(E[t+3]),A=C^r[0],I=F^r[1],b=U^r[2],L=w^r[3],N=4,k=1;k<i;k++)T=c[A>>>24]^l[I>>16&255]^h[b>>8&255]^u[L&255]^r[N],x=c[I>>>24]^l[b>>16&255]^h[L>>8&255]^u[A&255]^r[N+1],S=c[b>>>24]^l[L>>16&255]^h[A>>8&255]^u[I&255]^r[N+2],R=c[L>>>24]^l[A>>16&255]^h[I>>8&255]^u[b&255]^r[N+3],A=T,I=x,b=S,L=R,N=N+4;T=n[A>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[L&255]^r[N],x=n[I>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[A&255]^r[N+1],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[I&255]^r[N+2],R=n[L>>>24]<<24^n[A>>16&255]<<16^n[I>>8&255]<<8^n[b&255]^r[N+3],v[t]=$(T^g),v[t+1]=$(R^f),v[t+2]=$(S^p),v[t+3]=$(x^y),g=C,f=w,p=U,y=F,t=t+4}return v.buffer}}class Yc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Wc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Wc(a){switch(a){case vt.cbc:return"AES-CBC";case vt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const qc=16;class sr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Vc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==vt.cbc||t.byteLength!==16)return re.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ke(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Hc),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Yc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kc(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(re.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%qc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(re.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const zr=Math.pow(2,17);class jc{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 s=e.url;if(!s)return Promise.reject(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(Zr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Qr(e);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zr};e.stats=l.stats;const g={onSuccess:(f,p,y,E)=>{this.resetLoader(e,l);let v=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:E})},onError:(f,p,y,E)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ie({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:E}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Zr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Qr(e,t);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zr};t.stats=l.stats,l.load(h,d,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:g.data,networkDetails:y};s(E),o(E)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ie({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(G(i)&&G(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&Xc((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Zr(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:Y.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new ot(s)}function Xc(a){return a==="AES-128"||a==="AES-256"}class ot extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class _a extends Ve{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 ir{constructor(e,t,s,i=0,r=-1,n=!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=us(),this.buffering={audio:us(),video:us(),audiovideo:us()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function us(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jr={length:0,start:()=>0,end:()=>0};class j{static isBuffered(e,t){if(e){const s=j.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=j.getBuffered(e);return j.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=j.bufferedRanges(e);if(i.length)return j.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,n=l-t;else if(t+s<u){o=u;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Jr}catch(t){return re.log("failed to get media.buffered",t),Jr}}}const Da=/\{\$([a-zA-Z0-9-_]+)\}/g;function en(a){return Da.test(a)}function Oi(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Da,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function tn(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function zc(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Qc=/^(\d+)x(\d+)$/,sn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ue{constructor(e,t){typeof e=="string"&&(e=ue.parseAttrList(e,t)),ne(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Qc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(sn.lastIndex=0;(s=sn.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Oi(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="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":re.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const Zc="com.apple.hls.interstitial";function Jc(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function eh(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Ca{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){re.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=ne(new ue({}),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"]);G(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?(re.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(G(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===Zc}get isValid(){return!!this.id&&!this._badValueForSameId&&G(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 th=10;class sh{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>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 s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||th}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Bs(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function rn(a,e){return!a&&!e?!0:!a||!e?!1:Bs(a,e)}function Ft(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function rr(a){switch(a){case"AES-128":case"AES-256":return vt.cbc;case"AES-256-CTR":return vt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function nr(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Fi(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function ih(a){const e=Fi(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Pa(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function ka(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=nr(n)):t=ih(n)}}return t}const Us=typeof self<"u"?self:void 0;var de={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Re={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ls(a){switch(a){case Re.FAIRPLAY:return de.FAIRPLAY;case Re.PLAYREADY:return de.PLAYREADY;case Re.WIDEVINE:return de.WIDEVINE;case Re.CLEARKEY:return de.CLEARKEY}}function ni(a){switch(a){case de.FAIRPLAY:return Re.FAIRPLAY;case de.PLAYREADY:return Re.PLAYREADY;case de.WIDEVINE:return Re.WIDEVINE;case de.CLEARKEY:return Re.CLEARKEY}}function Wt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[de.FAIRPLAY,de.WIDEVINE,de.PLAYREADY,de.CLEARKEY].filter(i=>!!e[i]):[];return!s[de.WIDEVINE]&&t&&s.push(de.WIDEVINE),s}const wa=(function(a){return Us!=null&&(a=Us.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function rh(a,e,t,s){let i;switch(a){case de.FAIRPLAY:i=["cenc","sinf"];break;case de.WIDEVINE:case de.PLAYREADY:i=["cenc"];break;case de.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return nh(i,e,t,s)}function nh(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ah(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Oa(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=nr(o).subarray(0,16);return Pa(c),c}}return null}let Dt={};class yt{static clearKeyUriToKeyIdMap(){Dt={}}static setKeyIdForUri(e,t){Dt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Dt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Dt[e]=s,s}constructor(e,t,s,i=[1],r=null,n){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=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ft(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(la(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Bs(e.keyFormatVersions,this.keyFormatVersions)&&rn(e.iv,this.iv)&&rn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ft(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Re.FAIRPLAY:case Re.WIDEVINE:case Re.PLAYREADY:case Re.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(Ft(this.method)){let r=this.iv;return r||(typeof e!="number"&&(re.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=lh(e)),new yt(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Dt[this.uri];if(r&&!Bs(this.keyId,r)&&yt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=ka(this.uri);if(s)switch(this.keyFormat){case Re.WIDEVINE:if(this.pssh=s,!this.keyId){const r=uc(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=nn(t));break;case Re.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hc(r,null,s),this.keyId=Oa(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=oh(t),r||(r=nn(t),r||(r=Dt[this.uri])),r&&(this.keyId=r,yt.setKeyIdForUri(this.uri,r))}return this}}function oh(a){const e=a?.[Re.WIDEVINE];return e?e.keyId:null}function nn(a){const e=a?.[Re.PLAYREADY];if(e){const t=ka(e.uri);if(t)return Oa(t)}return null}function lh(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const an=/#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,on=/#EXT-X-MEDIA:(.*)/g,ch=/^#EXT(?:INF|-X-TARGETDURATION):/m,ai=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hh=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 et{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return zi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return ch.test(e)}static parseMasterPlaylist(e,t){const s=en(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(an.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=an.exec(e))!=null;)if(n[1]){var o;const l=new ue(n[1],i),h=Oi(i,n[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:et.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),hn(l.CODECS,u);const g=l["SUPPLEMENTAL-CODECS"];g&&(u.supplemental={},hn(g,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const u=new ue(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=ln(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):re.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new ue(h,i);tn(i,u,t)}break}case"CONTENT-STEERING":{const u=new ue(h,i);i.contentSteering={uri:et.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=cn(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(on.lastIndex=0;(i=on.exec(e))!==null;){const l=new ue(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],v={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?et.resolve(l.URI,t):""};if(f&&(v.assocLang=f),p&&(v.channels=p),y&&(v.characteristics=y),E&&(v.instreamId=E),u!=null&&u.length){const T=et.findGroup(u,v.groupId)||u[0];un(v,T,"audioCodec"),un(v,T,"textCodec")}d.push(v)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new sh(t),h=l.fragments,u=[];let d=null,g=0,f=0,p=0,y=0,E=0,v=null,T=new si(i,c),x,S,R,A=-1,I=!1,b=null,L;if(ai.lastIndex=0,l.m3u8=e,l.hasVariableRefs=en(e),((o=ai.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(x=ai.exec(e))!==null;){I&&(I=!1,T=new si(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),b&&(T.setByteRange(b),b=null)));const F=x[1];if(F){T.duration=parseFloat(F);const N=(" "+x[2]).slice(1);T.title=N||null,T.tagList.push(N?["INF",F,N]:["INF",F])}else if(x[3]){if(G(T.duration)){T.playlistOffset=p,T.setStart(p),R&&fn(T,R,l),T.sn=g,T.level=s,T.cc=y,h.push(T);const N=(" "+x[3]).slice(1);T.relurl=Oi(l,N),Mi(T,v,u),v=T,p+=T.duration,g++,f=0,I=!0}}else{if(x=x[0].match(hh),!x){re.warn("No matches on slow regex match for level playlist!");continue}for(S=1;S<x.length&&x[S]===void 0;S++);const N=(" "+x[S]).slice(1),k=(" "+x[S+1]).slice(1),$=x[S+2]?(" "+x[S+2]).slice(1):null;switch(N){case"BYTERANGE":v?T.setByteRange(k,v):T.setByteRange(k);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=k,T.tagList.push(["PROGRAM-DATE-TIME",k]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&rt(l,N,x),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?rt(l,N,x):h.length>0&&gn(l,N,x),g=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&rt(l,N,x);const B=new ue(k,l),K=B.decimalInteger("SKIPPED-SEGMENTS");if(G(K)){l.skippedSegments+=K;for(let M=K;M--;)h.push(null);g+=K}const W=B.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&rt(l,N,x),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&rt(l,N,x),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||rt(l,N,x),l.live=!1;break;case"#":(k||$)&&T.tagList.push($?[k,$]:[k]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([N]);break;case"BITRATE":T.tagList.push([N,k]),E=parseInt(k)*1e3,G(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const B=new ue(k,l),K=new Ca(B,l.dateRanges[B.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:re.warn(`Ignoring invalid DATERANGE tag: "${k}"`),T.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const B=new ue(k,l);"IMPORT"in B?zc(l,B,n):tn(l,B,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?rt(l,N,x):h.length>0&&gn(l,N,x),l.startCC=y=parseInt(k);break;case"KEY":{const B=ln(k,t,l);if(B.isSupported()){if(B.method==="NONE"){R=void 0;break}R||(R={});const K=R[B.keyFormat];K!=null&&K.matches(B)||(K&&(R=ne({},R)),R[B.keyFormat]=B)}else re.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=cn(k);break;case"MAP":{const B=new ue(k,l);if(T.duration){const K=new si(i,c);dn(K,B,s,R),d=K,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const K=T.byteRangeEndOffset;if(K){const W=T.byteRangeStartOffset;b=`${K-W}@${W}`}else b=null;dn(T,B,s,R),d=T,I=!0}d.cc=y;break}case"SERVER-CONTROL":{L&&rt(l,N,x),L=new ue(k),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&rt(l,N,x);const B=new ue(k);l.partTarget=B.decimalFloatingPoint("PART-TARGET");break}case"PART":{let B=l.partList;B||(B=l.partList=[]);const K=f>0?B[B.length-1]:void 0,W=f++,M=new ue(k,l),O=new zl(M,T,c,W,K);B.push(O),T.duration+=O.duration;break}case"PRELOAD-HINT":{const B=new ue(k,l);l.preloadHint=B;break}case"RENDITION-REPORT":{const B=new ue(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(B);break}default:re.warn(`line parsed but not handled: ${x}`);break}}}v&&!v.relurl?(h.pop(),p-=v.duration,l.partList&&(l.fragmentHint=v)):l.partList&&(Mi(T,v,u),T.cc=y,l.fragmentHint=T,R&&fn(T,R,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,w=h[0],U=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&U){l.averagetargetduration=p/C;const F=U.sn;l.endSN=F!=="initSegment"?F:0,l.live||(U.endList=!0),A>0&&(dh(h,A),w&&u.unshift(w))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&w&&Fa(u,l),l.endCC=y,l}}function Fa(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var n;if(((n=a[h])==null?void 0:n.sn)<e.startSN)break;const u=uh(e,l,a,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function uh(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const h=a.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let g=d;g>l;g--){const f=h[g].programDateTime;if(e>=f&&e<f+h[g].duration*1e3)return g}}return l}}}return-1}function ln(a,e,t){var s,i;const r=new ue(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&re.error(`Invalid IV: ${r.IV}`);const u=o?et.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new yt(n,u,h,d,c,r.KEYID)}function cn(a){const t=new ue(a).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function hn(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>Ji(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function un(a,e,t){const s=e[t];s&&(a[t]=s)}function dh(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Mi(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function dn(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function fn(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function rt(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function gn(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function oi(a,e){const t=e.startPTS;if(G(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function Ma(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(G(h)){const E=Math.abs(h-t);a&&E>a.totalduration?n.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${a.url}`):G(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const g=e.sn;if(!a||g<a.startSN||g>a.endSN)return 0;let f;const p=g-a.startSN,y=a.fragments;for(y[p]=e,f=p;f>0;f--)oi(y[f],y[f-1]);for(f=p;f<y.length-1;f++)oi(y[f],y[f+1]);return a.fragmentHint&&oi(y[y.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,d}function fh(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;ph(a,e,(h,u,d,g)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const f=h.cc-u.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}G(h.startPTS)&&G(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=gh(a.dateRanges,e,t));const h=a.fragments.filter(u=>u.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Mi(o[u],o[u-1],h);Fa(h,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const h=Ua(a,e.startSN-1);e.startCC=(c=h?.cc)!=null?c:n[0].cc}mh(a.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?Ma(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Na(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function gh(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ne({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new Ca(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[c].attr)}"`)}),r):s}function mh(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function ph(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=c[n+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,g=u.relurl;if(d&&yh(d,g)){e.playlistParsingError=mn(`media sequence mismatch ${u.sn}:`,a,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=mn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,a,e,h,u);return}}}}function mn(a,e,t,s,i){return new Error(`${a} ${i.url} 12 - Playlist starting @${e.startSN} 13 - ${e.m3u8} 14 - 15 - Playlist starting @${t.startSN} 16 - ${t.m3u8}`)}function Na(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;Ni(e,n)}function Ni(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Ba(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ua(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function pn(a,e,t){return a?$a(a.partList,e,t):null}function $a(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ga(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function yh(a,e){return a!==e&&e?yn(a)!==yn(e):!1}function yn(a){return a.replace(/\?[^?]*$/,"")}function qt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Eh(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function En(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Ka(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)En(t[s],a);e.fragmentHint&&En(e.fragmentHint,a),e.alignedSliding=!0}function vh(a,e){a&&(Va(e,a),e.alignedSliding||$s(e,a),!e.alignedSliding&&!e.skippedSegments&&Na(a,e,!1))}function Va(a,e){if(!Eh(e,a))return;const t=Math.min(e.endCC,a.endCC),s=qt(e.fragments,t),i=qt(a.fragments,t);if(!s||!i)return;re.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Ka(r,a)}function $s(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=qt(s,n),r=qt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=qt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Ka(l,a)}function Ce(a,e,t){Oe(a,e,t),a.addEventListener(e,t)}function Oe(a,e,t){a.removeEventListener(e,t)}const Th={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ar extends _a{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=j.bufferInfo(l||c,u,n.maxBufferHole),g=!d.len;if(this.log(`Media seeking to ${G(u)?u.toFixed(3):u}, state: ${h}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const f=n.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(u>f&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),g&&this.state===P.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 jc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new sr(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===P.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=P.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 s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=j.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return j.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ce(s,"seeking",this.onMediaSeeking),Ce(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Oe(i,"seeking",this.onMediaSeeking),Oe(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===P.FRAG_LOADING||!this.fragCurrent&&n===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ee.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ee.PARTIAL&&s.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,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Ft(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,rr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,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 s=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:${s?Th.toString(j.getBuffered(s)):"(detached)"})`),me(e)){var i;if(e.type!==V.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new ir(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),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||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(me(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&me(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const g=this.getNextPart(d,e,s);if(g>-1){const f=d[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${d.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(me(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.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} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==V.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const g=d.part;this.hls.trigger(m.FRAG_LOADED,d);const f=pn(s.details,e.sn,u.index+1)||$a(l,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Y.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:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===V.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?pn(c,r,n):null,h=l?l.fragment:Ua(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=Ke(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!j.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=j.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!G(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=j.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return j.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=V.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(d!==-1&&d>=n?d:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ee.OK||s===Ee.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(vn(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(vn(this.config)&&e.type!==V.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Mc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=La(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;d=Rt(r,n,e,p)}else d=n[n.length-1];if(d){const f=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Ee.OK||p===Ee.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[f+1];d.sn<o&&this.fragmentTracker.getState(E)!==Ee.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&G(r);if(n||!o&&!r){vh(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),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 s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&G(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&me(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!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===D.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,g=d&&c===Ie.RetryRequest,f=d&&!o.resolved&&l===Ne.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&me(i)&&!i.endList&&p&&!ba(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&h<u.maxNumRetry){var y;const E=wi((y=t.response)==null?void 0:y.code),v=tr(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${v}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==Ie.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Ie.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!wi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===V.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=j.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.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?"<removed>":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,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:Ma(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.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===V.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 vn(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Ha{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Sh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Sh(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var li={exports:{}},Tn;function xh(){return Tn||(Tn=1,(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,u||c,d),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,g=u.length,f=new Array(g);d<g;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,v,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,g),!0;case 6:return y.fn.call(y.context,h,u,d,g,f),!0}for(T=1,v=new Array(E-1);T<E;T++)v[T-1]=arguments[T];y.fn.apply(y.context,v)}else{var x=y.length,S;for(T=0;T<x;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!v)for(S=1,v=new Array(E-1);S<E;S++)v[S-1]=arguments[S];y[T].fn.apply(y[T].context,v)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var g=t?t+l:l;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&n(this,g);else{for(var p=0,y=[],E=f.length;p<E;p++)(f[p].fn!==h||d&&!f[p].once||u&&f[p].context!==u)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(li)),li.exports}var Ah=xh(),or=jl(Ah);const Jt="1.6.15",Ut={};function Ih(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Lh(){const a=Ut[Jt];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Ut[Jt]=i,i}function Rh(a){const e=Ut[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Ut[a]=i,i}function bh(a){const e=Ut[a||Jt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Ut[a||Jt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Ya(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function lr(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Ws(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function es(a,e){const t=e;let s=0;for(;lr(a,e);){s+=10;const i=Ws(a,e+6);s+=i,Ya(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function _h(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const g=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return re.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Wa(a,e){return a[e]===255&&(a[e+1]&246)===240}function qa(a,e){return a[e+1]&1?7:9}function cr(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Dh(a,e){return e+5<a.length}function Gs(a,e){return e+1<a.length&&Wa(a,e)}function Ch(a,e){return Dh(a,e)&&Wa(a,e)&&cr(a,e)<=a.length-e}function Ph(a,e){if(Gs(a,e)){const t=qa(a,e);if(e+t>=a.length)return!1;const s=cr(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||Gs(a,i)}return!1}function ja(a,e,t,s,i){if(!a.samplerate){const r=_h(e,t,s,i);if(!r)return;ne(a,r)}}function Xa(a){return 1024*9e4/a}function kh(a,e){const t=qa(a,e);if(e+t<=a.length){const s=cr(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function za(a,e,t,s,i){const r=Xa(a.samplerate),n=s+i*r,o=kh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,g=d+u,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+g);const p={unit:c,pts:n};return f||a.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function wh(a,e){return lr(a,e)&&Ws(a,e+6)+10<=a.length-e}function Oh(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function ci(a,e=0,t=1/0){return Fh(a,e,t,Uint8Array)}function Fh(a,e,t,s){const i=Mh(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=Nh(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Mh(a){return a instanceof ArrayBuffer?a:a.buffer}function Nh(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Bh(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=$e(ci(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=$e(ci(a.data,3+s,n));let c;return i==="-->"?c=$e(ci(a.data,4+s+n)):c=Oh(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Uh(a){if(a.size<2)return;const e=$e(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function $h(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=$e(a.data.subarray(t),!0);t+=s.length+1;const i=$e(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=$e(a.data.subarray(1));return{key:a.type,info:"",data:e}}function Gh(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=$e(a.data.subarray(t),!0);t+=s.length+1;const i=$e(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=$e(a.data);return{key:a.type,info:"",data:e}}function Kh(a){return a.type==="PRIV"?Uh(a):a.type[0]==="W"?Gh(a):a.type==="APIC"?Bh(a):$h(a)}function Vh(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ws(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const ds=10,Hh=10;function Qa(a){let e=0;const t=[];for(;lr(a,e);){const s=Ws(a,e+6);a[e+5]>>6&1&&(e+=ds),e+=ds;const i=e+s;for(;e+Hh<i;){const r=Vh(a.subarray(e)),n=Kh(r);n&&t.push(n),e+=r.size+ds}Ya(a,e)&&(e+=ds)}return t}function Za(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Yh(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function hr(a){const e=Qa(a);for(let t=0;t<e.length;t++){const s=e[t];if(Za(s))return Yh(s)}}let Ue=(function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a})({});function Qe(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ur{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Ke(this.cachedData,e),this.cachedData=null);let s=es(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?hr(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&G(c))&&(this.basePTS=Wh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ue.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else wh(e,i)?(s=es(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ue.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=Ke(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Qe(),id3Track:o,textTrack:Qe()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Qe(),id3Track:this._id3Track,textTrack:Qe()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Wh=(a,e,t)=>{if(G(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let fs=null;const qh=[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],jh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zh=[0,1,1,4];function Ja(a,e,t,s,i){if(t+24>e.length)return;const r=eo(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function eo(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=qh[c*14+i-1]*1e3,u=jh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,g=Xh[t][s],f=zh[s],p=g*8*f,y=Math.floor(g*l/u+n)*f;if(fs===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fs=T?parseInt(T[1]):0}return fs&&fs<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function dr(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function to(a,e){return e+1<a.length&&dr(a,e)}function Qh(a,e){return dr(a,e)&&4<=a.length-e}function so(a,e){if(e+1<a.length&&dr(a,e)){const s=eo(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||to(a,r)}return!1}class Zh extends ur{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=es(e,0);let i=s?.length||0;if(so(e,i))return!1;for(let r=e.length;i<r;i++)if(Ph(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ch(e,t)}appendFrame(e,t,s){ja(e,this.observer,t,s,e.manifestCodec);const i=za(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const io=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Jh extends ur{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=ro(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=es(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&hr(t)!==void 0&&io(e,s)<16}}function ro(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+g,y=e[t+5]>>3,E=e[t+5]&7,v=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,x=s+i*T,S=e.subarray(t,t+h);return a.config=v,a.channelCount=p,a.samplerate=o,a.samples.push({unit:S,pts:x}),h}class eu extends ur{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=es(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&hr(t)!==void 0&&io(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(so(e,s))return re.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Qh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Ja(e,t,s,this.basePTS,this.frameIndex)}}const tu=/\/emsg[-/]ID3/i;class su{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Qe("video",1),n=this.audioTrack=Qe("audio",1),o=this.txtTrack=Qe("text",1);if(this.id3Track=Qe("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ga(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=ua.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Jl(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ke(this.remainderData,e));const o=ac(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Nr(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Nr(e,t),{videoTrack:t,audioTrack:Qe(),id3Track:i,textTrack:Qe()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Q(e.samples,["emsg"]);i&&i.forEach(r=>{const n=lc(r);if(tu.test(n.schemeIdUri)){const o=Sn(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ue.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Sn(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Ue.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Sn(a,e){return G(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class iu{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new sr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,vt.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=ya(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class no{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,g=0;for(r===-1&&(d=0,g=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const f={data:t.subarray(d,h),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&c<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=Ke(f.data,t.subarray(0,h)),f.state=0))}c<i?(u=this.getNALuType(t,c),d=c,g=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const f={data:t.subarray(d,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Ke(f.data,t))}return e.naluState=r,o}}class jt{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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.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 s=this.word>>>32-t;if(e>32&&re.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>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 ru extends no{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=p;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,Zi(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let v="avc1.";for(let T=0;T<3;T++){let x=E[T].toString(16);x.length<2&&(x="0"+x),v+=x}e.codec=v}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new jt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new jt(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const v=h();if(u(5),f(3),h(),y(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const I=d();if(I===3&&f(1),y(),y(),f(1),g())for(c=I!==3?8:12,l=0;l<c;l++)g()&&(l<6?E(16,t):E(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(f(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),f(1);const x=d(),S=d(),R=u(1);R===0&&f(1),f(1),g()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(g()&&g())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((x+1)*16-s*2-i*2),height:(2-R)*(S+1)*16-(R?2:4)*(r+n),pixelRatio:A}}}class nu extends no{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,Zi(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ne(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new jt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new jt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),v=[],T=[];for(let ee=0;ee<s;ee++)v.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)v[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[ee]&&t.readUByte();t.readUEG();const x=t.readUEG();x==3&&t.skipBits(1);const S=t.readUEG(),R=t.readUEG(),A=t.readBoolean();let I=0,b=0,L=0,C=0;A&&(I+=t.readUEG(),b+=t.readUEG(),L+=t.readUEG(),C+=t.readUEG());const w=t.readUEG(),U=t.readUEG(),F=t.readUEG(),N=t.readBoolean();for(let ee=N?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Te=0;Te<4;Te++)for(let Pe=0;Pe<(Te===3?2:6);Pe++)if(!t.readBoolean())t.readUEG();else{const ae=Math.min(64,1<<4+(Te<<1));Te>1&&t.readEG();for(let Ae=0;Ae<ae;Ae++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const B=t.readUEG();let K=0;for(let ee=0;ee<B;ee++){let Te=!1;if(ee!==0&&(Te=t.readBoolean()),Te){ee===B&&t.readUEG(),t.readBoolean(),t.readUEG();let Pe=0;for(let it=0;it<=K;it++){const ae=t.readBoolean();let Ae=!1;ae||(Ae=t.readBoolean()),(ae||Ae)&&Pe++}K=Pe}else{const Pe=t.readUEG(),it=t.readUEG();K=Pe+it;for(let ae=0;ae<Pe;ae++)t.readUEG(),t.readBoolean();for(let ae=0;ae<it;ae++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ee=t.readUEG();for(let Te=0;Te<ee;Te++){for(let Pe=0;Pe<F+4;Pe++)t.readBits(1);t.readBits(1)}}let M=0,O=1,X=1,te=!0,z=1,Z=0;t.readBoolean(),t.readBoolean();let ve=!1;if(t.readBoolean()){if(t.readBoolean()){const Ge=t.readUByte(),Tr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],rs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ge>0&&Ge<16?(O=Tr[Ge-1],X=rs[Ge-1]):Ge===255&&(O=t.readBits(16),X=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(),ve=t.readBoolean(),ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(z=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const rs=t.readBoolean(),Sr=t.readBoolean();let Gt=!1;(rs||Sr)&&(Gt=t.readBoolean(),Gt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Gt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let xr=0;xr<=s;xr++){te=t.readBoolean();const Uo=te||t.readBoolean();let Ar=!1;Uo?t.readEG():Ar=t.readBoolean();const Ir=Ar?1:t.readUEG()+1;if(rs)for(let Kt=0;Kt<Ir;Kt++)t.readUEG(),t.readUEG(),Gt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Sr)for(let Kt=0;Kt<Ir;Kt++)t.readUEG(),t.readUEG(),Gt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let _e=S,He=R;if(A){let ee=1,Te=1;x===1?ee=Te=2:x==2&&(ee=2),_e=S-ee*b-ee*I,He=R-Te*C-Te*L}const De=i?["A","B","C"][i]:"",is=o<<24|c<<16|l<<8|h;let $t=0;for(let ee=0;ee<32;ee++)$t=($t|(is>>ee&1)<<31-ee)>>>0;let Tt=$t.toString(16);return n===1&&Tt==="2"&&(Tt="6"),{codecString:`hvc1.${De}${n}.${Tt}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,g,f,p,y],general_level_idc:E,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:M,chroma_format_idc:x,frame_rate:{fixed:te,fps:Z/z}},width:_e,height:He,pixelRatio:[O,X]}}readPPS(e){const t=new jt(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 i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Se=188;class mt{constructor(e,t,s,i){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=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=mt.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Se*5,t-Se)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=Se)if(e[c]===71&&(t-c===Se||e[c+Se]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+Se*99,e.length-Se)+1)),r||(r=Bi(e,c)===0),r&&o>1&&(n===0&&o>2||c+Se>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ua[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=mt.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=mt.createTrack("audio",i),this._id3Track=mt.createTrack("id3"),this._txtTrack=mt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,v=this._pmtId,T=e.length;if(this.remainderData&&(e=Ke(this.remainderData,e),T=e.length,this.remainderData=null),T<Se&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const x=Math.max(0,mt.syncOffset(e));T-=(T-x)%Se,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let S=0;for(let A=x;A<T;A+=Se)if(e[A]===71){const I=!!(e[A+1]&64),b=Bi(e,A),L=(e[A+3]&48)>>4;let C;if(L>1){if(C=A+5+e[A+4],C===A+Se)continue}else C=A+4;switch(b){case h:I&&(u&&(r=Ct(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+Se)),u.size+=A+Se-C);break;case d:if(I){if(f&&(r=Ct(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(C,A+Se)),f.size+=A+Se-C);break;case g:I&&(p&&(r=Ct(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+Se)),p.size+=A+Se-C);break;case 0:I&&(C+=e[C]+1),v=this._pmtId=au(e,C);break;case v:{I&&(C+=e[C]+1);const w=ou(e,C,this.typeSupported,s,this.observer,this.logger);h=w.videoPid,h>0&&(n.pid=h,n.segmentCodec=w.segmentVideoCodec),d=w.audioPid,d>0&&(o.pid=d,o.segmentCodec=w.segmentAudioCodec),g=w.id3Pid,g>0&&(c.pid=g),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${x} to parse all TS packets.`),y=null,A=x-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=b;break}}else S++;S>0&&Ui(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=f,c.pesData=p;const R={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(R),R}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:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=Ct(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=Ct(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Ct(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new iu(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ru:e==="hevc"&&(this.videoParser=new nu))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(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 s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=Ke(i.sample.unit,r);else{const g=d-u;i.sample.unit.set(r.subarray(0,u),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!Gs(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",Ui(this.observer,new Error(u),d,this.logger),!d)return}ja(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Xa(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=za(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!Gs(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(to(s,n)){const c=Ja(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=ro(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ne({},t,{type:this._videoTrack?Ue.emsg:Ue.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Bi(a,e){return((a[e+1]&31)<<8)+a[e+2]}function au(a,e){return(a[e+10]&31)<<8|a[e+11]}function ou(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=Bi(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){hi("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){hi("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){hi("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,g=u;for(;g>2;){a[d]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3"));const p=a[d+1]+2;d+=p,g-=p}}break;case 194:case 135:return Ui(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function Ui(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function hi(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Ct(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Ke(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class lu{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 dt=Math.pow(2,32)-1;class _{static init(){_.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 _.types)_.types.hasOwnProperty(e)&&(_.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]),s=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]);_.HDLR_TYPES={video:t,audio:s};const i=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]);_.STTS=_.STSC=_.STCO=r,_.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),_.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),_.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);_.FTYP=_.box(_.types.ftyp,n,c,n,o),_.DINF=_.box(_.types.dinf,_.box(_.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return _.box(_.types.hdlr,_.HDLR_TYPES[e])}static mdat(e){return _.box(_.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(dt+1)),i=Math.floor(t%(dt+1));return _.box(_.types.mdhd,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return _.box(_.types.mdia,_.mdhd(e.timescale||0,e.duration||0),_.hdlr(e.type),_.minf(e))}static mfhd(e){return _.box(_.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"?_.box(_.types.minf,_.box(_.types.smhd,_.SMHD),_.DINF,_.stbl(e)):_.box(_.types.minf,_.box(_.types.vmhd,_.VMHD),_.DINF,_.stbl(e))}static moof(e,t,s){return _.box(_.types.moof,_.mfhd(e),_.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=_.trak(e[t]);return _.box.apply(null,[_.types.moov,_.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(_.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=_.trex(e[t]);return _.box.apply(null,[_.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(dt+1)),i=Math.floor(t%(dt+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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 _.box(_.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return _.box(_.types.sdtp,s)}static stbl(e){return _.box(_.types.stbl,_.stsd(e),_.box(_.types.stts,_.STTS),_.box(_.types.stsc,_.STSC),_.box(_.types.stsz,_.STSZ),_.box(_.types.stco,_.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=_.box(_.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return _.box(_.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,l>>8&255,l&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]),o,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&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 _.box(_.types.mp4a,_.audioStsd(e),_.box(_.types.esds,_.esds(e)))}static mp3(e){return _.box(_.types[".mp3"],_.audioStsd(e))}static ac3(e){return _.box(_.types["ac-3"],_.audioStsd(e),_.box(_.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return _.box(_.types.stsd,_.STSD,_.mp4a(e));if(t==="ac3"&&e.config)return _.box(_.types.stsd,_.STSD,_.ac3(e));if(t==="mp3"&&e.codec==="mp3")return _.box(_.types.stsd,_.STSD,_.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return _.box(_.types.stsd,_.STSD,_.avc1(e));if(t==="hevc"&&e.vps)return _.box(_.types.stsd,_.STSD,_.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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(dt+1)),o=Math.floor(s%(dt+1));return _.box(_.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,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=_.sdtp(e),i=e.id,r=Math.floor(t/(dt+1)),n=Math.floor(t%(dt+1));return _.box(_.types.traf,_.box(_.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),_.box(_.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),_.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,_.box(_.types.trak,_.tkhd(e),_.mdia(e))}static trex(e){const t=e.id;return _.box(_.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 s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return _.box(_.types.trun,n)}static initSegment(e){_.types||_.init();const t=_.moov(e);return Ke(_.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let p=0;p<s[f].length;p+=1)n+=2+s[f][p].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),n),n+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),n),n+=2,o.set(s[f][p],n),n+=s[f][p].length}const l=_.box(_.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return _.box(_.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,h>>8&255,h&255,u>>8&255,u&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]),l,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}_.types=void 0;_.HDLR_TYPES=void 0;_.STTS=void 0;_.STSC=void 0;_.STCO=void 0;_.STSZ=void 0;_.VMHD=void 0;_.SMHD=void 0;_.STSD=void 0;_.FTYP=void 0;_.DINF=void 0;const ao=9e4;function fr(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function cu(a,e,t=1,s=!1){return fr(a,e,1/t,s)}function Ht(a,e=!1){return fr(a,1e3,1/ao,e)}function hu(a,e=1){return fr(a,ao,1/e)}function xn(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const uu=10*1e3,du=1024,fu=1152,gu=1536;let Pt=null,ui=null;function An(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class Rs extends Ve{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Pt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Pt=n?parseInt(n[1]):0}if(ui===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ui=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&&xn(t)} > ${e&&xn(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 s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=Be(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,g,f,p=r,y=r;const E=e.pid>-1,v=t.pid>-1,T=t.samples.length,x=e.samples.length>0,S=o&&T>0||T>1;if((!E||x)&&(!v||S)||this.ISGenerated||o){if(this.ISGenerated){var A,I,b,L;const F=this.videoTrackConfig;(F&&(t.width!==F.width||t.height!==F.height||((A=t.pixelRatio)==null?void 0:A[0])!==((I=F.pixelRatio)==null?void 0:I[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((L=F.pixelRatio)==null?void 0:L[1]))||!F&&S||this.nextAudioTs===null&&x)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const C=this.isVideoContiguous;let w=-1,U;if(S&&(w=mu(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn(`Dropped ${w} out of ${T} video samples due to a missing keyframe`);const F=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,y+=(t.samples[0].pts-F)/t.inputTimeScale,U=y}else w===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(x&&S){const F=this.getVideoStartPts(t.samples),k=(Be(e.samples[0].pts,F)-F)/t.inputTimeScale;p+=Math.max(0,k),y+=Math.max(0,-k)}if(x){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,v||S||c===V.AUDIO?y:void 0),S){const F=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,y,C,F)}}else S&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=w,l.independent=w!==-1,l.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=oo(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=lo(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Be(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,g,f,p=-1;if(h&&(d=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):_.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?d=g=this.computeInitPts(r[0].pts,f,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:_.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(n),E=Be(n[0].dts,y),v=this.computeInitPts(E,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,v),d=Math.min(d,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:c,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,v=!1;if(!s||u===null){const M=h+t*r,O=n[0].pts-Be(n[0].dts,n[0].pts);Pt&&u!==null&&Math.abs(M-O-(u+h))<15e3?s=!0:u=M-O-h}const T=u+h;for(let M=0;M<c;M++){const O=n[M];O.pts=Be(O.pts,T),O.dts=Be(O.dts,T),O.dts<n[M>0?M-1:M].dts&&(v=!0)}v&&n.sort(function(M,O){const X=M.dts-O.dts,te=M.pts-O.pts;return X||te}),f=n[0].dts,p=n[n.length-1].dts;const x=p-f,S=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){const M=f-T,O=M>S,X=M<-1;if((O||X)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!X||T>=n[0].pts||Pt)){f=T;const te=n[0].pts-M;if(O)n[0].dts=f,n[0].pts=te;else{let z=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>te&&z);Z++){const ve=n[Z].pts;if(n[Z].dts-=M,n[Z].pts-=M,Z<n.length-1){const ge=n[Z+1].pts,_e=n[Z].pts,He=ge<=_e,De=ge<=ve;z=He==De}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ht(te,!0)}/${Ht(f,!0)}, delta: ${Ht(M,!0)} ms`)}}f=Math.max(0,f);let R=0,A=0,I=f;for(let M=0;M<c;M++){const O=n[M],X=O.units,te=X.length;let z=0;for(let Z=0;Z<te;Z++)z+=X[Z].data.length;A+=z,R+=te,O.length=z,O.dts<I?(O.dts=I,I+=S/4|0||1):I=O.dts,y=Math.min(O.pts,y),E=Math.max(O.pts,E)}p=n[c-1].dts;const b=A+4*R+8;let L;try{L=new Uint8Array(b)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:b,reason:`fail allocating video mdat ${b}`});return}const C=new DataView(L.buffer);C.setUint32(0,b),L.set(_.types.mdat,4);let w=!1,U=Number.POSITIVE_INFINITY,F=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const O=n[M],X=O.units;let te=0;for(let ve=0,ge=X.length;ve<ge;ve++){const _e=X[ve],He=_e.data,De=_e.data.byteLength;C.setUint32(d,De),d+=4,L.set(He,d),d+=De,te+=4+De}let z;if(M<c-1)g=n[M+1].dts-O.dts,z=n[M+1].pts-O.pts;else{const ve=this.config,ge=M>0?O.dts-n[M-1].dts:S;if(z=M>0?O.pts-n[M-1].pts:S,ve.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(ve.maxBufferHole*r),He=(i?y+i*r:this.nextAudioTs+h)-O.pts;He>_e?(g=He-ge,g<0?g=ge:w=!0,this.log(`It is approximately ${He/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ge}else g=ge}const Z=Math.round(O.pts-O.dts);U=Math.min(U,g),N=Math.max(N,g),F=Math.min(F,z),k=Math.max(k,z),o.push(An(O.key,g,te,Z))}if(o.length){if(Pt){if(Pt<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(ui&&k-F<N-U&&S/N<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let O=0,X=o.length;O<X;O++){const te=M+o[O].duration,z=M+o[O].cts;if(O<X-1){const Z=te+o[O+1].cts;o[O].duration=Z-z}else o[O].duration=O?o[O-1].duration:S;o[O].cts=0,M=te}}}g=w||!g?S:g;const $=p+g;this.nextVideoTs=u=$-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const W={data1:_.moof(e.sequenceNumber++,f,ne(e,{samples:o})),data2:L,startPTS:(y-h)/r,endPTS:(E+g-h)/r,startDTS:(f-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return fu;case"ac3":return gu;default:return du}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const v=u.baseTime*n/u.timescale,T=v+t*n;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(T-(E+v))<9e3||Math.abs(Be(p[0].pts,T)-(E+v))<20*h),p.forEach(function(k){k.pts=Be(k.pts,T)}),!s||E<0){const k=p.length;if(p=p.filter($=>$.pts>=0),k!==p.length&&this.warn(`Removed ${p.length-k} of ${k} samples (initPTS ${v} / ${n})`),!p.length)return;r===0?E=0:i&&!f?E=Math.max(0,T-v):E=p[0].pts-v}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let $=0,B=E+v;$<p.length;$++){const K=p[$],W=K.pts,M=W-B,O=Math.abs(1e3*M/n);if(M<=-k*h&&f)$===0&&(this.warn(`Audio frame @ ${(W/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*M/n)} ms.`),this.nextAudioTs=E=W-v,B=W);else if(M>=k*h&&O<uu&&f){let X=Math.round(M/h);for(B=W-X*h;B<0&&X&&h;)X--,B+=h;$===0&&(this.nextAudioTs=E=B-v),this.warn(`Injecting ${X} audio frames @ ${((B-v)/n).toFixed(3)}s due to ${Math.round(1e3*M/n)} ms gap.`);for(let te=0;te<X;te++){let z=lu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),z=K.unit.subarray()),p.splice($,0,{unit:z,pts:B}),B+=h,$++}}K.pts=B,B+=h}}let x=null,S=null,R,A=0,I=p.length;for(;I--;)A+=p[I].unit.byteLength;for(let k=0,$=p.length;k<$;k++){const B=p[k],K=B.unit;let W=B.pts;if(S!==null){const O=g[k-1];O.duration=Math.round((W-S)/c)}else if(s&&e.segmentCodec==="aac"&&(W=E+v),x=W,A>0){A+=y;try{R=new Uint8Array(A)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(R.buffer).setUint32(0,A),R.set(_.types.mdat,4))}else return;R.set(K,y);const M=K.byteLength;y+=M,g.push(An(!0,l,M,0)),S=W}const b=g.length;if(!b)return;const L=g[g.length-1];E=S-v,this.nextAudioTs=E+c*L.duration;const C=d?new Uint8Array(0):_.moof(e.sequenceNumber++,x/c,ne({},e,{samples:g}));e.samples=[];const w=(x-v)/n,U=this.nextAudioTs/n,N={data1:C,data2:R,startPTS:w,endPTS:U,startDTS:w,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,N}}function Be(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function mu(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function oo(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=Be(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Be(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function lo(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Be(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class pu extends Ve{constructor(e,t,s,i){super("passthrough-remuxer",i),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,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=ga(e);if(t)ic(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=In(r,le.AUDIO,this)),n&&(i=In(n,le.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};G(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=nc(d,f,this),y=f.audio?p[f.audio.id]:null,E=f.video?p[f.video.id]:null,v=gs(E,1/0),T=gs(y,1/0),x=gs(E,0,!0),S=gs(y,0,!0);let R=r,A=0;const I=y&&(!E||!l&&T<v||l&&l.trackId===f.audio.id),b=I?y:E;if(b){const B=b.timescale,K=b.start-r*B,W=I?f.audio.id:f.video.id;R=b.start/B,A=I?S-T:x-v,(n||!l)&&(yu(l,R,r,A)||B!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${K/B} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${R-r} (${K}/${B}) trackId: ${W}`),l=null,g.initPTS=K,g.timescale=B,g.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=R,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const L=R-l.baseTime/l.timescale,C=L+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,U=!!f.video;let F="";w&&(F+="audio"),U&&(F+="video");const N=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),k={data1:d,startPTS:L,startDTS:L,endPTS:C,endDTS:C,type:F,hasAudio:w,hasVideo:U,nb:1,dropped:0,encrypted:N};u.audio=w&&!U?k:void 0,u.video=U?k:void 0;const $=E?.sampleCount;if($){const B=E.keyFrameIndex,K=B!==-1;k.nb=$,k.dropped=B===0||this.isVideoContiguous?0:K?B:$,k.independent=K,k.firstKeyFrame=B,K&&E.keyFrameStart&&(k.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${B}/${$} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return u.initSegment=g,u.id3=oo(s,r,l,l),i.samples.length&&(u.text=lo(i,r,l)),u}}function gs(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function yu(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function In(a,e,t){const s=a.codec;return s&&s.length>4?s:e===le.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?ws(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let lt;try{lt=self.performance.now.bind(self.performance)}catch{lt=Date.now}const bs=[{demux:su,remux:pu},{demux:mt,remux:Rs},{demux:Zh,remux:Rs},{demux:eu,remux:Rs}];bs.splice(2,0,{demux:Jh,remux:Rs});class Ln{constructor(e,t,s,i,r,n){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=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=lt();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:v,initSegmentData:T}=c,x=Eu(n,t);if(x&&Ft(x.method)){const I=this.getDecrypter(),b=rr(x.method);if(I.isSync()){let L=I.softwareDecrypt(n,x.key.buffer,x.iv.buffer,b);if(s.part>-1){const w=I.flush();L=w&&w.buffer}if(!L)return r.executeEnd=lt(),di(s);n=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(n,x.key.buffer,x.iv.buffer,b).then(L=>{const C=this.push(L,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const S=this.needsProbing(h,u);if(S){const I=this.configureTransmuxer(n);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=lt(),di(s)}(h||u||f||S)&&this.resetInitSegment(T,p,y,v,t),(h||f||S)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const R=this.transmux(n,x,g,d,s);this.asyncResult=ts(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=lt(),R}flush(e){const t=e.transmuxing;t.executeStart=lt();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=lt();const u=[di(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return ts(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===V.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=lt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=bs.length;u<d;u++){var n;if((n=bs[u].demux)!=null&&n.probe(e,this.logger)){r=bs[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new sr(this.config)),e}}function Eu(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const di=a=>({remuxResult:{},chunkMeta:a});function ts(a){return"then"in a&&a.then instanceof Function}class vu{constructor(e,t,s,i,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=s,this.duration=i,this.defaultInitPts=r||null}}class Tu{constructor(e,t,s,i,r,n){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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Rn=0;class co{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rn++,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 l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=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:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new or,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=$r(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||Ih()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Rh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Lh());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ce(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rn++;const t=this.hls.config,s=$r(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),bh(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,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=n?n.start:r.start,y=r.decryptdata,E=this.frag,v=!(E&&r.cc===E.cc),T=!(E&&l.level===E.level),x=E?l.sn-E.sn:-1,S=this.part?l.part-this.part.index:-1,R=x===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!T&&(x===1||x===0&&(S===1||R&&S<=0)),I=self.performance.now();(T||x||r.stats.parsing.start===0)&&(r.stats.parsing.start=I),n&&(S||!A)&&(n.stats.parsing.start=I);const b=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),L=new Tu(v,A,c,T,p,b);if(!A||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===V.MAIN?"level":"track"}: ${l.level} id: ${l.id} 17 - discontinuity: ${v} 18 - trackSwitch: ${T} 19 - contiguous: ${A} 20 - accurateTimeOffset: ${c} 21 - timeOffset: ${p} 22 - initSegmentChange: ${b}`);const C=new vu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){const C=f.push(e,y,l,L);ts(C)?C.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);ts(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const bn=100;class Su extends ar{constructor(e,t,s){super(e,t,s,"audio-stream-controller",V.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:s,initPTS:i,timescale:r,trackId:n}){if(s===V.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=La(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(bn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=P.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:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,le.AUDIO,V.AUDIO));const h=this.getFwdBufferInfo(l,V.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(u>=d&&!this.switchingTrack&&y<g[g.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,V.MAIN,d)),!E){this.bufferFlushed=!0;return}let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&me(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ee.OK&&(this.mainFragLoading=v=null),v&&me(v))){if(E.start>v.end){const x=this.fragmentTracker.getFragAtPos(y,V.MAIN);x&&x.end>v.end&&(v=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(E.start>v.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Zt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(bn),this.state=P.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Va(r,l),r.alignedSliding||$s(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new co(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,E=y!==-1,v=new ir(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,f,u,"",s,i,h.totalduration,!1,v,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ha,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===V.MAIN&&me(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==V.AUDIO){!this.audioOnly&&s.type===V.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(me(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,ie({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===J.AUDIO_TRACK&&(this.state=P.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,V.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:g,id3:f,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=d;l&&(l.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),c.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(d,c,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=ne({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=ne({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=V.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===Ee.NOT_LOADED||i===Ee.PARTIAL){var r;if(!me(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=P.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&$s(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;Lt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,At)||(Fs(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,ie({},e))}}class gr extends Ve{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,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Gr(s);return new Kr(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){fh(s,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:x}=t;T.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:x,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,g=(i.edge-d)*1e3,f=Ba(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,T=i.lastPartSn,x=i.endSN,S=i.lastPartIndex,R=S!==-1,A=T===x;R?A?(y=x+1,E=v?0:S):(y=T,E=v?S+1:i.maxPartIndex):y=x+1;const I=i.age,b=I+i.ageHeader;let L=Math.min(b-i.partTarget,i.targetduration*1.5);if(L>0){if(b>i.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&b-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{const C=Math.floor(L/i.targetduration);if(y+=C,E!==void 0){const w=Math.round(L%i.targetduration/i.partTarget);E+=w}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${L} skip sn ${C} to part ${E}`)}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),v||!A){i.requestScheduled=n,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Gr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Is.No),new Kr(s,i,r)}checkRetry(e){const t=e.details,s=Ms(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Ie.RetryRequest||!i.resolved&&r===Ie.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=tr(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function ho(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!ss(a[t].attrs,e[t].attrs))return!1;return!0}function ss(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function $i(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class xu extends gr{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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=Je(c,o,At);if(d>-1)r=o[d];else{const g=Je(c,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var n;const d=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===J.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Lt(e,i,At))return i;const r=Je(e,this.tracksInGroup,At);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=Oc(e,t.levels,s,n,At);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=Je(e,s);if(n>-1)return s[n]}}}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 s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,ie({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Lt(e,i,At)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(Lt({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},h,At))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ss(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ss(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Fs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Au{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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 i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.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?"<destroyed>":` 23 - ${this.list("video")} 24 - ${this.list("audio")} 25 - ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const _n=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,uo="HlsJsTrackRemovedError";class Iu extends Error{constructor(e){super(e),this.name=uo}}class Lu extends Ve{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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,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:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ql(Et(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 s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ne(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ne({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Et(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Dn(s),Ru(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) 26 - required tracks: ${ce(s,(c,l)=>c==="initSegment"?void 0:l)}; 27 - transfer tracks: ${ce(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!oa(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,g=h.id;if(d.hasFragments(g)||d.hasParts(g)){const y=j.getBuffered(u);d.detectEvictedFragments(l,y,g,null,!0)}const f=fi(l),p=[l,u];this.sourceBuffers[f]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&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}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Dn(i),i.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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Au(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:g,levelCodec:f,container:p,metadata:y,supplemental:E}=u;let v=i[c];const T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],x=T!=null&&T.buffer?T:v,S=x?.pendingCodec||x?.codec,R=x?.levelCodec;v||(v=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:E,container:p,levelCodec:f,metadata:y,id:d});const A=As(S,R),I=A?.replace(_n,"$1");let b=As(g,f);const L=(h=b)==null?void 0:h.replace(_n,"$1");b&&A&&I!==L&&(c.slice(0,5)==="audio"&&(b=ws(b,this.appendSource)),this.log(`switching codec ${S} to ${b}`),b!==(v.pendingCodec||v.codec)&&(v.pendingCodec=b),v.container=p,this.appendChangeType(c,p,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,V.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&j.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,V.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:g}=o,f=self.performance.now();u.start=f;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);const E=s.audio;let v=!1;r==="audio"&&E?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,x=T?.buffer;if(x&&d!=="initSegment"){const A=c||o,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const L=A.start+A.duration*.05,C=x.buffered,w=this.currentOp("video");!C.length&&!w?this.blockAudio(A):!w&&!j.isBuffered(x,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(A)}else if(r==="video"){const b=A.end;if(I){const L=I.frag.start;(b>L||b<this.lastVideoAppendEnd||j.isBuffered(x,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}const S=(c||o).start,R={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const I=(A=this.tracks[r])==null?void 0:A.buffer;I&&(v?this.updateTimestampOffset(I,S,.1,r,d,g):h!==void 0&&G(h)&&this.updateTimestampOffset(I,h,1e-6,r,d,g)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const I={};this.sourceBuffers.forEach(([b,L])=>{b&&(I[b]=j.getBuffered(L))}),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:o,part:c,chunkMeta:l,parent:o.type,timeRanges:I})},onError:A=>{var I;const b={type:Y.MEDIA_ERROR,parent:o.type,details:D.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},L=(I=this.media)==null?void 0:I.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)b.details=D.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)b.errorAction=Ot(!0);else if(A.name===uo&&this.sourceBufferCount===0)b.errorAction=Ot(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${L||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||L)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===V.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(R,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[le.AUDIOVIDEO]?r.push("audiovideo"):(n[le.AUDIO]&&r.push("audio"),n[le.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,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 s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.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===D.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;G(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(G(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(G(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=j.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=j.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return G(r)?{duration:r}:null;const n=this.media.duration,o=G(s.duration)?s.duration:0;return i>o&&i>n||!G(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(G(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ce(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.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:Y.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ce(o)}`);try{const h=s.addSourceBuffer(l),u=fi(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&zt(s,"video")&&(i=mc(i,s));const r=As(i,e.levelCodec);return r?t.slice(0,5)==="audio"?ws(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=G(i.duration)?i.duration:1/0,l=G(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Iu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.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:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Dn(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Ru(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function fi(a){return a==="audio"?1:0}class mr{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 s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&G(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,mr.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const bu={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ke=bu,_u={HLS:"h"},Du=_u;class tt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof tt?s:new tt(s))),this.value=e,this.params=t}}const Cu="Dict";function Pu(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function ku(a,e,t,s){return new Error(`failed to ${a} "${Pu(e)}" as ${t}`,{cause:s})}function st(a,e,t){return ku("serialize",a,e,t)}class fo{constructor(e){this.description=e}}const Cn="Bare Item",wu="Boolean";function Ou(a){if(typeof a!="boolean")throw st(a,wu);return a?"?1":"?0"}function Fu(a){return btoa(String.fromCharCode(...a))}const Mu="Byte Sequence";function Nu(a){if(ArrayBuffer.isView(a)===!1)throw st(a,Mu);return`:${Fu(a)}:`}const Bu="Integer";function Uu(a){return a<-999999999999999||999999999999999<a}function go(a){if(Uu(a))throw st(a,Bu);return a.toString()}function $u(a){return`@${go(a.getTime()/1e3)}`}function mo(a,e){if(a<0)return-mo(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const Gu="Decimal";function Ku(a){const e=mo(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw st(a,Gu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Vu="String",Hu=/[\x00-\x1f\x7f]+/;function Yu(a){if(Hu.test(a))throw st(a,Vu);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Wu(a){return a.description||a.toString().slice(7,-1)}const qu="Token";function Pn(a){const e=Wu(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw st(e,qu);return e}function Gi(a){switch(typeof a){case"number":if(!G(a))throw st(a,Cn);return Number.isInteger(a)?go(a):Ku(a);case"string":return Yu(a);case"symbol":return Pn(a);case"boolean":return Ou(a);case"object":if(a instanceof Date)return $u(a);if(a instanceof Uint8Array)return Nu(a);if(a instanceof fo)return Pn(a);default:throw st(a,Cn)}}const ju="Key";function Ki(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw st(a,ju);return a}function pr(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${Ki(e)}`:`;${Ki(e)}=${Gi(t)}`).join("")}function po(a){return a instanceof tt?`${Gi(a.value)}${pr(a.params)}`:Gi(a)}function Xu(a){return`(${a.value.map(po).join(" ")})${pr(a.params)}`}function zu(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw st(a,Cu);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof tt||(r=new tt(r));let n=Ki(i);return r.value===!0?n+=pr(r.params):(n+="=",Array.isArray(r.value)?n+=Xu(r):n+=po(r)),n}).join(`,${s}`)}function yo(a,e){return zu(a,e)}const Xe="CMCD-Object",fe="CMCD-Request",St="CMCD-Session",ft="CMCD-Status",Qu={br:Xe,ab:Xe,d:Xe,ot:Xe,tb:Xe,tpb:Xe,lb:Xe,tab:Xe,lab:Xe,url:Xe,pb:fe,bl:fe,tbl:fe,dl:fe,ltc:fe,mtp:fe,nor:fe,nrr:fe,rc:fe,sn:fe,sta:fe,su:fe,ttfb:fe,ttfbb:fe,ttlb:fe,cmsdd:fe,cmsds:fe,smrt:fe,df:fe,cs:fe,ts:fe,cid:St,pr:St,sf:St,sid:St,st:St,v:St,msd:St,bs:ft,bsd:ft,cdn:ft,rtp:ft,bg:ft,pt:ft,ec:ft,e:ft},Zu={REQUEST:fe};function Ju(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function ed(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?Ju(e):{};return s.reduce((r,n)=>{var o;const c=Qu[n]||i[n]||Zu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function td(a){return["ot","sf","st","e","sta"].includes(a)}function sd(a){return typeof a=="number"?G(a):a!=null&&a!==""&&a!==!1}const Eo="event";function id(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const _s=a=>Math.round(a),Vi=(a,e)=>Array.isArray(a)?a.map(t=>Vi(t,e)):a instanceof tt&&typeof a.value=="string"?new tt(Vi(a.value,e),a.params):(e.baseUrl&&(a=id(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),ms=a=>_s(a/100)*100,rd=(a,e)=>{let t=a;return e.version>=2&&(a instanceof tt&&typeof a.value=="string"?t=new tt([a]):typeof a=="string"&&(t=[a])),Vi(t,e)},nd={br:_s,d:_s,bl:ms,dl:ms,mtp:ms,nor:rd,rtp:ms,tb:_s},vo="request",To="response",yr=["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"],ad=["e"],od=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function qs(a){return od.test(a)}function ld(a){return yr.includes(a)||ad.includes(a)||qs(a)}const So=["d","dl","nor","ot","rtp","su"];function cd(a){return yr.includes(a)||So.includes(a)||qs(a)}const hd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ud(a){return yr.includes(a)||So.includes(a)||hd.includes(a)||qs(a)}const dd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function fd(a){return dd.includes(a)||qs(a)}const gd={[To]:ud,[Eo]:ld,[vo]:cd};function xo(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||vo,r=s===1?fd:gd[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===To||i===Eo;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ne({},nd,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const g=l[u];if(typeof g=="function"&&(d=g(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!G(d)&&(d=Date.now()),sd(d)&&(td(u)&&typeof d=="string"&&(d=new fo(d)),t[u]=d))}),t}function md(a,e={}){const t={};if(!a)return t;const s=xo(a,e),i=ed(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=yo(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function pd(a,e,t){return ne(a,md(e,t))}const yd="CMCD";function Ed(a,e={}){return a?yo(xo(a,e),{whitespace:!1}):""}function vd(a,e={}){if(!a)return"";const t=Ed(a,e);return encodeURIComponent(t)}function Td(a,e={}){if(!a)return"";const t=vd(a,e);return`${yd}=${t}`}const kn=/CMCD=[^&#]+/;function Sd(a,e,t){const s=Td(e,t);if(!s)return a;if(kn.test(a))return a.replace(kn,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class xd{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=i=>{try{this.apply(i,{ot:ke.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===ke.VIDEO||c===ke.AUDIO||c==ke.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.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 s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Du.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ne(t,this.createData());const s=t.ot===ke.INIT||t.ot===ke.VIDEO||t.ot===ke.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),pd(e.headers,t,r)):e.url=Sd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ke.TIMED_TEXT;if(e.sn==="initSegment")return ke.INIT;if(t==="audio")return ke.AUDIO;if(t==="main")return this.hls.audioTracks.length?ke.VIDEO:ke.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ke.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===ke.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:j.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const Ad=3e5;class Id extends Ve{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===Ie.SendAlternateToPenaltyBox&&s.flags===Ne.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===D.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ce(r)} penalized: ${ce(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Ad&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ga(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===J.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===J.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new ue(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=Ao(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Zt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${n}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${n}`);return p});t.push(...l),wn(this.audioTracks,s,c,n),wn(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const v={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,v),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wn(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ne({},n);return o.details=void 0,o.attrs=new ue(o.attrs),o.url=o.attrs.URI=Ao(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Ao(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Mt extends Ve{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=Mt.CDMCleanupPromise?[Mt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Wt(this.config));const o=n.map(ni).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=Ls(n);if(s!=="sinf"||o!==de.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=pe(new Uint8Array(i)),f=nr(JSON.parse(g).sinf),p=pa(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}const l=Le(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let g=0;g<u.length;g++){const f=u[g],p=f.decryptdata;if(!p.keyId)continue;const y=Le(p.keyId);if(Bs(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},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:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===de.WIDEVINE&&s)return s}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,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Me?o(u):o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return wa===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=rh(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ce(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Le(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=ps(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Le(e.decryptdata.keyId||[])} 28 - } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ni(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=ni(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Wt(this.config),s=e.map(Ls).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Ld(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=ps(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=On(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Me){const c=ie({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Me(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Me){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Le(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ps(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ls(e.keyFormat),r=i?[i]:Wt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Wt(this.config)),e.length===0)throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const f=n.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=ps(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new or,h=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(v=>{l.eventNames().length?l.emit("error",v):this.handleError(v)}):y==="license-release"?e.keySystem===de.FAIRPLAY&&this.updateKeySession(e,Fi("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${y}"`)},u=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=On(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(x=>y[x]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ce(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let v=y[o];if(v)u(v,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const S=this.getKeyStatus(e.decryptdata);if(S&&S!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${S} from other session.`),u(S,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",u(v,e)},1e3)),this.log(`No status for keyId ${o} (${ce(y)}).`)}};Ce(e.mediaKeysSession,"message",h),Ce(e.mediaKeysSession,"keystatuseschange",d);const g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===de.PLAYREADY&&r.length===16){const o=Le(r);t[o]=s,Pa(r)}const n=Le(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{n(d.data)},onError:(d,g,f,p)=>{o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ie({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Fi(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==de.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ce(s,"encrypted",this.onMediaEncrypted),Ce(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Oe(e,"encrypted",this.onMediaEncrypted),Oe(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 s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,yt.clearKeyUriToKeyIdMap();const r=i.length;Mt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).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 s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Le(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(ah(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Mt.CDMCleanupPromise=void 0;function ps(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return Le(a.keyId)}function Ld(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Me 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 On(a,e){const t=a==="output-restricted",s=t?D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Me({type:Y.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class Rd{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 s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,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 Io(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Lo(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){re.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){re.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function wt(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function Hi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=_d(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function bd(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function _d(a,e,t){const s=[],i=bd(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Ds(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Dd extends gr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=Ds(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-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 s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;Ds(s.textTracks).forEach(n=>{wt(n)})}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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Je(o,n);if(h>-1)r=n[h];else{const u=Je(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||Lt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(ss(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(ss(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if($i(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===J.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Lt(e,s))return s;const i=Je(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Je(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 s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Ds(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>$i(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function Cd(){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,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Xt(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Nt=.025;let Ks=(function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a})({});function Pd(a,e,t){return`${a.identifier}-${t+1}-${Xt(e)}`}class kd{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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 gi(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,s=gi(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=G(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 gi(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)<Nt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Ks.Range:Ks.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return wd(this)}}function gi(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Nt)?e.start:e.start+e.duration}function Ro(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function mi(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function wd(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function kt(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Od{constructor(e,t,s,i){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=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,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=Ro(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 s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=j.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=j.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 s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${kt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fn=.033;class Fd extends Ve{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,g=h.cue.pre,f=h.cue.post;if(u&&!g)return-1;if(g&&!u||d&&!f)return 1;if(f&&!d)return-1;if(!u&&!g&&!d&&!f){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new kd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,g=h.cue.post,f=e[u-1]||null,p=h.appendInPlace,y=g?r:h.startOffset,E=h.duration,v=h.timelineOccupancy===Ks.Range?E:0,T=h.resumptionOffset,x=f?.startTime===y,S=y+h.cumulativeDuration;let R=p?S+E:y+T;if(d||!g&&y<=0){const I=l;l+=v,h.timelineStart=S;const b=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:b,end:n},integrated:{start:I,end:l}})}else if(y<=r){if(!x){const L=y-c;if(L>Fn){const C=c,w=l;l+=L;const U=n;n+=L;const F={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+L,playout:{start:U,end:n},integrated:{start:w,end:l}};s.push(F)}else L>0&&f&&(f.cumulativeDuration+=L,s[s.length-1].end=y)}g&&(R=S),h.timelineStart=S;const I=l;l+=v;const b=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:b,end:n},integrated:{start:I,end:l}})}else return;const A=h.resumeTime;g||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const g=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:g,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Rt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Fn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=G(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Nt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=Rt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Nt+h||Math.abs(l.end-s)<Nt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ye(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class Md{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ro(s,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){const v=this.assignAssetListError(e,D.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,v);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,g,f,p)=>{const y=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,D.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:Y.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Mn(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function ys(a,e){return`[${a}] Advancing timeline position to ${e}`}class Nd extends Ve{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} 29 - Schedule: ${c.map(p=>Ye(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,g=null;n&&(d=this.updateItem(n,this.timelinePos),this.itemsMatch(n,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(v){Math.abs(E)>Nt&&this.warn(`${v} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(d,n),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Md(e),this.schedule=new Fd(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){Oe(e,"play",this.onPlay),Oe(e,"pause",this.onPause),Oe(e,"seeking",this.onSeeking),Oe(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ce(s,"seeking",this.onSeeking),Ce(s,"timeupdate",this.onTimeupdate),Ce(s,"play",this.onPlay),Ce(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),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,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,g,f,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Ks.Point){const v=s(g);v?.interstitial===E&&(y+=v.assetItem.startOffset+v[p])}}else{const v=f==="bufferedPos"?n():e[f];y+=v-u.start}return y}return 0},r=(u,d)=>{var g;if(u!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(u),y=(f=e.schedule.items)==null?void 0:f[p];if(y){const E=y[d].start-y.start;return u+E}}return u},n=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[u])||0},c=(u,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),v=(f=e.schedule.items)==null?void 0:f[E],T=e.getBufferingPlayer(),x=T?.interstitial,S=x?.appendInPlace,R=y&&e.itemsMatch(y,v);if(y&&(S||R)){const A=s(e.playingAsset),I=A?.media||e.primaryMedia;if(I){const b=d==="primary"?I.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),L=u-b,C=(S?b:I.currentTime)+L;if(C>=0&&(!A||S||C<=A.duration)){I.currentTime=C;return}}}if(v){let A=u;if(d!=="primary"){const b=v[d].start,L=u-b;A=v.start+L}const I=!e.isInterstitial(v);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(I||v.event.appendInPlace)){const b=e.media||(S?T?.media:null);b&&(b.currentTime=A)}else if(y){const b=e.findItemIndex(y);if(E>b){const C=e.schedule.findJumpRestrictedIndex(b+1,E);if(C>b){e.setSchedulePosition(C);return}}let L=0;if(I)e.timelinePos=A,e.checkBuffer();else{const C=v.event.assetList,w=u-(v[d]||v).start;for(let U=C.length;U--;){const F=C[U];if(F.duration&&w>=F.startOffset&&w<F.startOffset+F.duration){L=U;break}}}e.setSchedulePosition(E,L)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var g;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),g=e.effectivePlayingItem;g&&g===d&&c(u+g.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return n()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(u);if(d.appendInPlace){const f=u.playout.start+u.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!G(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ce(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),h=`${f}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ce(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(d===r&&g){const f=o&&e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}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 s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(ys("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=mi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=mi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(ys("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ye(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,u=this.playingAsset,d=u?.identifier,g=d?this.getAssetPlayer(d):null;if(g&&d&&(!this.eventItemsMatch(n,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const f=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${h.assetList.length} ${kt(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:f,event:h,schedule:i.slice(0),scheduleIndex:e,player:g}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(d,r),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ye(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const p=this.findItemIndex(r);this.advanceSchedule(p,f,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=n.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const f=mi(h,s-1);if(h.isAssetPastPlayoutLimit(f)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=f}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ye(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=h.assetList[s];if(!g){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=h.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${h}`),d=this.createAssetPlayer(h,g,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Mn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Mn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.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,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ye(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(ys("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ye(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:j.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(ys("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.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 s=this.hls.levels[t.level];if(!s.details)return;const i=ie(ie({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ie(ie({},this.altSelection),{},{audio:s});return}const r=ie(ie({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ie(ie({},this.altSelection),{},{subtitles:s});return}const r=ie(ie({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=j.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ye(e)} (was ${Ye(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=j.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const g=r.event;if(u-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ye(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:Pd(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ne({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const x=this.timelinePos-t.timelineStart;if(x>1){const S=t.duration;S&&x<S&&(h=x)}}const u=t.identifier,d=ie(ie({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=ne({},g,{contentId:Xt(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const f=new Od(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0;const y=x=>{if(x.live){var S;const I=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},L=((S=this.schedule)==null?void 0:S.findEventIndex(e.identifier))||-1;this.handleAssetItemError(b,e,L,s,I.message);return}const R=x.edge-x.fragmentStart,A=t.duration;(p||A===null||R>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${R}`),t.duration=R,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(x,{details:S})=>y(S)),f.on(m.LEVEL_PTS_UPDATED,(x,{details:S})=>y(S)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(x,S)=>{const R=this.getAssetPlayer(u);if(R&&S.tracks){R.off(m.BUFFER_CODECS,E),R.tracks=S.tracks;const A=this.primaryMedia;this.bufferingAsset===R.assetItem&&A&&!R.media&&this.bufferAssetPlayer(R,A)}};f.on(m.BUFFER_CODECS,E);const v=()=>{var x;const S=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const R=this.schedule.findEventIndex(e.identifier),A=(x=this.schedule.items)==null?void 0:x[R];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};f.on(m.BUFFERED_TO_END,v);const T=x=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,x)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(x,S)=>{if(!this.schedule)return;const R=this.getAssetPlayer(u);if(S.details===D.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${S.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const S=new Error(`Asset player destroyed unexpectedly ${u}`),R={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),s,S.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${kt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ye(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${kt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const u=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!oa(u,e.tracks)){const d=new Error(`Asset ${kt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),g={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===D.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&kt(n)} ${e.error}`),!this.schedule)return;const o=n?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=ne({},e,{fatal:!1,errorAction:Ot(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Ye(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===n;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(d){var f;const p=this.schedule.findEventIndex(n),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.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(y)}this.setSchedulePosition(p)}else if(g?.identifier===n){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case D.ASSET_LIST_PARSING_ERROR:case D.ASSET_LIST_LOAD_ERROR:case D.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case D.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Nn=500;class Bd extends ar{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",V.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=P.IDLE,this.setInterval(Nn),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:s,success:i}=t;if(this.fragContextChanged(s)||(me(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,V.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===V.SUBTITLE&&(t.details===D.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ho(this.levels,t)){this.levels=t.map(s=>new Zt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Zt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Nn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)n.hasProgramDateTime&&u.hasProgramDateTime?($s(n,u),l=n.fragmentStart):d&&(l=d.start,Ni(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,Ni(n,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(Rt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Ft(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,rr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=j.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const v=i.maxFragLookUpTolerance,T=o>g-v?0:v;f=Rt(p,u,Math.max(u[0].start,o),T),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,E=u[y-1];if(E&&E.cc===f.cc&&this.fragmentTracker.getState(E)===Ee.NOT_LOADED&&(f=E),this.fragmentTracker.getState(f)===Ee.NOT_LOADED){const v=this.mapToInitFragWhenRequired(f);v&&this.loadFragment(v,s,o)}}}loadFragment(e,t,s){me(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ud(this.tracksBuffered[this.currentTrackId]||[])}}class Ud{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const $d={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},bo=a=>String.fromCharCode($d[a]||a),We=15,nt=100,Gd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Kd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Yd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Wd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;re.log(`${this.time} [${e}] ${s}`)}}}const xt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class _o{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class qd{constructor(){this.uchar=" ",this.penState=new _o}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class jd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new _o,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<nt;t++)this.chars.push(new qd);this.logger=e}equals(e){for(let t=0;t<nt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<nt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<nt;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>nt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=nt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=bo(e);if(this.pos>=nt){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<nt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<nt;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class pi{constructor(e){this.rows=[],this.currRow=We-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<We;t++)this.rows.push(new jd(e));this.logger=e}reset(){for(let e=0;e<We;e++)this.rows[e].clear();this.currRow=We-1}equals(e){let t=!0;for(let s=0;s<We;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<We;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<We;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ce(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<We;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ce(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 s="",i=-1;for(let r=0;r<We;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(` 30 - `)),s}getTextAndFormat(){return this.rows}}class Bn{constructor(e,t,s){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 pi(s),this.nonDisplayedMemory=new pi(s),this.lastOutputScreen=new pi(s),this.currRollUpRow=this.displayedMemory.rows[We-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[We-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ce(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 Un{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=zd(),this.logger=void 0;const i=this.logger=new Wd;this.channels=[null,new Bn(e,t,i),new Bn(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+xt([t[s],t[s+1]])+"] -> ("+xt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Xd(i,r,c)){Es(null,null,c),this.logger.log(3,()=>"Repeated command ("+xt([i,r])+") is dropped");continue}Es(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Es(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+xt([i,r])+" orig: "+xt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+xt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?Gd[e]:Vd[e]:s=n===1?Kd[e]:Hd[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+bo(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+xt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Yd[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Es(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Es(a,e,t){t.a=a,t.b=e}function Xd(a,e,t){return t.a===a&&t.b===e}function zd(){return{a:null,b:null}}var Er=(function(){if(Us!=null&&Us.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function n(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",g=!1,f=o,p=c,y=l,E=null,v="",T=!0,x="auto",S="start",R=50,A="middle",I=50,b="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return g},set:function(L){g=!!L}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");f=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(L){E=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return v},set:function(L){const C=s(L);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");v=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return x},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");x=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return S},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");S=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return R},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");R=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return b},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");b=C,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n})();class Qd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Do(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.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 Zd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Co(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const Yi=new Er(0,0,""),vs=Yi.align==="middle"?"middle":"center";function Jd(a,e,t){const s=a;function i(){const o=Do(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new Zd;Co(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(d,f[0]),l.percent(d,f[0])&&l.set("snapToLines",!1),l.alt(d,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",vs,"end"]);break;case"position":f=g.split(","),l.percent(d,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",vs,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,g);break;case"align":l.alt(d,g,["start",vs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Yi.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",vs);let u=l.get("position","auto");u==="auto"&&Yi.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function Po(a){return a.replace(/<br(?: \/)?>/gi,` 31 - `)}class ef{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Qd,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 s(){let r=t.buffer,n=0;for(r=Po(r);n<r.length&&r[n]!=="\r"&&r[n]!==` 32 - `;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===` 33 - `&&++n,t.buffer=r.slice(n),o}function i(r){Co(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Er(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Jd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!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+=` 34 - `),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+=` 35 - 36 - `,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 tf=/\r\n|\n\r|\n|\r/g,yi=function(e,t,s=0){return e.slice(s,s+t.length)===t},sf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(s)||!G(i)||!G(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function vr(a,e,t){return Xt(a.toString())+Xt(e.toString())+Xt(t)}const rf=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function nf(a,e,t,s,i,r,n){const o=new ef,c=$e(new Uint8Array(a)).trim().replace(tf,` 37 - `).split(` 38 - `),l=[],h=e?hu(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,p=!0;o.oncue=function(y){const E=t[s];let v=t.ccOffset;const T=(d-h)/9e4;if(E!=null&&E.new&&(g!==void 0?v=t.ccOffset=E.start:rf(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}v=T-t.presentationOffset}const x=y.endTime-y.startTime,S=Be((y.startTime+v-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(S,0),y.endTime=Math.max(S+x,0);const R=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(R)),y.id||(y.id=vr(y.startTime,y.endTime,R)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){n(f);return}r(l)},c.forEach(y=>{if(p)if(yi(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{yi(E,"LOCAL:")?u=E.slice(6):yi(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=sf(u)/1e3}catch(E){f=E}return}else y===""&&(p=!1);o.parse(y+` 39 - `)}),o.flush()}const Ei="stpp.ttml.im1t",ko=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,af={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(a,e,t,s){const i=Q(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>$e(o)),n=cu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(of(o,n)))}catch(o){s(o)}}function of(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Gn(vi(i,"styling","style")),l=Gn(vi(i,"layout","region")),h=vi(i,"body","[begin]");return[].map.call(h,u=>{const d=Oo(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=Si(u.getAttribute("begin"),n),f=Si(u.getAttribute("dur"),n);let p=Si(u.getAttribute("end"),n);if(g===null)throw Kn(u);if(p===null){if(f===null)throw Kn(u);p=g+f}const y=new Er(g-e,p-e,d);y.id=vr(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],v=c[u.getAttribute("style")],T=lf(E,v,c),{textAlign:x}=T;if(x){const S=af[x];S&&(y.lineAlign=S),y.align=x}return ne(y,T),y}).filter(u=>u!==null)}function vi(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gn(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Oo(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+` 40 - `:(r=s.childNodes)!=null&&r.length?Oo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function lf(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=Ti(e,s,c)||Ti(a,s,c)||Ti(i,s,c);return l&&(o[c]=l),o},{})}function Ti(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Kn(a){return new Error(`Could not parse ttml timestamp ${a}`)}function Si(a,e){if(!a)return null;let t=Do(a);return t===null&&(ko.test(a)?t=cf(a,e):wo.test(a)&&(t=hf(a,e))),t}function cf(a,e){const t=ko.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function hf(a,e){const t=wo.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class Ts{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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class uf{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=Hn(),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 Ts(this,"textTrack1"),t=new Ts(this,"textTrack2"),s=new Ts(this,"textTrack3"),i=new Ts(this,"textTrack4");this.cea608Parser1=new Un(1,e,t),this.cea608Parser2=new Un(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=df(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===V.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.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:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Vn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,wt(s[e]),Io(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{wt(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hn(),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 s=0;s<t.length;s++)wt(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ei);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ho(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?Ds(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Vn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)wt(h);else{const u=Fo(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.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 n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===V.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===V.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ei?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;$n(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?Ke(s.initSegment.data,new Uint8Array(i)).buffer:i;nf(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||$n(t,this.initPTS[e.cc],()=>{s.textCodec=Ei,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>Lo(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===V.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===V.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Hi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Hi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function Fo(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Vn(a,e){return!!a&&a.kind===Fo(e)&&$i(e,a)}function df(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Hn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const ff=/\s/,gf={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)ff.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=Po(l.trim()),f=vr(e,t,g);a!=null&&(u=a.cues)!=null&&u.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=d+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>Lo(a,d))),i}};function mf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const pf=/(\d+)-(\d+)\/(\d+)/;class Yn{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||Tf,this.controller=new self.AbortController,this.stats=new Qi}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,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=yf(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&G(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(ts(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new Sf(y||"fetch, bad network response",p,u)}i.loading.first=g,i.total=vf(u.headers)||i.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&G(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,f):n?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:u,code:f.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!G(t.highWaterMark)&&E(i,e,u,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=u&&u.code||0,f=u?u.message:null;(d=this.callbacks)==null||d.onError({code:g,text:f},e,u?u.details:null,i)})}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,s,i=0,r){const n=new Ha,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function yf(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ne({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Ef(a){const e=pf.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function vf(a){const e=a.get("Content-Range");if(e){const s=Ef(e);if(G(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function Tf(a,e){return new self.Request(a.url,e)}class Sf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xf=/^age:\s*[\d.]+\s*$/im;class Mo{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 Qi,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,s){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=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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),s.timeout=r&&G(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=h??t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(n=this.callbacks)==null?void 0:n.onProgress;y&&y(s,e,f,t);const E={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,g={url:e.url,data:void 0,code:l};if(Ns(u,d,!1,g))this.retry(u);else{var c;re.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ns(e,t,!0))this.retry(e);else{var s;re.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=tr(e,s.retry),s.retry++,re.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.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&&xf.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 Af={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},If=ie(ie({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:Mo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fc,bufferController:Lu,capLevelController:mr,errorController:$c,fpsController:Rd,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:wa,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:Af},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},Lf()),{},{subtitleStreamController:Bd,subtitleTrackController:Dd,timelineController:uf,audioStreamController:Su,audioTrackController:xu,emeController:Mt,cmcdController:xd,contentSteeringController:Id,interstitialsController:Nd});function Lf(){return{cueHandler:gf,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 Rf(a,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 s=Wi(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${n}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const g=s[o].default;switch(e[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ce(e[o])}`)}),ie(ie({},s),e)}function Wi(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Wi):Object.keys(a).reduce((e,t)=>(e[t]=Wi(a[t]),e),{}):a}function bf(a,e){const t=a.loader;t!==Yn&&t!==Mo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):mf()&&(a.loader=Yn,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Cs=2,_f=.1,Df=.05,Cf=100;class Pf extends _a{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.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(Cf),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ce(s,"playing",this.onMediaPlaying),Ce(s,"waiting",this.onMediaWaiting),Ce(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Oe(s,"playing",this.onMediaPlaying),Oe(s,"waiting",this.onMediaWaiting),Oe(s,"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 s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!j.getBuffered(n).length){this.nudgeRetry=0;return}const u=j.bufferInfo(n,e,0),d=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const R=Wn(this.hls.inFlightFragments,e),A=u.len>Cs,I=!d||R||d-e>Cs&&!g.getPartialFragment(e);if(A||I)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,b=!!(f!=null&&f.live)?f.targetduration*2:Cs,L=Ss(e,g);if(A>0&&(A<=b||L)){n.paused||this._trySkipBufferHole(L);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let v=this.stalled;if(v===null)if(E>0&&y-E<p)v=this.stalled=E;else{this.stalled=y;return}const T=y-v;if(!o&&(T>=p||E)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const S=j.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=j.bufferedInfo(j.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=j.timeRangesToArray(i),o=j.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=j.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Ss(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=j.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Ss(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,V.MAIN),n=s.getFragAtPos(i,V.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ce(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=j.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-n;if(d>0&&(h||u)){if(d>r.maxBufferHole){let f=!1;if(n===0){const p=s.getAppendedFrag(0,V.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Wn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const v=Ss(E,s);if(v)E+=v.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(c+Df,n+_f);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${g}`),p={type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wn(a,e){const t=qn(a.main);if(t&&t.start<=e)return t;const s=qn(a.audio);return s&&s.start<=e?s:null}function qn(a){if(!a)return null;switch(a.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return a.frag}function Ss(a,e){return e.getAppendedFrag(a,V.MAIN)||e.getPartialFragment(a)}const kf=.25;function qi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function xi(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ce(i?ie({type:i},s):s))}return r}const xs=(()=>{const a=qi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class wf{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 s;this.media=t.media,((s=t.overrides)==null?void 0:s.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&&wt(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;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Io(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=qi();if(n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===Ue.emsg&&!s||!i)continue;const l=Qa(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>xs&&(u=xs),u-h<=0&&(u=h+kf);for(let g=0;g<l.length;g++){const f=l[g];if(!Za(f)){this.updateId3CueEnds(h,c);const p=xi(n,h,u,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===xs&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===Ue.audioId3&&c:i==="video"?l=h=>h.type===Ue.emsg&&o:l=h=>h.type===Ue.audioId3&&c||h.type===Ue.emsg&&o,Hi(r,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=qi();if(s&&i&&!n){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=xi(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var g;const E=p[y],v=(g=u[E])==null?void 0:g.cues;delete u[E],v&&Object.keys(v).forEach(T=>{const x=v[T];if(x){x.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(x)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(h.length===0||!G(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],v=E.startTime,T=u[y],x=T?.cues||{};let S=T?.durationKnown||!1,R=xs;const{duration:A,endDate:I}=E;if(I&&A!==null)R=v+A,S=!0;else if(E.endOnNext&&!S){const L=h.reduce((C,w)=>{if(w!==E.id){const U=l[w];if(U.class===E.class&&U.startDate>E.startDate&&(!C||E.startDate<C.startDate))return U}return C},null);L&&(R=L.startTime,S=!0)}const b=Object.keys(E.attr);for(let L=0;L<b.length;L++){const C=b[L];if(!Jc(C))continue;const w=x[C];if(w)S&&!(T!=null&&T.durationKnown)?w.endTime=R:Math.abs(w.startTime-v)>.01&&(w.startTime=v,w.endTime=R);else if(o){let U=E.attr[C];eh(C)&&(U=la(U));const N=xi(o,v,R,{key:C,data:U},Ue.dateRange);N&&(N.id=y,this.id3Track.addCue(N),x[C]=N,n&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&N.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:x,dateRange:E,durationKnown:S}}}}}class Of{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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,g)}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:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}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 s=e.buffered.length;return(s?e.buffered.end(s-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 s;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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 Ff extends gr{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 s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:g}=h;d&&(h.audioCodec=d=ws(d,s)||void 0),g&&(g=h.videoCodec=pc(g));const{width:f,height:p,unknownCodecs:y}=h,E=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!d),E||d&&!this.isAudioSupported(d)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":T,"HDCP-LEVEL":x,"PATHWAY-ID":S,RESOLUTION:R,"VIDEO-RANGE":A}=u,b=`${`${S||"."}-`}${h.bitrate}-${R}-${T}-${v}-${A}-${x}`;if(r[b])if(r[b].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const L=n[b]+=1;h.attrs["PATHWAY-ID"]=new Array(L+1).join(".");const C=this.createLevel(h);r[b]=C,i.push(C)}else r[b].addGroupId("audio",u.AUDIO),r[b].addGroupId("text",u.SUBTITLES);else{const L=this.createLevel(h);r[b]=L,n[b]=1,i.push(L)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Zt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Ta(i,[])}return t}isAudioSupported(e){return zt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return zt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:v,videoRange:T,width:x,height:S})=>(!!v||!!(x&&S))&&Rc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ce(t.levels.map(S=>S.attrs.CODECS).filter((S,R,A)=>A.indexOf(S)===R))}`,this.warn(T),v+=` (${T})`);const x=new Error(v);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),jn(o)),t.subtitles&&(c=t.subtitles,jn(c));const u=l.slice(0);l.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return Os.indexOf(v.videoRange)-Os.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){const x=Br(v.videoCodec),S=Br(T.videoCodec);if(x!==S)return S-x}if(v.uri===T.uri&&v.codecSet!==T.codecSet){const x=ks(v.codecSet),S=ks(T.codecSet);if(x!==S)return S-x}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let v=0;v<u.length;v++)if(u[v].pathwayId===l[0].pathwayId){d=u[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===d){var g;this._firstLevel=v;const T=d.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const S=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);S>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}const f=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!f&&o.some(v=>!!v.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i?.details,l);this.loadPlaylist(h)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===J.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===V.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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 s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ga(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}}function jn(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function No(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bo(){if(!Et())return!1;const e=No();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Mf(){if(!Bo())return!1;const a=Et();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Qt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Qt(e,"audio"))))}function Nf(){var a;const e=No();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const Bf=100;class Uf extends ar{constructor(e,t,s){super(e,t,s,"stream-controller",V.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 i=this.media,r=i?i.currentTime:null;if(r===null||!G(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,V.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.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:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Bf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.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 l=n.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&me(g)&&this.fragmentTracker.getState(g)!==Ee.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,E=l.fragments[y-1];E&&g.cc===E.cc&&(g=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,E=(y===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,V.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,V.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ee.NOT_LOADED||i===Ee.PARTIAL?me(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,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,V.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 s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Ce(s,"playing",this.onMediaPlaying),Ce(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Oe(s,"playing",this.onMediaPlaying),Oe(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=j.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:g}=j.bufferedInfo(u.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new co(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new ir(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,p),E=this.initPTS[s.cc];g.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Fs(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Fs(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===V.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),me(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&j.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===J.LEVEL&&(this.state=P.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case D.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 D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==le.AUDIO||!this.altAudio){const s=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,V.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 s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=j.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:h,text:u,id3:d,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){const y=g.tracks;if(y){const x=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,x,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:t,tracks:y})}const E=g.initPTS,v=g.timescale,T=this.initPTS[o.cc];if(G(E)&&(!T||T.baseTime!==E||T.timescale!==v)){const x=g.trackId;this.initPTS[o.cc]={baseTime:E,timescale:v,trackId:x},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:v,trackId:x})}}if(h&&f){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],E=o.sn===f.startSN,v=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:x,startDTS:S,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:x,startDTS:S,endDTS:R};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&I<b-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,x,o.start,R,!0)}else E&&T-(f.appliedTimelineOffset||0)>Cs&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,x,S,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||v)}else if(E||v)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=p;c&&(c.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),o.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(p,o,c,r)}if(f&&d!=null&&d.samples.length){const y={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&u){const y={id:t,frag:o,details:f,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${me(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=As(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=V.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=V.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.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(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,V.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(j.isBuffered(e,s)?t=this.getAppendedFrag(s):j.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.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 G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Rt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}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 $f extends Ve{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.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=D.KEY_LOAD_ERROR,s,i,r){return new ot({type:Y.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!me(e)||!me(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=Ls(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Wt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}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 s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=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,D.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=Ai(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Le(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={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,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=rc(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Le(o)}`),yt.setKeyIdForUri(e.decryptdata.uri,o)):(o=yt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Le(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!me(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const{frag:y,keyInfo:E}=f,v=Ai(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(y,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,n({frag:y,keyInfo:E})},onError:(d,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,ie({url:c.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ai(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Ai(a){if(a.keyFormat!==Re.FAIRPLAY){const e=a.keyId;if(e)return Le(e)}return a.uri}function Xn(a){const{type:e}=a;switch(e){case J.AUDIO_TRACK:return V.AUDIO;case J.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Ii(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Gf{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,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:J.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:J.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:J.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:J.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[J.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[J.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===J.MANIFEST?r=s.manifestLoadPolicy.default:r=ne({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===J.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===J.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===J.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ne({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=l.data;h.parsing.start=performance.now(),et.isMediaPlaylist(f)||u.type!==J.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,g):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Ii(e,s),c=et.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f}=c;this.variableList=f,h.forEach(v=>{const{unknownCodecs:T}=v;if(T){const{preferManagedMediaSource:x}=this.hls.config;let{audioCodec:S,videoCodec:R}=v;for(let A=T.length;A--;){const I=T[A];zt(I,"audio",x)?(v.audioCodec=S=S?`${S},${I}`:I,Bt.audio[S.substring(0,4)]=2,T.splice(A,1)):zt(I,"video",x)&&(v.videoCodec=R=R?`${R},${I}`:I,Bt.video[R.substring(0,4)]=2,T.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=et.parseMasterPlaylistMedia(n,o,c);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ue({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,h=Ii(e,s),u=G(c)?c:G(o)?o:0,d=Xn(s),g=et.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===J.MANIFEST){const f={attrs:new ue({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=t.loading.start+Ba(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===J.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===J.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===J.AUDIO_TRACK||e.type===J.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=D.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case J.MANIFEST:c=s?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,l=!0;break;case J.LEVEL:c=s?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,l=!1;break;case J.AUDIO_TRACK:c=s?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case J.SUBTITLE_TRACK:c=s?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:Y.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=t?.url||e.url;u.response=ie({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:g}=i,f=Ii(t,i),p=Xn(i);let y=typeof i.level=="number"&&p===V.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case J.MANIFEST:case J.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const v=o.levels.indexOf(h);v>-1&&(y=v)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:g,withoutMultiVariant:c===J.MANIFEST});break;case J.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break;case J.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break}}}class be{static get version(){return Jt}static isMSESupported(){return Bo()}static isSupported(){return Mf()}static getMediaSource(){return Et()}static get Events(){return m}static get MetadataSchema(){return Ue}static get ErrorTypes(){return Y}static get ErrorDetails(){return D}static get DefaultConfig(){return be.defaultConfig?be.defaultConfig:If}static set DefaultConfig(e){be.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 or,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=Wl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Rf(be.DefaultConfig,e,t);this.userConfig=e,s.progressive&&bf(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new Gc(this),d=s.interstitialsController,g=d?this.interstitialsController=new d(this,be):null,f=this.bufferController=new r(this,u),p=this.capLevelController=new n(this),y=new c(this),E=new Gf(this),v=s.contentSteeringController,T=v?new v(this):null,x=this.levelController=new Ff(this,T),S=new wf(this),R=new $f(this.config,this.logger),A=this.streamController=new Uf(this,u,R),I=this.gapController=new Pf(this,u);p.setStreamController(A),y.setStreamController(A);const b=[E,x,A];g&&b.splice(1,0,g),T&&b.splice(1,0,T),this.networkControllers=b;const L=[h,f,I,p,y,S,u];this.audioTrackController=this.createController(s.audioTrackController,b);const C=s.audioStreamController;C&&b.push(this.audioStreamController=new C(this,u,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const w=s.subtitleStreamController;w&&b.push(this.subtititleStreamController=new w(this,u,R)),this.createController(s.timelineController,L),R.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(Of,L),this.coreComponents=L,b.push(l);const U=l.onErrorOut;typeof U=="function"&&this.on(m.ERROR,U,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),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:Y.OTHER_ERROR,details:D.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,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}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,s=this._url,i=this._url=zi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||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?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.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=Cd()),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){Lc(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}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 s=Aa(t);return Sa(e,s,navigator.mediaCapabilities)}}be.defaultConfig=void 0;function pt(a,e=0){let t=0;const s=a+String(e);for(let i=0;i<s.length;i++){const r=s.charCodeAt(i);t=(t<<5)-t+r|0}return(t%65536+65536)%65536/65536}function Kf(a){const e=pt(a,0),t=pt(a,1),s=pt(a,2);return{rotation:(e-.5)*4,translateX:(t-.5)*12,translateY:(s-.5)*8}}var Vf=Fe('<div class="wavy-container svelte-7frlgw"><svg class="wavy-svg svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg"><defs><filter x="-5%" y="-5%" width="110%" height="110%"><feTurbulence type="turbulence" baseFrequency="0.03" numOctaves="4" result="turb"></feTurbulence><feDisplacementMap in="SourceGraphic" in2="turb" scale="3" xChannelSelector="R" yChannelSelector="G"></feDisplacementMap></filter></defs><path stroke-linejoin="round"></path></svg> <div class="wavy-content svelte-7frlgw"><!></div></div>');function ji(a,e){Vs(e,!0);let t=as(e,"fill",3,"#39FF44"),s=as(e,"strokeColor",3,"#0A182B"),i=as(e,"strokeWidth",3,3),r=as(e,"padding",3,16);const n=l(e.seed),o=`turb-${e.seed.replace(/[^a-zA-Z0-9]/g,"").slice(0,12)}`,c=Math.floor(pt(e.seed,99)*999);function l(v){const R=[];for(let I=0;I<=10;I++){const b=I/10,L=pt(v,I);R.push([6+b*88,6+(L-.5)*5*2])}for(let I=1;I<=10;I++){const b=I/10,L=pt(v,10+I+50);R.push([94+(L-.5)*5*2,6+b*88])}for(let I=1;I<=10;I++){const b=I/10,L=pt(v,20+I+100);R.push([94-b*88,94+(L-.5)*5*2])}for(let I=1;I<10;I++){const b=I/10,L=pt(v,30+I+150);R.push([6+(L-.5)*5*2,94-b*88])}if(R.length<3)return"";let A=`M ${R[0][0]} ${R[0][1]}`;for(let I=0;I<R.length;I++){const b=R[(I-1+R.length)%R.length],L=R[I],C=R[(I+1)%R.length],w=R[(I+2)%R.length],U=.35,F=L[0]+(C[0]-b[0])*U,N=L[1]+(C[1]-b[1])*U,k=C[0]-(w[0]-L[0])*U,$=C[1]-(w[1]-L[1])*U;A+=` C ${F.toFixed(1)} ${N.toFixed(1)}, ${k.toFixed(1)} ${$.toFixed(1)}, ${C[0].toFixed(1)} ${C[1].toFixed(1)}`}return A+=" Z",A}var h=Vf(),u=he(h),d=he(u),g=he(d),f=he(g);Jn(),oe(g),oe(d);var p=ye(d);oe(u);var y=ye(u,2),E=he(y);vl(E,()=>e.children),oe(y),oe(h),Ze(()=>{_i(h,`--padding: ${r()??""}px;`),at(g,"id",o),at(f,"seed",c),at(p,"d",n),at(p,"fill",t()),at(p,"stroke",s()),at(p,"stroke-width",i()),at(p,"filter",`url(#${o})`)}),we(a,h),Hs()}var Hf=Fe('<div class="error-overlay svelte-zbxgh1"> </div>'),Yf=Fe('<div class="player-wrapper svelte-zbxgh1"><video controls="" playsinline="" class="svelte-zbxgh1"><track kind="captions"/></video> <!></div>',2);function Wf(a,e){Vs(e,!0);let t=xe(void 0),s=null,i=xe("");function r(){s&&(s.destroy(),s=null)}function n(){!H(t)||!e.src||(r(),se(i,""),be.isSupported()?(s=new be({enableWorker:!0,lowLatencyMode:!1}),s.loadSource(e.src),s.attachMedia(H(t)),s.on(be.Events.MANIFEST_PARSED,()=>{H(t)?.play().catch(()=>{})}),s.on(be.Events.ERROR,(o,c)=>{if(console.error("HLS error:",c),c.fatal)switch(c.type){case be.ErrorTypes.NETWORK_ERROR:se(i,`Network error loading video: ${c.details}`),s?.startLoad();break;case be.ErrorTypes.MEDIA_ERROR:se(i,`Media error: ${c.details}`),s?.recoverMediaError();break;default:se(i,`Fatal error: ${c.details}`),r();break}})):H(t).canPlayType("application/vnd.apple.mpegurl")?(H(t).src=e.src,H(t).addEventListener("loadedmetadata",()=>{H(t)?.play().catch(()=>{})})):se(i,"HLS playback is not supported in this browser."))}gl(()=>(e.src,H(t)&&n(),r)),ji(a,{seed:"player-main",children:(o,c)=>{var l=Yf(),h=he(l);Ri(h,g=>se(t,g),()=>H(t));var u=ye(h,2);{var d=g=>{var f=Hf(),p=he(f,!0);oe(f),Ze(()=>qe(p,H(i))),we(g,f)};It(u,g=>{H(i)&&g(d)})}oe(l),we(o,l)},$$slots:{default:!0}}),Hs()}var qf=Fe("<img/>"),jf=Fe('<div class="loading-spinner svelte-1nxalmg"><div class="spinner svelte-1nxalmg"></div></div>'),Xf=Fe('<div class="scrub-bar svelte-1nxalmg"><div class="scrub-bar-fill svelte-1nxalmg"></div></div>'),zf=Fe('<div class="thumbnail svelte-1nxalmg" role="img"><!> <canvas></canvas> <!> <!> <div class="thumb-shadow svelte-1nxalmg"></div></div>'),Qf=Fe('<span class="duration-badge svelte-1nxalmg"> </span> <div class="thumb-wrapper svelte-1nxalmg"><!></div> <div class="info svelte-1nxalmg"><h3 class="title svelte-1nxalmg"> </h3> <p class="creator svelte-1nxalmg"> </p> <p class="date svelte-1nxalmg"> </p></div>',1),Zf=Fe('<button class="card svelte-1nxalmg"><!></button>');function Jf(a,e){Vs(e,!0);let t=xe(ea(e.video.value.creator)),s=xe(null);const i=e.video.uri.split("/").pop()||e.video.uri,r=Kf(e.video.value.creator),n=`transform: rotate(${r.rotation}deg) translate(${r.translateX}px, ${r.translateY}px);`;let o=xe(void 0),c=xe(void 0),l=xe(!1),h=xe(0),u=xe(!1),d=xe(!1),g=xe(!1),f=null,p=null,y=0,E=!1,v=null;zn(()=>{aa(e.video.value.creator).then(F=>se(t,F,!0)),Nl(e.video).then(F=>se(s,F,!0))}),$o(x);function T(){if(f)return;se(d,!0),f=document.createElement("video"),f.muted=!0,f.playsInline=!0,f.preload="auto",f.style.cssText="position:fixed;top:-9999px;left:-9999px;width:320px;height:180px;pointer-events:none;",document.body.appendChild(f),f.addEventListener("seeked",S);const F=ia(e.video.uri);be.isSupported()?(p=new be({enableWorker:!1,lowLatencyMode:!1,startLevel:0}),p.loadSource(F),p.attachMedia(f),p.on(be.Events.LEVEL_LOADED,(N,k)=>{y=k.details.totalduration,se(u,!0),A(H(h))}),p.on(be.Events.ERROR,(N,k)=>{k.fatal&&se(d,!1)})):f.canPlayType("application/vnd.apple.mpegurl")&&(f.src=F,f.addEventListener("loadedmetadata",()=>{f&&(y=f.duration,se(u,!0),A(H(h)))}))}function x(){p&&(p.destroy(),p=null),f&&(f.removeEventListener("seeked",S),f.remove(),f=null),se(u,!1),se(d,!1),se(g,!1),E=!1,v=null,y=0}function S(){if(E=!1,se(d,!1),I(),v!==null){const F=v;v=null,R(F)}}function R(F){!f||!H(u)||(E=!0,f.currentTime=F)}function A(F){if(!H(u)||!y)return;const N=F*y;E?v=N:R(N)}function I(){if(!f||!H(c))return;const F=f.videoWidth,N=f.videoHeight;if(!F||!N)return;const k=H(c).getBoundingClientRect(),$=window.devicePixelRatio||1;H(c).width=k.width*$,H(c).height=k.height*$;const B=H(c).getContext("2d");B&&(B.drawImage(f,0,0,H(c).width,H(c).height),se(g,!0))}function b(){se(l,!0),T()}function L(F){if(!H(o))return;const N=H(o).getBoundingClientRect();se(h,Math.max(0,Math.min(1,(F.clientX-N.left)/N.width)),!0),A(H(h))}function C(){se(l,!1)}var w=Zf(),U=he(w);ji(U,{get seed(){return i},fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:3.5,padding:20,children:(F,N)=>{var k=Qf(),$=ml(k),B=he($,!0);oe($);var K=ye($,2),W=he(K);{let ge=ta(()=>i+"-thumb");ji(W,{get seed(){return H(ge)},fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:2,padding:0,children:(_e,He)=>{var De=zf(),is=he(De);{var $t=ae=>{var Ae=qf();let Ge;Ze(()=>{at(Ae,"src",H(s)),at(Ae,"alt",e.video.value.title),Ge=Dr(Ae,1,"thumb-img svelte-1nxalmg",null,Ge,{hidden:H(l)&&H(g)})}),we(ae,Ae)};It(is,ae=>{H(s)&&ae($t)})}var Tt=ye(is,2);let js;Ri(Tt,ae=>se(c,ae),()=>H(c));var ee=ye(Tt,2);{var Te=ae=>{var Ae=jf();we(ae,Ae)};It(ee,ae=>{H(l)&&H(d)&&!H(g)&&ae(Te)})}var Pe=ye(ee,2);{var it=ae=>{var Ae=Xf(),Ge=he(Ae);oe(Ae),Ze(()=>_i(Ge,`width: ${H(h)*100}%`)),we(ae,Ae)};It(Pe,ae=>{H(l)&&H(u)&&ae(it)})}Jn(2),oe(De),Ri(De,ae=>se(o,ae),()=>H(o)),Ze(()=>js=Dr(Tt,1,"scrub-canvas svelte-1nxalmg",null,js,{visible:H(l)&&H(g)})),_r("mouseenter",De,b),Ps("mousemove",De,L),_r("mouseleave",De,C),we(_e,De)},$$slots:{default:!0}})}oe(K);var M=ye(K,2),O=he(M),X=he(O,!0);oe(O);var te=ye(O,2),z=he(te,!0);oe(te);var Z=ye(te,2),ve=he(Z,!0);oe(Z),oe(M),Ze((ge,_e)=>{qe(B,ge),qe(X,e.video.value.title),qe(z,H(t)),qe(ve,_e)},[()=>ra(e.video.value.duration),()=>na(e.video.value.createdAt)]),we(F,k)},$$slots:{default:!0}}),oe(w),Ze(()=>_i(w,n)),Ps("click",w,()=>e.onSelect(e.video)),we(a,w),Hs()}sa(["click","mousemove"]);var eg=Fe('<header class="frog-header svelte-1kxia9k"><div class="title-row svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1> <img src="/frogcursor.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k">@goose.art using @stream.place</p></div></header>');function tg(a){var e=eg();we(a,e)}var sg=Fe('<section class="player-section svelte-1uha8ag"><!> <div class="player-info svelte-1uha8ag"><div class="player-info-left"><h2 class="player-title svelte-1uha8ag"> </h2> <p class="player-meta svelte-1uha8ag"><span class="creator-tag svelte-1uha8ag"> </span> <span class="dot svelte-1uha8ag">·</span> <span class="dot svelte-1uha8ag">·</span> </p></div> <button class="close-btn svelte-1uha8ag" title="Close player">✕</button></div></section>'),ig=Fe('<div class="error svelte-1uha8ag"> </div>'),rg=Fe('<div class="load-more svelte-1uha8ag"><button class="svelte-1uha8ag"> </button></div>'),ng=Fe('<div class="app svelte-1uha8ag"><!> <!> <!> <section class="grid svelte-1uha8ag"></section> <!></div>');function pg(a,e){Vs(e,!0);let t=xe(ea([])),s=xe(void 0),i=xe(!1),r=xe(!0),n=xe(null),o=xe(""),c=xe("");async function l(){if(!(H(i)||!H(r))){se(i,!0),se(c,"");try{const S=await Ol(H(s),24);se(t,[...H(t),...S.records],!0),se(s,S.cursor,!0),se(r,!!S.cursor&&S.records.length>0,!0)}catch(S){se(c,S.message,!0)}se(i,!1)}}function h(S){se(n,S,!0),aa(S.value.creator).then(R=>se(o,R,!0)),window.scrollTo({top:0,behavior:"smooth"})}function u(){se(n,null)}zn(l);var d=ng();Tl("1uha8ag",S=>{pl(()=>{yl.title="vod frog 🐸"})});var g=he(d);tg(g);var f=ye(g,2);{var p=S=>{var R=sg(),A=he(R);{let B=ta(()=>ia(H(n).uri));Wf(A,{get src(){return H(B)}})}var I=ye(A,2),b=he(I),L=he(b),C=he(L,!0);oe(L);var w=ye(L,2),U=he(w),F=he(U,!0);oe(U);var N=ye(U,3),k=ye(N,2);oe(w),oe(b);var $=ye(b,2);oe(I),oe(R),Ze((B,K)=>{qe(C,H(n).value.title),qe(F,H(o)||H(n).value.creator),qe(N,` ${B??""} `),qe(k,` ${K??""}`)},[()=>na(H(n).value.createdAt),()=>ra(H(n).value.duration)]),Ps("click",$,u),we(S,R)};It(f,S=>{H(n)&&S(p)})}var y=ye(f,2);{var E=S=>{var R=ig(),A=he(R,!0);oe(R),Ze(()=>qe(A,H(c))),we(S,R)};It(y,S=>{H(c)&&S(E)})}var v=ye(y,2);xl(v,21,()=>H(t),S=>S.uri,(S,R)=>{Jf(S,{get video(){return H(R)},onSelect:h})}),oe(v);var T=ye(v,2);{var x=S=>{var R=rg(),A=he(R),I=he(A,!0);oe(A),oe(R),Ze(()=>{A.disabled=H(i),qe(I,H(i)?"loading...":"load more 🐸")}),Ps("click",A,l),we(S,R)};It(T,S=>{H(r)&&S(x)})}oe(d),we(a,d),Hs()}sa(["click"]);export{pg as component};
+40
.svelte-kit/output/client/_app/immutable/nodes/2.DCJPxWEg.js
··· 1 + import{a as ke,f as Oe}from"../chunks/DGbOEUpF.js";import{o as zn,a as Mo}from"../chunks/DxGD2b0U.js";import{g as Js,l as No,j as vt,t as ei,v as Bo,F as Uo,A as F,G as $o,aq as Go,I as br,q as ti,k as hs,C as Ko,aL as Vo,az as _r,i as Ho,aP as gt,h as _i,aQ as Yo,s as Wo,V as qo,aR as jo,aK as Qi,aS as Xo,aT as zo,z as Qo,am as Dr,aU as Zo,N as Jo,d as Qn,p as Zn,aV as si,aW as el,aI as tl,m as sl,f as il,o as rl,a1 as Zi,Z as ii,B as q,a5 as de,a7 as ve,a6 as ue,a3 as Ge,a4 as Ji,ab as ie,L as Di,a2 as Jn,aa as nl,ac as ea,a as al,aX as ol,a9 as ll,aY as Cr}from"../chunks/CkzjbUDB.js";import{d as er,a as ft,e as xt,s as Xe}from"../chunks/BsDbD4Ku.js";import{i as mt}from"../chunks/XE2G8ySY.js";import{h as cl}from"../chunks/DmyE0d-6.js";import{t as hl,W as Fs,s as dt,a as Rs,b as ul,r as Ci,c as dl,f as ta,d as sa,e as ia,F as fl,l as gl}from"../chunks/D_t83wNY.js";import{b as Ms}from"../chunks/Dr80VTgO.js";function ml(a,e,t){for(var s=[],i=e.length,r,n=e.length,o=0;o<i;o++){let u=e[o];Zn(u,()=>{if(r){if(r.pending.delete(u),r.done.add(u),r.pending.size===0){var d=a.outrogroups;Pi(a,Qi(r.done)),d.delete(r),d.size===0&&(a.outrogroups=null)}}else n-=1},!1)}if(n===0){var c=s.length===0&&t!==null;if(c){var l=t,h=l.parentNode;tl(h),h.append(l),a.items.clear()}Pi(a,e,!c)}else r={pending:new Set(e),done:new Set},(a.outrogroups??=new Set).add(r)}function Pi(a,e,t=!0){var s;if(a.pending.size>0){s=new Set;for(const n of a.pending.values())for(const o of n)s.add(a.items.get(o).e)}for(var i=0;i<e.length;i++){var r=e[i];if(s?.has(r)){r.f|=gt;const n=document.createDocumentFragment();sl(r,n)}else il(e[i],t)}}var Pr;function pl(a,e,t,s,i,r=null){var n=a,o=new Map;{var c=a;n=vt?ei(Bo(c)):c.appendChild(Js())}vt&&Uo();var l=null,h=qo(()=>{var v=t();return jo(v)?v:v==null?[]:Qi(v)}),u,d=new Map,g=!0;function f(v){(E.effect.f&Jo)===0&&(E.pending.delete(v),E.fallback=l,yl(E,u,n,e,s),l!==null&&(u.length===0?(l.f&gt)===0?Qn(l):(l.f^=gt,zt(l,null,n)):Zn(l,()=>{l=null})))}function p(v){E.pending.delete(v)}var y=No(()=>{u=F(h);var v=u.length;let T=!1;if(vt){var S=$o(n)===Go;S!==(v===0)&&(n=br(),ei(n),ti(!1),T=!0)}for(var x=new Set,D=Ho,A=Wo(),L=0;L<v;L+=1){vt&&hs.nodeType===Ko&&hs.data===Vo&&(n=hs,T=!0,ti(!1));var R=u[L],I=s(R,L),C=g?null:o.get(I);C?(C.v&&_r(C.v,R),C.i&&_r(C.i,L),A&&D.unskip_effect(C.e)):(C=El(o,g?n:Pr??=Js(),R,I,L,i,e,t),g||(C.e.f|=gt),o.set(I,C)),x.add(I)}if(v===0&&r&&!l&&(g?l=_i(()=>r(n)):(l=_i(()=>r(Pr??=Js())),l.f|=gt)),v>x.size&&Yo(),vt&&v>0&&ei(br()),!g)if(d.set(D,x),A){for(const[$,K]of o)x.has($)||D.skip_effect(K.e);D.oncommit(f),D.ondiscard(p)}else f(D);T&&ti(!0),F(h)}),E={effect:y,items:o,pending:d,outrogroups:null,fallback:l};g=!1,vt&&(n=hs)}function jt(a){for(;a!==null&&(a.f&el)===0;)a=a.next;return a}function yl(a,e,t,s,i){var r=e.length,n=a.items,o=jt(a.effect.first),c,l=null,h=[],u=[],d,g,f,p;for(p=0;p<r;p+=1){if(d=e[p],g=i(d,p),f=n.get(g).e,a.outrogroups!==null)for(const L of a.outrogroups)L.pending.delete(f),L.done.delete(f);if((f.f&si)!==0&&Qn(f),(f.f&gt)!==0)if(f.f^=gt,f===o)zt(f,null,t);else{var y=l?l.next:o;f===a.effect.last&&(a.effect.last=f.prev),f.prev&&(f.prev.next=f.next),f.next&&(f.next.prev=f.prev),pt(a,l,f),pt(a,f,y),zt(f,y,t),l=f,h=[],u=[],o=jt(l.next);continue}if(f!==o){if(c!==void 0&&c.has(f)){if(h.length<u.length){var E=u[0],v;l=E.prev;var T=h[0],S=h[h.length-1];for(v=0;v<h.length;v+=1)zt(h[v],E,t);for(v=0;v<u.length;v+=1)c.delete(u[v]);pt(a,T.prev,S.next),pt(a,l,T),pt(a,S,E),o=E,l=S,p-=1,h=[],u=[]}else c.delete(f),zt(f,o,t),pt(a,f.prev,f.next),pt(a,f,l===null?a.effect.first:l.next),pt(a,l,f),l=f;continue}for(h=[],u=[];o!==null&&o!==f;)(c??=new Set).add(o),u.push(o),o=jt(o.next);if(o===null)continue}(f.f&gt)===0&&h.push(f),l=f,o=jt(f.next)}if(a.outrogroups!==null){for(const L of a.outrogroups)L.pending.size===0&&(Pi(a,Qi(L.done)),a.outrogroups?.delete(L));a.outrogroups.size===0&&(a.outrogroups=null)}if(o!==null||c!==void 0){var x=[];if(c!==void 0)for(f of c)(f.f&si)===0&&x.push(f);for(;o!==null;)(o.f&si)===0&&o!==a.fallback&&x.push(o),o=jt(o.next);var D=x.length;if(D>0){var A=r===0?t:null;ml(a,x,A)}}}function El(a,e,t,s,i,r,n,o){var c=(n&Xo)!==0?(n&zo)===0?Qo(t,!1,!1):Dr(t):null,l=(n&Zo)!==0?Dr(i):null;return{v:c,i:l,e:_i(()=>(r(e,c??t,l??i,o),()=>{a.delete(s)}))}}function zt(a,e,t){if(a.nodes)for(var s=a.nodes.start,i=a.nodes.end,r=e&&(e.f&gt)===0?e.nodes.start:t;s!==null;){var n=rl(s);if(r.before(s),s===i)return;s=n}}function pt(a,e,t){e===null?a.effect.first=t:e.next=t,t===null?a.effect.last=e:t.prev=e}function Zt(a,e,t,s,i,r){var n=a.__className;if(vt||n!==t||n===void 0){var o=hl(t,s,r);(!vt||o!==a.getAttribute("class"))&&(o==null?a.removeAttribute("class"):a.className=o),a.__className=t}else if(r&&i!==r)for(var c in r){var l=!!r[c];(i==null||l!==!!i[c])&&a.classList.toggle(c,l)}return r}const V=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},vl=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Tl},Tl=Number.MAX_SAFE_INTEGER||9007199254740991;let W=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),_=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a})({}),m=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a})({});var te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Y={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ot{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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 Sl{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ot(e),this.fast_=new Ot(t),this.defaultTTFB_=i,this.ttfb_=new Ot(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ot(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ot(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ot(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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 xl(a,e,t){return(e=Il(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ae(){return ae=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ae.apply(null,arguments)}function kr(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function re(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kr(Object(t),!0).forEach(function(s){xl(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):kr(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Al(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Il(a){var e=Al(a,"string");return typeof e=="symbol"?e:e+""}class Ye{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Tt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Tt=function(){},Ll={trace:Tt,debug:Tt,log:Tt,warn:Tt,info:Tt,error:Tt};function ki(){return ae({},Ll)}function Rl(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):Tt}function wr(a,e,t){return e[a]?e[a].bind(e):Rl(a,t)}const wi=ki();function bl(a,e,t){const s=ki();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=wr(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return ki()}i.forEach(r=>{wi[r]=wr(r,a)})}else ae(wi,s);return s}const ne=wi;function It(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _l(a){return typeof self<"u"&&a===self.ManagedMediaSource}function ra(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function Ve(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function be(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function na(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Dl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ri={exports:{}},Or;function Cl(){return Or||(Or=1,(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var y=g.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()})(ri)),ri.exports}var tr=Cl();class sr{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class aa{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,kl(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[le.AUDIO]:null,[le.VIDEO]:null,[le.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new sr),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=tr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}}function Te(a){return a.sn!=="initSegment"}class ni extends aa{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(V(e)&&V(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=V(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!V(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Te(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 s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class Pl extends aa{constructor(e,t,s,i,r){super(s),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=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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 oa(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||oa(t,e)}}function kl(a,e){const t=oa(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Fr=Math.pow(2,32)-1,wl=[].push,la={video:1,audio:2,id3:3,text:4};function Ae(a){return String.fromCharCode.apply(null,a)}function ca(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function z(a,e){const t=ha(a,e);return t<0?4294967296+t:t}function Mr(a,e){let t=z(a,e);return t*=Math.pow(2,32),t+=z(a,e+4),t}function ha(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Ol(a){const e=a.byteLength;for(let t=0;t<e;){const s=z(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function ee(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=z(a,i),n=Ae(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=ee(a.subarray(i+8,o),e.slice(1));c.length&&wl.apply(t,c)}i=o}return t}function Fl(a){const e=[],t=a[0];let s=8;const i=z(a,s);s+=4;let r=0,n=0;t===0?(r=z(a,s),n=z(a,s+4),s+=8):(r=Mr(a,s),n=Mr(a,s+8),s+=16),s+=2;let o=a.length+n;const c=ca(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=z(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return ne.warn("SIDX has hierarchical references (not supported)"),null;const f=z(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function ua(a){const e=[],t=ee(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=ee(r,["tkhd"])[0];if(n){let o=n[0];const c=z(n,o===0?12:20),l=ee(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=z(l,o===0?12:20),u=ee(r,["mdia","hdlr"])[0];if(u){const d=Ae(u.subarray(8,12)),g={soun:le.AUDIO,vide:le.VIDEO}[d],f=ee(r,["mdia","minf","stbl","stsd"])[0],p=Ml(f);g?(e[c]={timescale:h,type:g,stsd:p},e[g]=re({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return ee(a,["moov","mvex","trex"]).forEach(i=>{const r=z(i,4),n=e[r];n&&(n.default={duration:z(i,12),flags:z(i,20)})}),e}function Ml(a){const e=a.subarray(8),t=e.subarray(86),s=Ae(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=ee(e,[s])[0].subarray(s==="enca"?28:78);ee(l,["sinf"]).forEach(u=>{const d=ee(u,["schm"])[0];if(d){const g=Ae(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=ee(u,["frma"])[0];f&&(i=Ae(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=ee(t,["avcC"])[0];c&&c.length>3&&(i+="."+ds(c[1])+ds(c[2])+ds(c[3]),r=us(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=ee(e,[s])[0],l=ee(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=ai(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=ai(l,h);const d=l[h++];if(d===64)i+="."+ds(d);else break;if(h+=12,l[h++]!==5)break;h=ai(l,h);const g=l[h++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[h]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=ee(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=z(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+Nl(d).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let E=p.length;E--;){const v=p[E];(v||y)&&(y="."+v.toString(16).toUpperCase()+y)}i+=y}r=us(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=us(i,t)||i;break}case"vp09":{const c=ee(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Je(l)+"."+Je(h)+"."+Je(u)}break}case"av01":{const c=ee(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&d?g?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,v=c[2]&3;i+="."+l+"."+Je(h)+u+"."+Je(f)+"."+p+"."+y+E+v+"."+Je(1)+"."+Je(1)+"."+Je(1)+"."+0,r=us("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function us(a,e){const t=ee(e,["dvvC"]),s=t.length?t[0]:ee(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Je(i)+"."+Je(r)}}function Nl(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function ai(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function ds(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Je(a){return(a<10?"0":"")+a}function Bl(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&da(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(ne.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${be(r)} -> ${be(t)}`),s.set(t,8))})}function Ul(a){const e=[];return da(a,t=>e.push(t.subarray(8,24))),e}function da(a,e){ee(a,["moov","trak"]).forEach(s=>{const i=ee(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=ee(r,["enca"]);const o=n.length>0;o||(n=ee(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);ee(l,["sinf"]).forEach(u=>{const d=fa(u);d&&e(d,o)})})})}function fa(a){const e=ee(a,["schm"])[0];if(e){const t=Ae(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=ee(a,["schi","tenc"])[0];if(s)return s}}}function $l(a,e,t){const s={},i=ee(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=ee(n,["tfhd"])[0],c=z(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=ee(n,["tfdt"])[0];if(u){const T=u[0];let S=z(u,4);T===1&&(S===Fr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Fr+1,S+=z(u,8))),V(S)&&(!V(h.start)||S<h.start)&&(h.start=S)}const d=l.default,g=z(o,0)|d?.flags;let f=d?.duration||0;g&8&&(g&2?f=z(o,12):f=z(o,8));const p=ee(n,["trun"]);let y=h.start||0,E=0,v=f;for(let T=0;T<p.length;T++){const S=p[T],x=z(S,4),D=h.sampleCount;h.sampleCount+=x;const A=S[3]&1,L=S[3]&4,R=S[2]&1,I=S[2]&2,C=S[2]&4,$=S[2]&8;let K=8,H=x;for(A&&(K+=4),L&&x&&(!(S[K+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),K+=4,R?(v=z(S,K),K+=4):v=f,I&&(K+=4),$&&(K+=4),y+=v,E+=v,H--);H--;)R?(v=z(S,K),K+=4):v=f,I&&(K+=4),C&&(S[K+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(H+1),h.keyFrameStart=y),K+=4),$&&(K+=4),y+=v,E+=v;!E&&f&&(E+=f*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=ee(a,["sidx"]);for(let c=0;c<o.length;c++){const l=Fl(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&V(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function Gl(a){const e={valid:null,remainder:null},t=ee(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function He(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Nr(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return ee(s,["moof"]).map(c=>{const l=c.byteOffset-8;ee(c,["traf"]).map(u=>{const d=ee(u,["tfdt"]).map(g=>{const f=g[0];let p=z(g,4);return f===1&&(p*=Math.pow(2,32),p+=z(g,8)),p/i})[0];return d!==void 0&&(a=d),ee(u,["tfhd"]).map(g=>{const f=z(g,4),p=z(g,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,v=(p&8)!==0;let T=0;const S=(p&16)!==0;let x=0;const D=(p&32)!==0;let A=8;f===r&&(y&&(A+=8),E&&(A+=4),v&&(T=z(g,A),A+=4),S&&(x=z(g,A),A+=4),D&&(A+=4),e.type==="video"&&(n=js(e.codec)),ee(u,["trun"]).map(L=>{const R=L[0],I=z(L,0)&16777215,C=(I&1)!==0;let $=0;const K=(I&4)!==0,H=(I&256)!==0;let O=0;const w=(I&512)!==0;let k=0;const M=(I&1024)!==0,N=(I&2048)!==0;let G=0;const B=z(L,4);let U=8;C&&($=z(L,U),U+=4),K&&(U+=4);let j=$+l;for(let J=0;J<B;J++){if(H?(O=z(L,U),U+=4):O=T,w?(k=z(L,U),U+=4):k=x,M&&(U+=4),N&&(R===0?G=z(L,U):G=ha(L,U),U+=4),e.type===le.VIDEO){let X=0;for(;X<k;){const Z=z(s,j);if(j+=4,Kl(n,s[j])){const oe=s.subarray(j,j+Z);ir(oe,n?2:1,a+G/i,t)}j+=Z,X+=Z+4}}a+=O/i}}))})})}),t}function js(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Kl(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ir(a,e,t,s){const i=ga(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){ne.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=ca(i,h);if(h+=2,d===49){const g=z(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const p=i[h++],y=31&p,E=64&p,v=E?2+y*3:0,T=new Uint8Array(v);if(E){T[0]=p;for(let S=1;S<v;S++)T[S]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:T})}}}}}else if(n===5&&o>16){const u=[];for(let f=0;f<16;f++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:Ve(g),userDataBytes:g})}}}function ga(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function Vl(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;Ae(a.subarray(l,l+1))!=="\0";)t+=Ae(a.subarray(l,l+1)),l+=1;for(t+=Ae(a.subarray(l,l+1)),l+=1;Ae(a.subarray(l,l+1))!=="\0";)s+=Ae(a.subarray(l,l+1)),l+=1;s+=Ae(a.subarray(l,l+1)),l+=1,i=z(a,12),r=z(a,16),o=z(a,20),c=z(a,24),l=28}else if(e===1){l+=4,i=z(a,l),l+=4;const u=z(a,l);l+=4;const d=z(a,l);for(l+=4,n=2**32*u+d,vl(n)||(n=Number.MAX_SAFE_INTEGER,ne.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=z(a,l),l+=4,c=z(a,l),l+=4;Ae(a.subarray(l,l+1))!=="\0";)t+=Ae(a.subarray(l,l+1)),l+=1;for(t+=Ae(a.subarray(l,l+1)),l+=1;Ae(a.subarray(l,l+1))!=="\0";)s+=Ae(a.subarray(l,l+1)),l+=1;s+=Ae(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function Hl(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function Yl(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),Hl([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function Wl(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=ql(i);e.push(r),s+=r.size}}return e}function ql(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=be(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let g=0;g<d;g++)c.push(new Uint8Array(n,t+32+g*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const ma=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Yt={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 rr(a,e){const t=Yt[e];return!!t&&!!t[a.slice(0,4)]}function ss(a,e,t=!0){return!a.split(",").some(s=>!nr(s,e,t))}function nr(a,e,t=!0){var s;const i=It(t);return(s=i?.isTypeSupported(is(a,e)))!=null?s:!1}function is(a,e){return`${e}/mp4;codecs=${a}`}function Br(a){if(a){const e=a.substring(0,4);return Yt.video[e]}return 2}function Ns(a){const e=ma();return a.split(",").reduce((t,s)=>{const r=e&&js(s)?9:Yt.video[s];return r?(r*2+t)/(t?3:2):(Yt.audio[s]+t)/(t?2:1)},0)}const oi={};function jl(a,e=!0){if(oi[a])return oi[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(nr(t[i],"audio",e))return oi[a]=t[i],t[i];if(t[i]==="mp3"&&(s=It(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const Xl=/flac|opus|mp4a\.40\.34/i;function Bs(a,e=!0){return a.replace(Xl,t=>jl(t.toLowerCase(),e))}function zl(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)rr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function bs(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Ur(a,"audio")||Ur(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function Ur(a,e){return rr(a,e)&&nr(a,e)}function Ql(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Zl(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function $r(a){const e=It(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Oi(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Jl={supported:!0,powerEfficient:!0,smooth:!0},ec={supported:!1,smooth:!1,powerEfficient:!1},pa={supported:!0,configurations:[],decodingInfoResults:[Jl]};function ya(a,e){return{supported:!1,configurations:e,decodingInfoResults:[ec],error:a}}function tc(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>js(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&V(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Ea(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(pa);const r=[],n=sc(a),o=n.length,c=ic(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>js(u))&&ma())return Promise.resolve(ya(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=nc(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function sc(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=va(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:is(Zl(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function ic(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=va(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(g=>{const f={contentType:is(g,"audio"),bitrate:t?rc(g,r):r};d&&(f.channels=""+d),h.push(f)})}return h},n):n},[]):[]}function rc(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function va(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function nc(a){let e="";const{audio:t,video:s}=a;if(s){const i=Oi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Oi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Fi=["NONE","TYPE-0","TYPE-1",null];function ac(a){return Fi.indexOf(a)>-1}const Us=["SDR","PQ","HLG"];function oc(a){return!!a&&Us.indexOf(a)>-1}var _s={No:"",Yes:"YES",v2:"v2"};function Gr(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?_s.v2:_s.Yes:_s.No}class Kr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class rs{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Vr(this._audioGroups,e)}hasSubtitleGroup(e){return Vr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Vr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function lc(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function cc(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||Us.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&lc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const hc=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ce=(a,e)=>JSON.stringify(a,hc(e));function uc(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,g=1/0,f=1/0,p=1/0,y=0,E=[];const{preferHDR:v,allowedVideoRanges:T}=cc(e,i);for(let L=r.length;L--;){const R=a[r[L]];h||(h=R.channels[2]>0),d=Math.min(d,R.minHeight),g=Math.min(g,R.minFramerate),f=Math.min(f,R.minBitrate),T.filter(C=>R.videoRanges[C]>0).length>0&&(u=!0)}d=V(d)?d:0,g=V(g)?g:0;const S=Math.max(1080,d),x=Math.max(30,g);f=V(f)?f:t,t=Math.max(f,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((L,R)=>{const I=a[R];if(R===L)return L;if(E=u?T.filter(C=>I.videoRanges[C]>0):[],D){if(I.minBitrate>t)return Qe(R,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),L;if(!I.hasDefaultAudio)return Qe(R,"no renditions with default or auto-select sound found"),L;if(o&&R.indexOf(o.substring(0,4))%5!==0)return Qe(R,`audio codec preference "${o}" not found`),L;if(n&&!l){if(!I.channels[n])return Qe(R,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),L}else if((!o||l)&&h&&I.channels[2]===0)return Qe(R,"no renditions with stereo sound found"),L;if(I.minHeight>S)return Qe(R,`min resolution of ${I.minHeight} > maximum of ${S}`),L;if(I.minFramerate>x)return Qe(R,`min framerate of ${I.minFramerate} > maximum of ${x}`),L;if(!E.some(C=>I.videoRanges[C]>0))return Qe(R,`no variants with VIDEO-RANGE of ${ce(E)} found`),L;if(c&&R.indexOf(c.substring(0,4))%5!==0)return Qe(R,`video codec preference "${c}" not found`),L;if(I.maxScore<y)return Qe(R,`max score of ${I.maxScore} < selected max of ${y}`),L}return L&&(Ns(R)>=Ns(L)||I.fragmentError>a[L].fragmentError)?L:(p=I.minIndex,y=I.maxScore,R)},void 0),videoRanges:E,preferHDR:v,minFramerate:g,minBitrate:f,minIndex:p}}function Qe(a,e){ne.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Ta(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function dc(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Hr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function tt(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(Ct(a,i,t))return s}return-1}function Ct(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||fc(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||gc(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function fc(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function gc(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Dt(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function mc(a,e,t,s,i){const r=e[s],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=Yr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return tt(a,f,i)>-1});return u>-1?u:Yr(e,s,d=>{const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return tt(a,f,i)>-1})}function Yr(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function $s(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class pc extends Ye{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,g=n.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const v=n.mainForwardBufferInfo;if(!E&&v===null)return;const T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(d<=Math.max(T,1e3*(u/(S*2))))return;const x=v?v.len/S:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,L=this.getBwEstimate(),R=n.levels,I=R[f],C=Math.max(h.loaded,Math.round(u*(i.bitrate||I.averageBitrate)/8));let $=A?d-D:d;$<1&&A&&($=Math.min(d,h.loaded*8/L));const K=A?h.loaded*1e3/$:0,H=T/1e3,O=K?(C-h.loaded)/K:C*8/L+H;if(O<=x)return;const w=K?K*8:L,k=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,M=this.hls.config.abrBandWidthUpFactor;let N=Number.POSITIVE_INFINITY,G;for(G=f-1;G>g;G--){const J=R[G].maxBitrate,X=!R[G].details||k;if(N=this.getTimeToLoadFrag(H,w,u*J,X),N<Math.min(x,u+H))break}if(N>=O||N>u*10)return;A?this.bwEstimator.sample(d-Math.min(T,D),h.loaded):this.bwEstimator.sampleTTFB(d);const B=R[G].maxBitrate;this.getBwEstimate()*M>B&&this.resetEstimator(B);const U=this.findBestLevel(B,g,G,0,x,1,1);U>-1&&(G=U),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly; 2 + Fragment duration: ${i.duration.toFixed(3)} 3 + Time to underbuffer: ${x.toFixed(3)} s 4 + Estimated load time for current fragment: ${O.toFixed(3)} s 5 + Estimated load time for down switch fragment: ${N.toFixed(3)} s 6 + TTFB estimate: ${D|0} ms 7 + Current BW estimate: ${V(L)?L|0:"Unknown"} bps 8 + New BW estimate: ${this.getBwEstimate()|0} bps 9 + Switching to level ${G} @ ${B|0} bps`),n.nextLoadLevel=n.nextAutoLevel=G,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===G&&G>0){const J=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${G>0?"and switching down":""} 10 + Fragment duration: ${i.duration.toFixed(3)} s 11 + Time to underbuffer: ${J.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,G>g){let X=this.findBestLevel(this.hls.levels[g].bitrate,g,G,0,J,1,1);X===-1&&(X=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||O>N*2?j():this.timer=self.setInterval(j,N*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},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 Sl(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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;V(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===Y.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Y.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[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:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,n,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const g=this.findBestLevel(c,n,i,l,d,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[n],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(f.length===1)return 0;const v=f[u],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||h===-1;let x,D="SDR",A=v?.frameRate||0;const{audioPreference:L,videoPreference:R}=E,I=this.audioTracksByGroup||(this.audioTracksByGroup=Ta(p));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=dc(f,I,t,s)),k=uc(w,D,e,L,R),{codecSet:M,videoRanges:N,minFramerate:G,minBitrate:B,minIndex:U,preferHDR:j}=k;C=U,x=M,D=j?N[N.length-1]:N[0],A=G,e=Math.max(e,B),this.log(`picked start tier ${ce(k)}`)}else x=v?.codecSet,D=v?.videoRange;const $=g?g.duration:d?d.duration:0,K=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let w=s;w>=t;w--){var O;const k=f[w],M=w>u;if(!k)continue;if(E.useMediaCapabilities&&!k.supportedResult&&!k.supportedPromise){const X=navigator.mediaCapabilities;typeof X?.decodingInfo=="function"&&tc(k,I,D,A,e,L)?(k.supportedPromise=Ea(k,I,X,this.supportedCache),k.supportedPromise.then(Z=>{if(!this.hls)return;k.supportedResult=Z;const oe=this.hls.levels,he=oe.indexOf(k);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${he} ${ce(Z)}`):Z.supported?Z.decodingInfoResults.some(xe=>xe.smooth===!1||xe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${he} not smooth or powerEfficient: ${ce(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${he} ${ce(Z)}`),he>-1&&oe.length>1&&(this.log(`Removing unsupported level ${he}`),this.hls.removeLevel(he),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):k.supportedResult=pa}if((x&&k.codecSet!==x||D&&k.videoRange!==D||M&&A>k.frameRate||!M&&A>0&&A<k.frameRate||(O=k.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(X=>X.smooth===!1))&&(!S||w!==C)){H.push(w);continue}const N=k.details,G=(g?N?.partTarget:N?.averagetargetduration)||$;let B;M?B=o*e:B=n*e;const U=$&&i>=$*2&&r===0?k.averageBitrate:k.maxBitrate,j=this.getTimeToLoadFrag(K,B,U*G,N===void 0);if(B>=U&&(w===h||k.loadError===0&&k.fragmentError===0)&&(j<=K||!V(j)||T&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return w!==y&&(X===-1||X!==y)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[H[0]].codecs}" ${f[H[0]].videoRange}; not compatible with "${x}" ${D}`),this.info(`switch candidate:${u}->${w} adjustedbw(${Math.round(B)})-bitrate=${Math.round(B-U)} ttfb:${K.toFixed(1)} avgDuration:${G.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${S} codecSet:${k.codecSet} videoRange:${k.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Sa={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function yc(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!V(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(vc(e,t,n))return n}return null}function Pt(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&Wr(t,s,r)===0||Ec(r,a,Math.min(i,s))))return r;const n=Sa.search(e,Wr.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Ec(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function Wr(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function vc(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function xa(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return Sa.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function Gs(a){switch(a.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Aa(a){return a.details.startsWith("key")}function Ia(a){return Aa(a)&&!!a.frag&&!a.frag.decryptdata}function qr(a,e){const t=Gs(e);return a.default[`${t?"timeout":"error"}Retry`]}function ar(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function jr(a){return re(re({},a),{errorRetry:null,timeoutRetry:null})}function Ks(a,e,t,s){if(!a)return!1;const i=s?.code,r=e<a.maxNumRetry&&(Tc(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function Tc(a){return Mi(a)||!!a&&(a<400||a>499)}function Mi(a){return a===0&&navigator.onLine===!1}var Re={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ue={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Sc extends Ye{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===Y.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Gt();return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var n;const c=t.parent===Y.MAIN?t.level:i.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===te.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===te.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Ue.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingHDCP};return;case _.KEY_SYSTEM_SESSION_UPDATE_FAILED:case _.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case _.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingKey};return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction=Gt();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Gt())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=qr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ks(i,r,Gs(e),e.response))return{action:Re.RetryRequest,flags:Ue.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=qr(Aa(e)?n:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==_.FRAG_GAP&&i.fragmentError++,!Ia(e)&&Ks(o,c,Gs(e),e.response)))return{action:Re.RetryRequest,flags:Ue.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===_.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===Y.AUDIO&&l===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>i.audioCodec!==D),T=e.sourceBufferName==="video"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:A})=>i.codecSet!==D&&i.audioCodec===A),{type:S,groupId:x}=(n=e.context)!=null?n:{};for(let D=u.length;D--;){const A=(D+d)%u.length;if(A!==d&&A>=g&&A<=f&&u[A].loadError===0){var o,c;const L=u[A];if(l===_.FRAG_GAP&&p===Y.MAIN&&e.frag){const R=u[A].details;if(R){const I=Pt(e.frag,R.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(S===te.AUDIO_TRACK&&L.hasAudioGroup(x)||S===te.SUBTITLE_TRACK&&L.hasSubtitleGroup(x))continue;if(p===Y.AUDIO&&(o=i.audioGroups)!=null&&o.some(R=>L.hasAudioGroup(R))||p===Y.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(R=>L.hasSubtitleGroup(R))||E&&i.audioCodec===L.audioCodec||T&&i.codecSet===L.codecSet||!E&&i.codecSet!==L.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Ue.None,nextAutoLevel:h}}return{action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.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,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ue.None:this.switchLevel(e,r);break;case Ue.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=Fi[Fi.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ue.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var n,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(n=l[d].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${be(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==Y.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===_.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Oi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Gt(a){const e={action:Re.DoNothing,flags:Ue.None};return a&&(e.resolved=!0),e}var Ie={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class xc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if(o?.body.type===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=Ft(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),fs(r)||this.removeParts(s.sn-1,s.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 s=this.activePartLists[t];s&&(this.activePartLists[t]=Xr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ft(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<d&&o>u){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&fs(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||fs(t))}getState(e){const t=Ft(e),s=this.fragments[t];return s?s.buffered?fs(s)?Ie.PARTIAL:Ie.OK:Ie.APPENDING:Ie.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Ft(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ft(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Ft(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Xr(s,r=>r.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}}function fs(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function Ft(a){return`${a.type}_${a.level}_${a.sn}`}function Xr(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Lt={cbc:0,ctr:1};class Ac{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Lt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Lt.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 Ic(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Lc{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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[f]=E,t[E]=f;const v=g[f],T=g[v],S=g[T];let x=g[E]*257^E*16843008;i[f]=x<<24|x>>>8,r[f]=x<<16|x>>>16,n[f]=x<<8|x>>>24,o[f]=x,x=S*16843009^T*65537^v*257^f*16843008,l[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,f?(f=v^g[g[g[S^v]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],E=g[3];let v,T;for(o=0;o<n;o++){if(o<r){v=l[o]=t[o];continue}T=v,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),l[o]=v=(l[o-r]^T)>>>0}for(c=0;c<n;c++)o=n-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?h[c]=T:h[c]=f[u[T>>>24]]^p[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],p=d[2],y=d[3];const E=new Int32Array(e),v=new Int32Array(E.length);let T,S,x,D,A,L,R,I,C,$,K,H,O,w;const k=this.networkToHostOrderSwap;for(;t<E.length;){for(C=k(E[t]),$=k(E[t+1]),K=k(E[t+2]),H=k(E[t+3]),A=C^r[0],L=H^r[1],R=K^r[2],I=$^r[3],O=4,w=1;w<i;w++)T=c[A>>>24]^l[L>>16&255]^h[R>>8&255]^u[I&255]^r[O],S=c[L>>>24]^l[R>>16&255]^h[I>>8&255]^u[A&255]^r[O+1],x=c[R>>>24]^l[I>>16&255]^h[A>>8&255]^u[L&255]^r[O+2],D=c[I>>>24]^l[A>>16&255]^h[L>>8&255]^u[R&255]^r[O+3],A=T,L=S,R=x,I=D,O=O+4;T=n[A>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[I&255]^r[O],S=n[L>>>24]<<24^n[R>>16&255]<<16^n[I>>8&255]<<8^n[A&255]^r[O+1],x=n[R>>>24]<<24^n[I>>16&255]<<16^n[A>>8&255]<<8^n[L&255]^r[O+2],D=n[I>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[R&255]^r[O+3],v[t]=k(T^g),v[t+1]=k(D^f),v[t+2]=k(x^p),v[t+3]=k(S^y),g=C,f=$,p=K,y=H,t=t+4}return v.buffer}}class Rc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=bc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function bc(a){switch(a){case Lt.cbc:return"AES-CBC";case Lt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const _c=16;class or{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Ic(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==Lt.cbc||t.byteLength!==16)return ne.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=He(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Lc),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Rc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ac(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ne.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%_c;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ne.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const zr=Math.pow(2,17);class Dc{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 s=e.url;if(!s)return Promise.reject(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(Zr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Qr(e);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zr};e.stats=l.stats;const g={onSuccess:(f,p,y,E)=>{this.resetLoader(e,l);let v=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:E})},onError:(f,p,y,E)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:E}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Zr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Qr(e,t);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zr};t.stats=l.stats,l.load(h,d,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:g.data,networkDetails:y};s(E),o(E)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(V(i)&&V(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&Cc((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Zr(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new ht(s)}function Cc(a){return a==="AES-128"||a==="AES-256"}class ht extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class La extends Ye{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 lr{constructor(e,t,s,i=0,r=-1,n=!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=gs(),this.buffering={audio:gs(),video:gs(),audiovideo:gs()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function gs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jr={length:0,start:()=>0,end:()=>0};class Q{static isBuffered(e,t){if(e){const s=Q.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=Q.getBuffered(e);return Q.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=Q.bufferedRanges(e);if(i.length)return Q.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,n=l-t;else if(t+s<u){o=u;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Jr}catch(t){return ne.log("failed to get media.buffered",t),Jr}}}const Ra=/\{\$([a-zA-Z0-9-_]+)\}/g;function en(a){return Ra.test(a)}function Ni(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Ra,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function tn(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Pc(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const kc=/^(\d+)x(\d+)$/,sn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class fe{constructor(e,t){typeof e=="string"&&(e=fe.parseAttrList(e,t)),ae(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=kc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(sn.lastIndex=0;(s=sn.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Ni(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="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":ne.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const wc="com.apple.hls.interstitial";function Oc(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Fc(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class ba{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){ne.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=ae(new fe({}),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"]);V(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?(ne.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(V(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===wc}get isValid(){return!!this.id&&!this._badValueForSameId&&V(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 Mc=10;class Nc{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>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 s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?V(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Mc}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Vs(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function rn(a,e){return!a&&!e?!0:!a||!e?!1:Vs(a,e)}function Kt(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function cr(a){switch(a){case"AES-128":case"AES-256":return Lt.cbc;case"AES-256-CTR":return Lt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function hr(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Bi(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function Bc(a){const e=Bi(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function _a(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function Da(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=hr(n)):t=Bc(n)}}return t}const Hs=typeof self<"u"?self:void 0;var ge={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},_e={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ds(a){switch(a){case _e.FAIRPLAY:return ge.FAIRPLAY;case _e.PLAYREADY:return ge.PLAYREADY;case _e.WIDEVINE:return ge.WIDEVINE;case _e.CLEARKEY:return ge.CLEARKEY}}function li(a){switch(a){case ge.FAIRPLAY:return _e.FAIRPLAY;case ge.PLAYREADY:return _e.PLAYREADY;case ge.WIDEVINE:return _e.WIDEVINE;case ge.CLEARKEY:return _e.CLEARKEY}}function Qt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[ge.FAIRPLAY,ge.WIDEVINE,ge.PLAYREADY,ge.CLEARKEY].filter(i=>!!e[i]):[];return!s[ge.WIDEVINE]&&t&&s.push(ge.WIDEVINE),s}const Ca=(function(a){return Hs!=null&&(a=Hs.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Uc(a,e,t,s){let i;switch(a){case ge.FAIRPLAY:i=["cenc","sinf"];break;case ge.WIDEVINE:case ge.PLAYREADY:i=["cenc"];break;case ge.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return $c(i,e,t,s)}function $c(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Gc(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Pa(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=hr(o).subarray(0,16);return _a(c),c}}return null}let Mt={};class At{static clearKeyUriToKeyIdMap(){Mt={}}static setKeyIdForUri(e,t){Mt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Mt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Mt[e]=s,s}constructor(e,t,s,i=[1],r=null,n){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=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Kt(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(na(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Vs(e.keyFormatVersions,this.keyFormatVersions)&&rn(e.iv,this.iv)&&rn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Kt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case _e.FAIRPLAY:case _e.WIDEVINE:case _e.PLAYREADY:case _e.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(Kt(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ne.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Vc(e)),new At(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Mt[this.uri];if(r&&!Vs(this.keyId,r)&&At.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Da(this.uri);if(s)switch(this.keyFormat){case _e.WIDEVINE:if(this.pssh=s,!this.keyId){const r=Wl(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=nn(t));break;case _e.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Yl(r,null,s),this.keyId=Pa(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Kc(t),r||(r=nn(t),r||(r=Mt[this.uri])),r&&(this.keyId=r,At.setKeyIdForUri(this.uri,r))}return this}}function Kc(a){const e=a?.[_e.WIDEVINE];return e?e.keyId:null}function nn(a){const e=a?.[_e.PLAYREADY];if(e){const t=Da(e.uri);if(t)return Pa(t)}return null}function Vc(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const an=/#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,on=/#EXT-X-MEDIA:(.*)/g,Hc=/^#EXT(?:INF|-X-TARGETDURATION):/m,ci=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Yc=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 st{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return tr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Hc.test(e)}static parseMasterPlaylist(e,t){const s=en(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(an.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=an.exec(e))!=null;)if(n[1]){var o;const l=new fe(n[1],i),h=Ni(i,n[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:st.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),hn(l.CODECS,u);const g=l["SUPPLEMENTAL-CODECS"];g&&(u.supplemental={},hn(g,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const u=new fe(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=ln(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):ne.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new fe(h,i);tn(i,u,t)}break}case"CONTENT-STEERING":{const u=new fe(h,i);i.contentSteering={uri:st.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=cn(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(on.lastIndex=0;(i=on.exec(e))!==null;){const l=new fe(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],v={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?st.resolve(l.URI,t):""};if(f&&(v.assocLang=f),p&&(v.channels=p),y&&(v.characteristics=y),E&&(v.instreamId=E),u!=null&&u.length){const T=st.findGroup(u,v.groupId)||u[0];un(v,T,"audioCodec"),un(v,T,"textCodec")}d.push(v)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new Nc(t),h=l.fragments,u=[];let d=null,g=0,f=0,p=0,y=0,E=0,v=null,T=new ni(i,c),S,x,D,A=-1,L=!1,R=null,I;if(ci.lastIndex=0,l.m3u8=e,l.hasVariableRefs=en(e),((o=ci.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=ci.exec(e))!==null;){L&&(L=!1,T=new ni(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),R&&(T.setByteRange(R),R=null)));const H=S[1];if(H){T.duration=parseFloat(H);const O=(" "+S[2]).slice(1);T.title=O||null,T.tagList.push(O?["INF",H,O]:["INF",H])}else if(S[3]){if(V(T.duration)){T.playlistOffset=p,T.setStart(p),D&&fn(T,D,l),T.sn=g,T.level=s,T.cc=y,h.push(T);const O=(" "+S[3]).slice(1);T.relurl=Ni(l,O),Ui(T,v,u),v=T,p+=T.duration,g++,f=0,L=!0}}else{if(S=S[0].match(Yc),!S){ne.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<S.length&&S[x]===void 0;x++);const O=(" "+S[x]).slice(1),w=(" "+S[x+1]).slice(1),k=S[x+2]?(" "+S[x+2]).slice(1):null;switch(O){case"BYTERANGE":v?T.setByteRange(w,v):T.setByteRange(w);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=w,T.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&lt(l,O,S),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?lt(l,O,S):h.length>0&&gn(l,O,S),g=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&lt(l,O,S);const M=new fe(w,l),N=M.decimalInteger("SKIPPED-SEGMENTS");if(V(N)){l.skippedSegments+=N;for(let B=N;B--;)h.push(null);g+=N}const G=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(G.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&lt(l,O,S),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&lt(l,O,S),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||lt(l,O,S),l.live=!1;break;case"#":(w||k)&&T.tagList.push(k?[w,k]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([O]);break;case"BITRATE":T.tagList.push([O,w]),E=parseInt(w)*1e3,V(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const M=new fe(w,l),N=new ba(M,l.dateRanges[M.ID],l.dateRangeTagCount);l.dateRangeTagCount++,N.isValid||l.skippedSegments?l.dateRanges[N.id]=N:ne.warn(`Ignoring invalid DATERANGE tag: "${w}"`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const M=new fe(w,l);"IMPORT"in M?Pc(l,M,n):tn(l,M,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?lt(l,O,S):h.length>0&&gn(l,O,S),l.startCC=y=parseInt(w);break;case"KEY":{const M=ln(w,t,l);if(M.isSupported()){if(M.method==="NONE"){D=void 0;break}D||(D={});const N=D[M.keyFormat];N!=null&&N.matches(M)||(N&&(D=ae({},D)),D[M.keyFormat]=M)}else ne.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=cn(w);break;case"MAP":{const M=new fe(w,l);if(T.duration){const N=new ni(i,c);dn(N,M,s,D),d=N,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const N=T.byteRangeEndOffset;if(N){const G=T.byteRangeStartOffset;R=`${N-G}@${G}`}else R=null;dn(T,M,s,D),d=T,L=!0}d.cc=y;break}case"SERVER-CONTROL":{I&&lt(l,O,S),I=new fe(w),l.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),l.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&lt(l,O,S);const M=new fe(w);l.partTarget=M.decimalFloatingPoint("PART-TARGET");break}case"PART":{let M=l.partList;M||(M=l.partList=[]);const N=f>0?M[M.length-1]:void 0,G=f++,B=new fe(w,l),U=new Pl(B,T,c,G,N);M.push(U),T.duration+=U.duration;break}case"PRELOAD-HINT":{const M=new fe(w,l);l.preloadHint=M;break}case"RENDITION-REPORT":{const M=new fe(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(M);break}default:ne.warn(`line parsed but not handled: ${S}`);break}}}v&&!v.relurl?(h.pop(),p-=v.duration,l.partList&&(l.fragmentHint=v)):l.partList&&(Ui(T,v,u),T.cc=y,l.fragmentHint=T,D&&fn(T,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,$=h[0],K=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&K){l.averagetargetduration=p/C;const H=K.sn;l.endSN=H!=="initSegment"?H:0,l.live||(K.endList=!0),A>0&&(qc(h,A),$&&u.unshift($))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&$&&ka(u,l),l.endCC=y,l}}function ka(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var n;if(((n=a[h])==null?void 0:n.sn)<e.startSN)break;const u=Wc(e,l,a,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function Wc(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const h=a.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let g=d;g>l;g--){const f=h[g].programDateTime;if(e>=f&&e<f+h[g].duration*1e3)return g}}return l}}}return-1}function ln(a,e,t){var s,i;const r=new fe(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&ne.error(`Invalid IV: ${r.IV}`);const u=o?st.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new At(n,u,h,d,c,r.KEYID)}function cn(a){const t=new fe(a).decimalFloatingPoint("TIME-OFFSET");return V(t)?t:null}function hn(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>rr(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function un(a,e,t){const s=e[t];s&&(a[t]=s)}function qc(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ui(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function dn(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function fn(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function lt(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function gn(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function hi(a,e){const t=e.startPTS;if(V(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function wa(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(V(h)){const E=Math.abs(h-t);a&&E>a.totalduration?n.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${a.url}`):V(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const g=e.sn;if(!a||g<a.startSN||g>a.endSN)return 0;let f;const p=g-a.startSN,y=a.fragments;for(y[p]=e,f=p;f>0;f--)hi(y[f],y[f-1]);for(f=p;f<y.length-1;f++)hi(y[f],y[f+1]);return a.fragmentHint&&hi(y[y.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,d}function jc(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;Qc(a,e,(h,u,d,g)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const f=h.cc-u.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}V(h.startPTS)&&V(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Xc(a.dateRanges,e,t));const h=a.fragments.filter(u=>u.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ui(o[u],o[u-1],h);ka(h,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const h=Ma(a,e.startSN-1);e.startCC=(c=h?.cc)!=null?c:n[0].cc}zc(a.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?wa(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Oa(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function Xc(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ae({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new ba(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[c].attr)}"`)}),r):s}function zc(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function Qc(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=c[n+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,g=u.relurl;if(d&&Zc(d,g)){e.playlistParsingError=mn(`media sequence mismatch ${u.sn}:`,a,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=mn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,a,e,h,u);return}}}}function mn(a,e,t,s,i){return new Error(`${a} ${i.url} 12 + Playlist starting @${e.startSN} 13 + ${e.m3u8} 14 + 15 + Playlist starting @${t.startSN} 16 + ${t.m3u8}`)}function Oa(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;$i(e,n)}function $i(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Fa(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ma(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function pn(a,e,t){return a?Na(a.partList,e,t):null}function Na(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ba(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Zc(a,e){return a!==e&&e?yn(a)!==yn(e):!1}function yn(a){return a.replace(/\?[^?]*$/,"")}function Jt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Jc(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function En(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Ua(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)En(t[s],a);e.fragmentHint&&En(e.fragmentHint,a),e.alignedSliding=!0}function eh(a,e){a&&($a(e,a),e.alignedSliding||Ys(e,a),!e.alignedSliding&&!e.skippedSegments&&Oa(a,e,!1))}function $a(a,e){if(!Jc(e,a))return;const t=Math.min(e.endCC,a.endCC),s=Jt(e.fragments,t),i=Jt(a.fragments,t);if(!s||!i)return;ne.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Ua(r,a)}function Ys(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=Jt(s,n),r=Jt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Jt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Ua(l,a)}function we(a,e,t){Me(a,e,t),a.addEventListener(e,t)}function Me(a,e,t){a.removeEventListener(e,t)}const th={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ur extends La{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=Q.bufferInfo(l||c,u,n.maxBufferHole),g=!d.len;if(this.log(`Media seeking to ${V(u)?u.toFixed(3):u}, state: ${h}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const f=n.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(u>f&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),g&&this.state===P.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 Dc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new or(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===P.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=P.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 s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Q.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return Q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;we(s,"seeking",this.onMediaSeeking),we(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Me(i,"seeking",this.onMediaSeeking),Me(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===P.FRAG_LOADING||!this.fragCurrent&&n===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ie.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ie.PARTIAL&&s.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,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Kt(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,cr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,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 s=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:${s?th.toString(Q.getBuffered(s)):"(detached)"})`),Te(e)){var i;if(e.type!==Y.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new lr(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),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||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Te(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&Te(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const g=this.getNextPart(d,e,s);if(g>-1){const f=d[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${d.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(Te(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.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} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),V(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==Y.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const g=d.part;this.hls.trigger(m.FRAG_LOADED,d);const f=pn(s.details,e.sn,u.index+1)||Na(l,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.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:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===Y.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?pn(c,r,n):null,h=l?l.fragment:Ma(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=He(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=Q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!V(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=Q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return Q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=Y.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(d!==-1&&d>=n?d:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ie.OK||s===Ie.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(vn(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(vn(this.config)&&e.type!==Y.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=yc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=xa(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;d=Pt(r,n,e,p)}else d=n[n.length-1];if(d){const f=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Ie.OK||p===Ie.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[f+1];d.sn<o&&this.fragmentTracker.getState(E)!==Ie.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&V(r);if(n||!o&&!r){eh(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),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 s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&V(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Te(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!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===_.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,g=d&&c===Re.RetryRequest,f=d&&!o.resolved&&l===Ue.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&Te(i)&&!i.endList&&p&&!Ia(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&h<u.maxNumRetry){var y;const E=Mi((y=t.response)==null?void 0:y.code),v=ar(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${v}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Re.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Mi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Y.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=Q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.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?"<removed>":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,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:wa(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.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===Y.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 vn(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Ga{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=sh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function sh(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var ui={exports:{}},Tn;function ih(){return Tn||(Tn=1,(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,u||c,d),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,g=u.length,f=new Array(g);d<g;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,v,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,g),!0;case 6:return y.fn.call(y.context,h,u,d,g,f),!0}for(T=1,v=new Array(E-1);T<E;T++)v[T-1]=arguments[T];y.fn.apply(y.context,v)}else{var S=y.length,x;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!v)for(x=1,v=new Array(E-1);x<E;x++)v[x-1]=arguments[x];y[T].fn.apply(y[T].context,v)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var g=t?t+l:l;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&n(this,g);else{for(var p=0,y=[],E=f.length;p<E;p++)(f[p].fn!==h||d&&!f[p].once||u&&f[p].context!==u)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(ui)),ui.exports}var rh=ih(),dr=Dl(rh);const ns="1.6.15",Wt={};function nh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ah(){const a=Wt[ns];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Wt[ns]=i,i}function oh(a){const e=Wt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wt[a]=i,i}function lh(a){const e=Wt[a||ns];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Wt[a||ns],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Ka(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function fr(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Xs(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function as(a,e){const t=e;let s=0;for(;fr(a,e);){s+=10;const i=Xs(a,e+6);s+=i,Ka(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function ch(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const g=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return ne.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Va(a,e){return a[e]===255&&(a[e+1]&246)===240}function Ha(a,e){return a[e+1]&1?7:9}function gr(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function hh(a,e){return e+5<a.length}function Ws(a,e){return e+1<a.length&&Va(a,e)}function uh(a,e){return hh(a,e)&&Va(a,e)&&gr(a,e)<=a.length-e}function dh(a,e){if(Ws(a,e)){const t=Ha(a,e);if(e+t>=a.length)return!1;const s=gr(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||Ws(a,i)}return!1}function Ya(a,e,t,s,i){if(!a.samplerate){const r=ch(e,t,s,i);if(!r)return;ae(a,r)}}function Wa(a){return 1024*9e4/a}function fh(a,e){const t=Ha(a,e);if(e+t<=a.length){const s=gr(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function qa(a,e,t,s,i){const r=Wa(a.samplerate),n=s+i*r,o=fh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,g=d+u,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+g);const p={unit:c,pts:n};return f||a.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function gh(a,e){return fr(a,e)&&Xs(a,e+6)+10<=a.length-e}function mh(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function di(a,e=0,t=1/0){return ph(a,e,t,Uint8Array)}function ph(a,e,t,s){const i=yh(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=Eh(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function yh(a){return a instanceof ArrayBuffer?a:a.buffer}function Eh(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function vh(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ve(di(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=Ve(di(a.data,3+s,n));let c;return i==="-->"?c=Ve(di(a.data,4+s+n)):c=mh(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Th(a){if(a.size<2)return;const e=Ve(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Sh(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Ve(a.data.subarray(t),!0);t+=s.length+1;const i=Ve(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Ve(a.data.subarray(1));return{key:a.type,info:"",data:e}}function xh(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Ve(a.data.subarray(t),!0);t+=s.length+1;const i=Ve(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Ve(a.data);return{key:a.type,info:"",data:e}}function Ah(a){return a.type==="PRIV"?Th(a):a.type[0]==="W"?xh(a):a.type==="APIC"?vh(a):Sh(a)}function Ih(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Xs(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const ms=10,Lh=10;function ja(a){let e=0;const t=[];for(;fr(a,e);){const s=Xs(a,e+6);a[e+5]>>6&1&&(e+=ms),e+=ms;const i=e+s;for(;e+Lh<i;){const r=Ih(a.subarray(e)),n=Ah(r);n&&t.push(n),e+=r.size+ms}Ka(a,e)&&(e+=ms)}return t}function Xa(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Rh(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function mr(a){const e=ja(a);for(let t=0;t<e.length;t++){const s=e[t];if(Xa(s))return Rh(s)}}let Ke=(function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a})({});function et(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class pr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=He(this.cachedData,e),this.cachedData=null);let s=as(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?mr(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&V(c))&&(this.basePTS=bh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ke.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else gh(e,i)?(s=as(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ke.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=He(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:et(),id3Track:o,textTrack:et()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:et(),id3Track:this._id3Track,textTrack:et()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const bh=(a,e,t)=>{if(V(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let ps=null;const _h=[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],Dh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ch=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ph=[0,1,1,4];function za(a,e,t,s,i){if(t+24>e.length)return;const r=Qa(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function Qa(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=_h[c*14+i-1]*1e3,u=Dh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,g=Ch[t][s],f=Ph[s],p=g*8*f,y=Math.floor(g*l/u+n)*f;if(ps===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ps=T?parseInt(T[1]):0}return ps&&ps<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function yr(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function Za(a,e){return e+1<a.length&&yr(a,e)}function kh(a,e){return yr(a,e)&&4<=a.length-e}function Ja(a,e){if(e+1<a.length&&yr(a,e)){const s=Qa(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||Za(a,r)}return!1}class wh extends pr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=as(e,0);let i=s?.length||0;if(Ja(e,i))return!1;for(let r=e.length;i<r;i++)if(dh(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return uh(e,t)}appendFrame(e,t,s){Ya(e,this.observer,t,s,e.manifestCodec);const i=qa(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const eo=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Oh extends pr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=to(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=as(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&mr(t)!==void 0&&eo(e,s)<16}}function to(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+g,y=e[t+5]>>3,E=e[t+5]&7,v=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,x=e.subarray(t,t+h);return a.config=v,a.channelCount=p,a.samplerate=o,a.samples.push({unit:x,pts:S}),h}class Fh extends pr{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=as(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&mr(t)!==void 0&&eo(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Ja(e,s))return ne.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return kh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return za(e,t,s,this.basePTS,this.frameIndex)}}const Mh=/\/emsg[-/]ID3/i;class Nh{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=et("video",1),n=this.audioTrack=et("audio",1),o=this.txtTrack=et("text",1);if(this.id3Track=et("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ua(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=la.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Ol(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=He(this.remainderData,e));const o=Gl(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Nr(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Nr(e,t),{videoTrack:t,audioTrack:et(),id3Track:i,textTrack:et()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=ee(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Vl(r);if(Mh.test(n.schemeIdUri)){const o=Sn(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ke.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Sn(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Ke.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Sn(a,e){return V(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class Bh{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new or(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Lt.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=ga(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class so{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,g=0;for(r===-1&&(d=0,g=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const f={data:t.subarray(d,h),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&c<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=He(f.data,t.subarray(0,h)),f.state=0))}c<i?(u=this.getNALuType(t,c),d=c,g=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const f={data:t.subarray(d,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=He(f.data,t))}return e.naluState=r,o}}class es{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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.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 s=this.word>>>32-t;if(e>32&&ne.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>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 Uh extends so{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=p;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,ir(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let v="avc1.";for(let T=0;T<3;T++){let S=E[T].toString(16);S.length<2&&(S="0"+S),v+=S}e.codec=v}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new es(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new es(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const v=h();if(u(5),f(3),h(),y(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const L=d();if(L===3&&f(1),y(),y(),f(1),g())for(c=L!==3?8:12,l=0;l<c;l++)g()&&(l<6?E(16,t):E(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(f(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),f(1);const S=d(),x=d(),D=u(1);D===0&&f(1),f(1),g()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(g()&&g())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+n),pixelRatio:A}}}class $h extends so{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,ir(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ae(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new es(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new es(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),v=[],T=[];for(let se=0;se<s;se++)v.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let se=s;se<8;se++)t.readBits(2);for(let se=0;se<s;se++)v[se]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[se]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let L=0,R=0,I=0,C=0;A&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),C+=t.readUEG());const $=t.readUEG(),K=t.readUEG(),H=t.readUEG(),O=t.readBoolean();for(let se=O?0:s;se<=s;se++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Se=0;Se<4;Se++)for(let Pe=0;Pe<(Se===3?2:6);Pe++)if(!t.readBoolean())t.readUEG();else{const Ne=Math.min(64,1<<4+(Se<<1));Se>1&&t.readEG();for(let at=0;at<Ne;at++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const M=t.readUEG();let N=0;for(let se=0;se<M;se++){let Se=!1;if(se!==0&&(Se=t.readBoolean()),Se){se===M&&t.readUEG(),t.readBoolean(),t.readUEG();let Pe=0;for(let ze=0;ze<=N;ze++){const Ne=t.readBoolean();let at=!1;Ne||(at=t.readBoolean()),(Ne||at)&&Pe++}N=Pe}else{const Pe=t.readUEG(),ze=t.readUEG();N=Pe+ze;for(let Ne=0;Ne<Pe;Ne++)t.readUEG(),t.readBoolean();for(let Ne=0;Ne<ze;Ne++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const se=t.readUEG();for(let Se=0;Se<se;Se++){for(let Pe=0;Pe<H+4;Pe++)t.readBits(1);t.readBits(1)}}let B=0,U=1,j=1,J=!0,X=1,Z=0;t.readBoolean(),t.readBoolean();let oe=!1;if(t.readBoolean()){if(t.readBoolean()){const ot=t.readUByte(),cs=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],wt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ot>0&&ot<16?(U=cs[ot-1],j=wt[ot-1]):ot===255&&(U=t.readBits(16),j=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(),oe=t.readBoolean(),oe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const wt=t.readBoolean(),me=t.readBoolean();let Ee=!1;(wt||me)&&(Ee=t.readBoolean(),Ee&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ee&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Rt=0;Rt<=s;Rt++){J=t.readBoolean();const Zs=J||t.readBoolean();let Lr=!1;Zs?t.readEG():Lr=t.readBoolean();const Rr=Lr?1:t.readUEG()+1;if(wt)for(let qt=0;qt<Rr;qt++)t.readUEG(),t.readUEG(),Ee&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(me)for(let qt=0;qt<Rr;qt++)t.readUEG(),t.readUEG(),Ee&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),B=t.readUEG())}let xe=x,Ce=D;if(A){let se=1,Se=1;S===1?se=Se=2:S==2&&(se=2),xe=x-se*R-se*L,Ce=D-Se*C-Se*I}const ye=i?["A","B","C"][i]:"",nt=o<<24|c<<16|l<<8|h;let kt=0;for(let se=0;se<32;se++)kt=(kt|(nt>>se&1)<<31-se)>>>0;let We=kt.toString(16);return n===1&&We==="2"&&(We="6"),{codecString:`hvc1.${ye}${n}.${We}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,g,f,p,y],general_level_idc:E,bit_depth:$+8,bit_depth_luma_minus8:$,bit_depth_chroma_minus8:K,min_spatial_segmentation_idc:B,chroma_format_idc:S,frame_rate:{fixed:J,fps:Z/X}},width:xe,height:Ce,pixelRatio:[U,j]}}readPPS(e){const t=new es(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 i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Le=188;class St{constructor(e,t,s,i){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=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=St.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Le*5,t-Le)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=Le)if(e[c]===71&&(t-c===Le||e[c+Le]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+Le*99,e.length-Le)+1)),r||(r=Gi(e,c)===0),r&&o>1&&(n===0&&o>2||c+Le>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:la[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=St.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=St.createTrack("audio",i),this._id3Track=St.createTrack("id3"),this._txtTrack=St.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,v=this._pmtId,T=e.length;if(this.remainderData&&(e=He(this.remainderData,e),T=e.length,this.remainderData=null),T<Le&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const S=Math.max(0,St.syncOffset(e));T-=(T-S)%Le,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let x=0;for(let A=S;A<T;A+=Le)if(e[A]===71){const L=!!(e[A+1]&64),R=Gi(e,A),I=(e[A+3]&48)>>4;let C;if(I>1){if(C=A+5+e[A+4],C===A+Le)continue}else C=A+4;switch(R){case h:L&&(u&&(r=Nt(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+Le)),u.size+=A+Le-C);break;case d:if(L){if(f&&(r=Nt(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(C,A+Le)),f.size+=A+Le-C);break;case g:L&&(p&&(r=Nt(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+Le)),p.size+=A+Le-C);break;case 0:L&&(C+=e[C]+1),v=this._pmtId=Gh(e,C);break;case v:{L&&(C+=e[C]+1);const $=Kh(e,C,this.typeSupported,s,this.observer,this.logger);h=$.videoPid,h>0&&(n.pid=h,n.segmentCodec=$.segmentVideoCodec),d=$.audioPid,d>0&&(o.pid=d,o.segmentCodec=$.segmentAudioCodec),g=$.id3Pid,g>0&&(c.pid=g),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,A=S-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=R;break}}else x++;x>0&&Ki(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=f,c.pesData=p;const D={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}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:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=Nt(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=Nt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Nt(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new Bh(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Uh:e==="hevc"&&(this.videoParser=new $h))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(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 s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=He(i.sample.unit,r);else{const g=d-u;i.sample.unit.set(r.subarray(0,u),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!Ws(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",Ki(this.observer,new Error(u),d,this.logger),!d)return}Ya(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Wa(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=qa(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!Ws(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(Za(s,n)){const c=za(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=to(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ae({},t,{type:this._videoTrack?Ke.emsg:Ke.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Gi(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Gh(a,e){return(a[e+10]&31)<<8|a[e+11]}function Kh(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=Gi(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){fi("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){fi("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){fi("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,g=u;for(;g>2;){a[d]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3"));const p=a[d+1]+2;d+=p,g-=p}}break;case 194:case 135:return Ki(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function Ki(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function fi(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Nt(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=He(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class Vh{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 yt=Math.pow(2,32)-1;class b{static init(){b.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 b.types)b.types.hasOwnProperty(e)&&(b.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]),s=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]);b.HDLR_TYPES={video:t,audio:s};const i=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]);b.STTS=b.STSC=b.STCO=r,b.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),b.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),b.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),b.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);b.FTYP=b.box(b.types.ftyp,n,c,n,o),b.DINF=b.box(b.types.dinf,b.box(b.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return b.box(b.types.hdlr,b.HDLR_TYPES[e])}static mdat(e){return b.box(b.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(yt+1)),i=Math.floor(t%(yt+1));return b.box(b.types.mdhd,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return b.box(b.types.mdia,b.mdhd(e.timescale||0,e.duration||0),b.hdlr(e.type),b.minf(e))}static mfhd(e){return b.box(b.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"?b.box(b.types.minf,b.box(b.types.smhd,b.SMHD),b.DINF,b.stbl(e)):b.box(b.types.minf,b.box(b.types.vmhd,b.VMHD),b.DINF,b.stbl(e))}static moof(e,t,s){return b.box(b.types.moof,b.mfhd(e),b.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=b.trak(e[t]);return b.box.apply(null,[b.types.moov,b.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(b.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=b.trex(e[t]);return b.box.apply(null,[b.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(yt+1)),i=Math.floor(t%(yt+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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 b.box(b.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return b.box(b.types.sdtp,s)}static stbl(e){return b.box(b.types.stbl,b.stsd(e),b.box(b.types.stts,b.STTS),b.box(b.types.stsc,b.STSC),b.box(b.types.stsz,b.STSZ),b.box(b.types.stco,b.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=b.box(b.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return b.box(b.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,l>>8&255,l&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]),o,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&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 b.box(b.types.mp4a,b.audioStsd(e),b.box(b.types.esds,b.esds(e)))}static mp3(e){return b.box(b.types[".mp3"],b.audioStsd(e))}static ac3(e){return b.box(b.types["ac-3"],b.audioStsd(e),b.box(b.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return b.box(b.types.stsd,b.STSD,b.mp4a(e));if(t==="ac3"&&e.config)return b.box(b.types.stsd,b.STSD,b.ac3(e));if(t==="mp3"&&e.codec==="mp3")return b.box(b.types.stsd,b.STSD,b.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return b.box(b.types.stsd,b.STSD,b.avc1(e));if(t==="hevc"&&e.vps)return b.box(b.types.stsd,b.STSD,b.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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(yt+1)),o=Math.floor(s%(yt+1));return b.box(b.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,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=b.sdtp(e),i=e.id,r=Math.floor(t/(yt+1)),n=Math.floor(t%(yt+1));return b.box(b.types.traf,b.box(b.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),b.box(b.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),b.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,b.box(b.types.trak,b.tkhd(e),b.mdia(e))}static trex(e){const t=e.id;return b.box(b.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 s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return b.box(b.types.trun,n)}static initSegment(e){b.types||b.init();const t=b.moov(e);return He(b.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let p=0;p<s[f].length;p+=1)n+=2+s[f][p].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),n),n+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),n),n+=2,o.set(s[f][p],n),n+=s[f][p].length}const l=b.box(b.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return b.box(b.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,h>>8&255,h&255,u>>8&255,u&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]),l,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}b.types=void 0;b.HDLR_TYPES=void 0;b.STTS=void 0;b.STSC=void 0;b.STCO=void 0;b.STSZ=void 0;b.VMHD=void 0;b.SMHD=void 0;b.STSD=void 0;b.FTYP=void 0;b.DINF=void 0;const io=9e4;function Er(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Hh(a,e,t=1,s=!1){return Er(a,e,1/t,s)}function Xt(a,e=!1){return Er(a,1e3,1/io,e)}function Yh(a,e=1){return Er(a,io,1/e)}function xn(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const Wh=10*1e3,qh=1024,jh=1152,Xh=1536;let Bt=null,gi=null;function An(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class Cs extends Ye{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Bt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bt=n?parseInt(n[1]):0}if(gi===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);gi=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&&xn(t)} > ${e&&xn(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 s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=$e(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,g,f,p=r,y=r;const E=e.pid>-1,v=t.pid>-1,T=t.samples.length,S=e.samples.length>0,x=o&&T>0||T>1;if((!E||S)&&(!v||x)||this.ISGenerated||o){if(this.ISGenerated){var A,L,R,I;const H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((A=t.pixelRatio)==null?void 0:A[0])!==((L=H.pixelRatio)==null?void 0:L[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((I=H.pixelRatio)==null?void 0:I[1]))||!H&&x||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const C=this.isVideoContiguous;let $=-1,K;if(x&&($=zh(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,$>0){this.warn(`Dropped ${$} out of ${T} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice($),t.dropped+=$,y+=(t.samples[0].pts-H)/t.inputTimeScale,K=y}else $===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(S&&x){const H=this.getVideoStartPts(t.samples),w=($e(e.samples[0].pts,H)-H)/t.inputTimeScale;p+=Math.max(0,w),y+=Math.max(0,-w)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,v||x||c===Y.AUDIO?y:void 0),x){const H=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,y,C,H)}}else x&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=$,l.independent=$!==-1,l.firstKeyFramePTS=K)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=ro(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=no(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=$e(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,g,f,p=-1;if(h&&(d=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):b.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?d=g=this.computeInitPts(r[0].pts,f,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:b.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(n),E=$e(n[0].dts,y),v=this.computeInitPts(E,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,v),d=Math.min(d,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:c,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,v=!1;if(!s||u===null){const B=h+t*r,U=n[0].pts-$e(n[0].dts,n[0].pts);Bt&&u!==null&&Math.abs(B-U-(u+h))<15e3?s=!0:u=B-U-h}const T=u+h;for(let B=0;B<c;B++){const U=n[B];U.pts=$e(U.pts,T),U.dts=$e(U.dts,T),U.dts<n[B>0?B-1:B].dts&&(v=!0)}v&&n.sort(function(B,U){const j=B.dts-U.dts,J=B.pts-U.pts;return j||J}),f=n[0].dts,p=n[n.length-1].dts;const S=p-f,x=S?Math.round(S/(c-1)):g||e.inputTimeScale/30;if(s){const B=f-T,U=B>x,j=B<-1;if((U||j)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Xt(B,!0)} ms (${B}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Xt(-B,!0)} ms (${B}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||T>=n[0].pts||Bt)){f=T;const J=n[0].pts-B;if(U)n[0].dts=f,n[0].pts=J;else{let X=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>J&&X);Z++){const oe=n[Z].pts;if(n[Z].dts-=B,n[Z].pts-=B,Z<n.length-1){const he=n[Z+1].pts,xe=n[Z].pts,Ce=he<=xe,ye=he<=oe;X=Ce==ye}}}this.log(`Video: Initial PTS/DTS adjusted: ${Xt(J,!0)}/${Xt(f,!0)}, delta: ${Xt(B,!0)} ms`)}}f=Math.max(0,f);let D=0,A=0,L=f;for(let B=0;B<c;B++){const U=n[B],j=U.units,J=j.length;let X=0;for(let Z=0;Z<J;Z++)X+=j[Z].data.length;A+=X,D+=J,U.length=X,U.dts<L?(U.dts=L,L+=x/4|0||1):L=U.dts,y=Math.min(U.pts,y),E=Math.max(U.pts,E)}p=n[c-1].dts;const R=A+4*D+8;let I;try{I=new Uint8Array(R)}catch(B){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:B,bytes:R,reason:`fail allocating video mdat ${R}`});return}const C=new DataView(I.buffer);C.setUint32(0,R),I.set(b.types.mdat,4);let $=!1,K=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let B=0;B<c;B++){const U=n[B],j=U.units;let J=0;for(let oe=0,he=j.length;oe<he;oe++){const xe=j[oe],Ce=xe.data,ye=xe.data.byteLength;C.setUint32(d,ye),d+=4,I.set(Ce,d),d+=ye,J+=4+ye}let X;if(B<c-1)g=n[B+1].dts-U.dts,X=n[B+1].pts-U.pts;else{const oe=this.config,he=B>0?U.dts-n[B-1].dts:x;if(X=B>0?U.pts-n[B-1].pts:x,oe.stretchShortVideoTrack&&this.nextAudioTs!==null){const xe=Math.floor(oe.maxBufferHole*r),Ce=(i?y+i*r:this.nextAudioTs+h)-U.pts;Ce>xe?(g=Ce-he,g<0?g=he:$=!0,this.log(`It is approximately ${Ce/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=he}else g=he}const Z=Math.round(U.pts-U.dts);K=Math.min(K,g),O=Math.max(O,g),H=Math.min(H,X),w=Math.max(w,X),o.push(An(U.key,g,J,Z))}if(o.length){if(Bt){if(Bt<70){const B=o[0].flags;B.dependsOn=2,B.isNonSync=0}}else if(gi&&w-H<O-K&&x/O<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let B=f;for(let U=0,j=o.length;U<j;U++){const J=B+o[U].duration,X=B+o[U].cts;if(U<j-1){const Z=J+o[U+1].cts;o[U].duration=Z-X}else o[U].duration=U?o[U-1].duration:x;o[U].cts=0,B=J}}}g=$||!g?x:g;const k=p+g;this.nextVideoTs=u=k-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const G={data1:b.moof(e.sequenceNumber++,f,ae(e,{samples:o})),data2:I,startPTS:(y-h)/r,endPTS:(E+g-h)/r,startDTS:(f-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,G}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return jh;case"ac3":return Xh;default:return qh}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const v=u.baseTime*n/u.timescale,T=v+t*n;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(T-(E+v))<9e3||Math.abs($e(p[0].pts,T)-(E+v))<20*h),p.forEach(function(w){w.pts=$e(w.pts,T)}),!s||E<0){const w=p.length;if(p=p.filter(k=>k.pts>=0),w!==p.length&&this.warn(`Removed ${p.length-w} of ${w} samples (initPTS ${v} / ${n})`),!p.length)return;r===0?E=0:i&&!f?E=Math.max(0,T-v):E=p[0].pts-v}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let k=0,M=E+v;k<p.length;k++){const N=p[k],G=N.pts,B=G-M,U=Math.abs(1e3*B/n);if(B<=-w*h&&f)k===0&&(this.warn(`Audio frame @ ${(G/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*B/n)} ms.`),this.nextAudioTs=E=G-v,M=G);else if(B>=w*h&&U<Wh&&f){let j=Math.round(B/h);for(M=G-j*h;M<0&&j&&h;)j--,M+=h;k===0&&(this.nextAudioTs=E=M-v),this.warn(`Injecting ${j} audio frames @ ${((M-v)/n).toFixed(3)}s due to ${Math.round(1e3*B/n)} ms gap.`);for(let J=0;J<j;J++){let X=Vh.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=N.unit.subarray()),p.splice(k,0,{unit:X,pts:M}),M+=h,k++}}N.pts=M,M+=h}}let S=null,x=null,D,A=0,L=p.length;for(;L--;)A+=p[L].unit.byteLength;for(let w=0,k=p.length;w<k;w++){const M=p[w],N=M.unit;let G=M.pts;if(x!==null){const U=g[w-1];U.duration=Math.round((G-x)/c)}else if(s&&e.segmentCodec==="aac"&&(G=E+v),S=G,A>0){A+=y;try{D=new Uint8Array(A)}catch(U){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(b.types.mdat,4))}else return;D.set(N,y);const B=N.byteLength;y+=B,g.push(An(!0,l,B,0)),x=G}const R=g.length;if(!R)return;const I=g[g.length-1];E=x-v,this.nextAudioTs=E+c*I.duration;const C=d?new Uint8Array(0):b.moof(e.sequenceNumber++,S/c,ae({},e,{samples:g}));e.samples=[];const $=(S-v)/n,K=this.nextAudioTs/n,O={data1:C,data2:D,startPTS:$,endPTS:K,startDTS:$,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,O}}function $e(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function zh(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function ro(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=$e(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=$e(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function no(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=$e(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class Qh extends Ye{constructor(e,t,s,i){super("passthrough-remuxer",i),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,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=ua(e);if(t)Bl(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=In(r,le.AUDIO,this)),n&&(i=In(n,le.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};V(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=$l(d,f,this),y=f.audio?p[f.audio.id]:null,E=f.video?p[f.video.id]:null,v=ys(E,1/0),T=ys(y,1/0),S=ys(E,0,!0),x=ys(y,0,!0);let D=r,A=0;const L=y&&(!E||!l&&T<v||l&&l.trackId===f.audio.id),R=L?y:E;if(R){const M=R.timescale,N=R.start-r*M,G=L?f.audio.id:f.video.id;D=R.start/M,A=L?x-T:S-v,(n||!l)&&(Zh(l,D,r,A)||M!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${N/M} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${N}/${M}) trackId: ${G}`),l=null,g.initPTS=N,g.timescale=M,g.trackId=G)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=D,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const I=D-l.baseTime/l.timescale,C=I+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const $=!!f.audio,K=!!f.video;let H="";$&&(H+="audio"),K&&(H+="video");const O=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),w={data1:d,startPTS:I,startDTS:I,endPTS:C,endDTS:C,type:H,hasAudio:$,hasVideo:K,nb:1,dropped:0,encrypted:O};u.audio=$&&!K?w:void 0,u.video=K?w:void 0;const k=E?.sampleCount;if(k){const M=E.keyFrameIndex,N=M!==-1;w.nb=k,w.dropped=M===0||this.isVideoContiguous?0:N?M:k,w.independent=N,w.firstKeyFrame=M,N&&E.keyFrameStart&&(w.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${M}/${k} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return u.initSegment=g,u.id3=ro(s,r,l,l),i.samples.length&&(u.text=no(i,r,l)),u}}function ys(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function Zh(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function In(a,e,t){const s=a.codec;return s&&s.length>4?s:e===le.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Bs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let ut;try{ut=self.performance.now.bind(self.performance)}catch{ut=Date.now}const Ps=[{demux:Nh,remux:Qh},{demux:St,remux:Cs},{demux:wh,remux:Cs},{demux:Fh,remux:Cs}];Ps.splice(2,0,{demux:Oh,remux:Cs});class Ln{constructor(e,t,s,i,r,n){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=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=ut();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:v,initSegmentData:T}=c,S=Jh(n,t);if(S&&Kt(S.method)){const L=this.getDecrypter(),R=cr(S.method);if(L.isSync()){let I=L.softwareDecrypt(n,S.key.buffer,S.iv.buffer,R);if(s.part>-1){const $=L.flush();I=$&&$.buffer}if(!I)return r.executeEnd=ut(),mi(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(n,S.key.buffer,S.iv.buffer,R).then(I=>{const C=this.push(I,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const L=this.configureTransmuxer(n);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),r.executeEnd=ut(),mi(s)}(h||u||f||x)&&this.resetInitSegment(T,p,y,v,t),(h||f||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(n,S,g,d,s);this.asyncResult=os(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=ut(),D}flush(e){const t=e.transmuxing;t.executeStart=ut();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=ut();const u=[mi(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return os(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===Y.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=ut()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=Ps.length;u<d;u++){var n;if((n=Ps[u].demux)!=null&&n.probe(e,this.logger)){r=Ps[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new or(this.config)),e}}function Jh(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const mi=a=>({remuxResult:{},chunkMeta:a});function os(a){return"then"in a&&a.then instanceof Function}class eu{constructor(e,t,s,i,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=s,this.duration=i,this.defaultInitPts=r||null}}class tu{constructor(e,t,s,i,r,n){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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Rn=0;class ao{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rn++,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 l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=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:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new dr,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=$r(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||nh()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=oh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=ah());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ce(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rn++;const t=this.hls.config,s=$r(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),lh(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,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=n?n.start:r.start,y=r.decryptdata,E=this.frag,v=!(E&&r.cc===E.cc),T=!(E&&l.level===E.level),S=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=S===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!T&&(S===1||S===0&&(x===1||D&&x<=0)),L=self.performance.now();(T||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=L),n&&(x||!A)&&(n.stats.parsing.start=L);const R=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),I=new tu(v,A,c,T,p,R);if(!A||v||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Y.MAIN?"level":"track"}: ${l.level} id: ${l.id} 17 + discontinuity: ${v} 18 + trackSwitch: ${T} 19 + contiguous: ${A} 20 + accurateTimeOffset: ${c} 21 + timeOffset: ${p} 22 + initSegmentChange: ${R}`);const C=new eu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(f){const C=f.push(e,y,l,I);os(C)?C.then($=>{this.handleTransmuxComplete($)}).catch($=>{this.transmuxerError($,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);os(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const bn=100;class su extends ur{constructor(e,t,s){super(e,t,s,"audio-stream-controller",Y.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:s,initPTS:i,timescale:r,trackId:n}){if(s===Y.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=xa(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(bn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=P.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:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,le.AUDIO,Y.AUDIO));const h=this.getFwdBufferInfo(l,Y.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(u>=d&&!this.switchingTrack&&y<g[g.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,Y.MAIN,d)),!E){this.bufferFlushed=!0;return}let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Te(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ie.OK&&(this.mainFragLoading=v=null),v&&Te(v))){if(E.start>v.end){const S=this.fragmentTracker.getFragAtPos(y,Y.MAIN);S&&S.end>v.end&&(v=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(E.start>v.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new rs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(bn),this.state=P.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||($a(r,l),r.alignedSliding||Ys(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new ao(this.hls,Y.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,E=y!==-1,v=new lr(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,f,u,"",s,i,h.totalduration,!1,v,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ga,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Y.MAIN&&Te(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==Y.AUDIO){!this.audioOnly&&s.type===Y.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Te(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,re({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===te.AUDIO_TRACK&&(this.state=P.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,Y.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:g,id3:f,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=d;l&&(l.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),c.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(d,c,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=ae({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=ae({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=Y.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===Ie.NOT_LOADED||i===Ie.PARTIAL){var r;if(!Te(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=P.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Ys(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;Ct({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,Dt)||($s(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,re({},e))}}class vr extends Ye{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,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Gr(s);return new Kr(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){jc(s,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=t;T.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,g=(i.edge-d)*1e3,f=Fa(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,D=x!==-1,A=T===S;D?A?(y=S+1,E=v?0:x):(y=T,E=v?x+1:i.maxPartIndex):y=S+1;const L=i.age,R=L+i.ageHeader;let I=Math.min(R-i.partTarget,i.targetduration*1.5);if(I>0){if(R>i.targetduration*3)this.log(`Playlist last advanced ${L.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&R-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;else{const C=Math.floor(I/i.targetduration);if(y+=C,E!==void 0){const $=Math.round(I%i.targetduration/i.partTarget);E+=$}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${I} skip sn ${C} to part ${E}`)}i.tuneInGoal=I}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),v||!A){i.requestScheduled=n,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Gr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=_s.No),new Kr(s,i,r)}checkRetry(e){const t=e.details,s=Gs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Re.RetryRequest||!i.resolved&&r===Re.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=ar(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function oo(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!ls(a[t].attrs,e[t].attrs))return!1;return!0}function ls(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function Vi(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class iu extends vr{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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=tt(c,o,Dt);if(d>-1)r=o[d];else{const g=tt(c,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var n;const d=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===te.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Ct(e,i,Dt))return i;const r=tt(e,this.tracksInGroup,Dt);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=mc(e,t.levels,s,n,Dt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=tt(e,s);if(n>-1)return s[n]}}}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 s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,re({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Ct(e,i,Dt)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(Ct({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},h,Dt))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ls(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&$s(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class ru{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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 i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.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?"<destroyed>":` 23 + ${this.list("video")} 24 + ${this.list("audio")} 25 + ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const _n=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,lo="HlsJsTrackRemovedError";class nu extends Error{constructor(e){super(e),this.name=lo}}class au extends Ye{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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,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:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=_l(It(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 s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ae(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ae({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=It(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Dn(s),ou(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) 26 + required tracks: ${ce(s,(c,l)=>c==="initSegment"?void 0:l)}; 27 + transfer tracks: ${ce(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!ra(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,g=h.id;if(d.hasFragments(g)||d.hasParts(g)){const y=Q.getBuffered(u);d.detectEvictedFragments(l,y,g,null,!0)}const f=pi(l),p=[l,u];this.sourceBuffers[f]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&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}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Dn(i),i.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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[pi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ru(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:g,levelCodec:f,container:p,metadata:y,supplemental:E}=u;let v=i[c];const T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],S=T!=null&&T.buffer?T:v,x=S?.pendingCodec||S?.codec,D=S?.levelCodec;v||(v=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:E,container:p,levelCodec:f,metadata:y,id:d});const A=bs(x,D),L=A?.replace(_n,"$1");let R=bs(g,f);const I=(h=R)==null?void 0:h.replace(_n,"$1");R&&A&&L!==I&&(c.slice(0,5)==="audio"&&(R=Bs(R,this.appendSource)),this.log(`switching codec ${x} to ${R}`),R!==(v.pendingCodec||v.codec)&&(v.pendingCodec=R),v.container=p,this.appendChangeType(c,p,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,Y.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&Q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,Y.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:g}=o,f=self.performance.now();u.start=f;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);const E=s.audio;let v=!1;r==="audio"&&E?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,S=T?.buffer;if(S&&d!=="initSegment"){const A=c||o,L=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const I=A.start+A.duration*.05,C=S.buffered,$=this.currentOp("video");!C.length&&!$?this.blockAudio(A):!$&&!Q.isBuffered(S,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(A)}else if(r==="video"){const R=A.end;if(L){const I=L.frag.start;(R>I||R<this.lastVideoAppendEnd||Q.isBuffered(S,I))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const L=(A=this.tracks[r])==null?void 0:A.buffer;L&&(v?this.updateTimestampOffset(L,x,.1,r,d,g):h!==void 0&&V(h)&&this.updateTimestampOffset(L,h,1e-6,r,d,g)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const L={};this.sourceBuffers.forEach(([R,I])=>{R&&(L[R]=Q.getBuffered(I))}),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:o,part:c,chunkMeta:l,parent:o.type,timeRanges:L})},onError:A=>{var L;const R={type:W.MEDIA_ERROR,parent:o.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},I=(L=this.media)==null?void 0:L.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)R.details=_.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)R.errorAction=Gt(!0);else if(A.name===lo&&this.sourceBufferCount===0)R.errorAction=Gt(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||I)&&(R.fatal=!0)}this.hls.trigger(m.ERROR,R)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===Y.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[le.AUDIOVIDEO]?r.push("audiovideo"):(n[le.AUDIO]&&r.push("audio"),n[le.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,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 s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.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===_.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;V(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(V(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(V(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=Q.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=Q.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return V(r)?{duration:r}:null;const n=this.media.duration,o=V(s.duration)?s.duration:0;return i>o&&i>n||!V(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(V(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ce(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.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:W.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ce(o)}`);try{const h=s.addSourceBuffer(l),u=pi(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&ss(s,"video")&&(i=zl(i,s));const r=bs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Bs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=V(i.duration)?i.duration:1/0,l=V(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new nu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.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:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Dn(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function ou(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function pi(a){return a==="audio"?1:0}class Tr{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 s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&V(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Tr.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const lu={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Fe=lu,cu={HLS:"h"},hu=cu;class it{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof it?s:new it(s))),this.value=e,this.params=t}}const uu="Dict";function du(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function fu(a,e,t,s){return new Error(`failed to ${a} "${du(e)}" as ${t}`,{cause:s})}function rt(a,e,t){return fu("serialize",a,e,t)}class co{constructor(e){this.description=e}}const Cn="Bare Item",gu="Boolean";function mu(a){if(typeof a!="boolean")throw rt(a,gu);return a?"?1":"?0"}function pu(a){return btoa(String.fromCharCode(...a))}const yu="Byte Sequence";function Eu(a){if(ArrayBuffer.isView(a)===!1)throw rt(a,yu);return`:${pu(a)}:`}const vu="Integer";function Tu(a){return a<-999999999999999||999999999999999<a}function ho(a){if(Tu(a))throw rt(a,vu);return a.toString()}function Su(a){return`@${ho(a.getTime()/1e3)}`}function uo(a,e){if(a<0)return-uo(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const xu="Decimal";function Au(a){const e=uo(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rt(a,xu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Iu="String",Lu=/[\x00-\x1f\x7f]+/;function Ru(a){if(Lu.test(a))throw rt(a,Iu);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function bu(a){return a.description||a.toString().slice(7,-1)}const _u="Token";function Pn(a){const e=bu(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rt(e,_u);return e}function Hi(a){switch(typeof a){case"number":if(!V(a))throw rt(a,Cn);return Number.isInteger(a)?ho(a):Au(a);case"string":return Ru(a);case"symbol":return Pn(a);case"boolean":return mu(a);case"object":if(a instanceof Date)return Su(a);if(a instanceof Uint8Array)return Eu(a);if(a instanceof co)return Pn(a);default:throw rt(a,Cn)}}const Du="Key";function Yi(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw rt(a,Du);return a}function Sr(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${Yi(e)}`:`;${Yi(e)}=${Hi(t)}`).join("")}function fo(a){return a instanceof it?`${Hi(a.value)}${Sr(a.params)}`:Hi(a)}function Cu(a){return`(${a.value.map(fo).join(" ")})${Sr(a.params)}`}function Pu(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw rt(a,uu);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof it||(r=new it(r));let n=Yi(i);return r.value===!0?n+=Sr(r.params):(n+="=",Array.isArray(r.value)?n+=Cu(r):n+=fo(r)),n}).join(`,${s}`)}function go(a,e){return Pu(a,e)}const Ze="CMCD-Object",pe="CMCD-Request",bt="CMCD-Session",Et="CMCD-Status",ku={br:Ze,ab:Ze,d:Ze,ot:Ze,tb:Ze,tpb:Ze,lb:Ze,tab:Ze,lab:Ze,url:Ze,pb:pe,bl:pe,tbl:pe,dl:pe,ltc:pe,mtp:pe,nor:pe,nrr:pe,rc:pe,sn:pe,sta:pe,su:pe,ttfb:pe,ttfbb:pe,ttlb:pe,cmsdd:pe,cmsds:pe,smrt:pe,df:pe,cs:pe,ts:pe,cid:bt,pr:bt,sf:bt,sid:bt,st:bt,v:bt,msd:bt,bs:Et,bsd:Et,cdn:Et,rtp:Et,bg:Et,pt:Et,ec:Et,e:Et},wu={REQUEST:pe};function Ou(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function Fu(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?Ou(e):{};return s.reduce((r,n)=>{var o;const c=ku[n]||i[n]||wu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function Mu(a){return["ot","sf","st","e","sta"].includes(a)}function Nu(a){return typeof a=="number"?V(a):a!=null&&a!==""&&a!==!1}const mo="event";function Bu(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const ks=a=>Math.round(a),Wi=(a,e)=>Array.isArray(a)?a.map(t=>Wi(t,e)):a instanceof it&&typeof a.value=="string"?new it(Wi(a.value,e),a.params):(e.baseUrl&&(a=Bu(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Es=a=>ks(a/100)*100,Uu=(a,e)=>{let t=a;return e.version>=2&&(a instanceof it&&typeof a.value=="string"?t=new it([a]):typeof a=="string"&&(t=[a])),Wi(t,e)},$u={br:ks,d:ks,bl:Es,dl:Es,mtp:Es,nor:Uu,rtp:Es,tb:ks},po="request",yo="response",xr=["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"],Gu=["e"],Ku=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zs(a){return Ku.test(a)}function Vu(a){return xr.includes(a)||Gu.includes(a)||zs(a)}const Eo=["d","dl","nor","ot","rtp","su"];function Hu(a){return xr.includes(a)||Eo.includes(a)||zs(a)}const Yu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Wu(a){return xr.includes(a)||Eo.includes(a)||Yu.includes(a)||zs(a)}const qu=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ju(a){return qu.includes(a)||zs(a)}const Xu={[yo]:Wu,[mo]:Vu,[po]:Hu};function vo(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||po,r=s===1?ju:Xu[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===yo||i===mo;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ae({},$u,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const g=l[u];if(typeof g=="function"&&(d=g(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!V(d)&&(d=Date.now()),Nu(d)&&(Mu(u)&&typeof d=="string"&&(d=new co(d)),t[u]=d))}),t}function zu(a,e={}){const t={};if(!a)return t;const s=vo(a,e),i=Fu(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=go(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function Qu(a,e,t){return ae(a,zu(e,t))}const Zu="CMCD";function Ju(a,e={}){return a?go(vo(a,e),{whitespace:!1}):""}function ed(a,e={}){if(!a)return"";const t=Ju(a,e);return encodeURIComponent(t)}function td(a,e={}){if(!a)return"";const t=ed(a,e);return`${Zu}=${t}`}const kn=/CMCD=[^&#]+/;function sd(a,e,t){const s=td(e,t);if(!s)return a;if(kn.test(a))return a.replace(kn,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class id{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=i=>{try{this.apply(i,{ot:Fe.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===Fe.VIDEO||c===Fe.AUDIO||c==Fe.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.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 s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:hu.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ae(t,this.createData());const s=t.ot===Fe.INIT||t.ot===Fe.VIDEO||t.ot===Fe.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Qu(e.headers,t,r)):e.url=sd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Fe.TIMED_TEXT;if(e.sn==="initSegment")return Fe.INIT;if(t==="audio")return Fe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Fe.VIDEO:Fe.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Fe.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Fe.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const rd=3e5;class nd extends Ye{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===Re.SendAlternateToPenaltyBox&&s.flags===Ue.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===_.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ce(r)} penalized: ${ce(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>rd&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ba(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===te.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===te.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new fe(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=To(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new rs({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${n}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${n}`);return p});t.push(...l),wn(this.audioTracks,s,c,n),wn(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const v={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,v),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wn(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ae({},n);return o.details=void 0,o.attrs=new fe(o.attrs),o.url=o.attrs.URI=To(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function To(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Vt extends Ye{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=Vt.CDMCleanupPromise?[Vt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Qt(this.config));const o=n.map(li).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=Ds(n);if(s!=="sinf"||o!==ge.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=Ae(new Uint8Array(i)),f=hr(JSON.parse(g).sinf),p=fa(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}const l=be(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let g=0;g<u.length;g++){const f=u[g],p=f.decryptdata;if(!p.keyId)continue;const y=be(p.keyId);if(Vs(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},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:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===ge.WIDEVINE&&s)return s}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,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Be?o(u):o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Ca===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=Uc(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ce(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${be(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=vs(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${be(e.decryptdata.keyId||[])} 28 + } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>li(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=li(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Qt(this.config),s=e.map(Ds).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=ad(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=vs(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=On(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Be){const c=re({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Be(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Be){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${be(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=vs(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ds(e.keyFormat),r=i?[i]:Qt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Qt(this.config)),e.length===0)throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const f=n.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=vs(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new dr,h=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(v=>{l.eventNames().length?l.emit("error",v):this.handleError(v)}):y==="license-release"?e.keySystem===ge.FAIRPLAY&&this.updateKeySession(e,Bi("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${y}"`)},u=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=On(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(S=>y[S]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ce(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let v=y[o];if(v)u(v,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",u(v,e)},1e3)),this.log(`No status for keyId ${o} (${ce(y)}).`)}};we(e.mediaKeysSession,"message",h),we(e.mediaKeysSession,"keystatuseschange",d);const g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===ge.PLAYREADY&&r.length===16){const o=be(r);t[o]=s,_a(r)}const n=be(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{n(d.data)},onError:(d,g,f,p)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:re({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Bi(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==ge.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,we(s,"encrypted",this.onMediaEncrypted),we(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Me(e,"encrypted",this.onMediaEncrypted),Me(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 s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,At.clearKeyUriToKeyIdMap();const r=i.length;Vt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).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 s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${be(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(Gc(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Vt.CDMCleanupPromise=void 0;function vs(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return be(a.keyId)}function ad(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Be 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 On(a,e){const t=a==="output-restricted",s=t?_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Be({type:W.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class od{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 s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,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 So(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function xo(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ne.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){ne.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function $t(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function qi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=cd(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function ld(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function cd(a,e,t){const s=[],i=ld(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ws(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class hd extends vr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ws(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-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 s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;ws(s.textTracks).forEach(n=>{$t(n)})}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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=tt(o,n);if(h>-1)r=n[h];else{const u=tt(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||Ct(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(Vi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===te.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Ct(e,s))return s;const i=tt(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=tt(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 s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ws(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>Vi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!V(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function ud(){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,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function ts(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Ht=.025;let qs=(function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a})({});function dd(a,e,t){return`${a.identifier}-${t+1}-${ts(e)}`}class fd{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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 yi(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,s=yi(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=V(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 yi(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)<Ht))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?qs.Range:qs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return gd(this)}}function yi(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Ht)?e.start:e.start+e.duration}function Ao(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Ei(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function gd(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function Ut(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class md{constructor(e,t,s,i){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=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,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=Ao(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 s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=Q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=Q.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 s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ut(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fn=.033;class pd extends Ye{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,g=h.cue.pre,f=h.cue.post;if(u&&!g)return-1;if(g&&!u||d&&!f)return 1;if(f&&!d)return-1;if(!u&&!g&&!d&&!f){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new fd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,g=h.cue.post,f=e[u-1]||null,p=h.appendInPlace,y=g?r:h.startOffset,E=h.duration,v=h.timelineOccupancy===qs.Range?E:0,T=h.resumptionOffset,S=f?.startTime===y,x=y+h.cumulativeDuration;let D=p?x+E:y+T;if(d||!g&&y<=0){const L=l;l+=v,h.timelineStart=x;const R=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:R,end:n},integrated:{start:L,end:l}})}else if(y<=r){if(!S){const I=y-c;if(I>Fn){const C=c,$=l;l+=I;const K=n;n+=I;const H={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+I,playout:{start:K,end:n},integrated:{start:$,end:l}};s.push(H)}else I>0&&f&&(f.cumulativeDuration+=I,s[s.length-1].end=y)}g&&(D=x),h.timelineStart=x;const L=l;l+=v;const R=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:R,end:n},integrated:{start:L,end:l}})}else return;const A=h.resumeTime;g||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const g=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:g,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Pt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Fn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=V(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Ht?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=Pt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Ht+h||Math.abs(l.end-s)<Ht+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function qe(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class yd{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ao(s,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){const v=this.assignAssetListError(e,_.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,v);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,g,f,p)=>{const y=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,_.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Mn(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function Ts(a,e){return`[${a}] Advancing timeline position to ${e}`}class Ed extends Ye{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} 29 + Schedule: ${c.map(p=>qe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,g=null;n&&(d=this.updateItem(n,this.timelinePos),this.itemsMatch(n,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(v){Math.abs(E)>Ht&&this.warn(`${v} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(d,n),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new yd(e),this.schedule=new pd(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){Me(e,"play",this.onPlay),Me(e,"pause",this.onPause),Me(e,"seeking",this.onSeeking),Me(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;we(s,"seeking",this.onSeeking),we(s,"timeupdate",this.onTimeupdate),we(s,"play",this.onPlay),we(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),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,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,g,f,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==qs.Point){const v=s(g);v?.interstitial===E&&(y+=v.assetItem.startOffset+v[p])}}else{const v=f==="bufferedPos"?n():e[f];y+=v-u.start}return y}return 0},r=(u,d)=>{var g;if(u!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(u),y=(f=e.schedule.items)==null?void 0:f[p];if(y){const E=y[d].start-y.start;return u+E}}return u},n=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[u])||0},c=(u,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),v=(f=e.schedule.items)==null?void 0:f[E],T=e.getBufferingPlayer(),S=T?.interstitial,x=S?.appendInPlace,D=y&&e.itemsMatch(y,v);if(y&&(x||D)){const A=s(e.playingAsset),L=A?.media||e.primaryMedia;if(L){const R=d==="primary"?L.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),I=u-R,C=(x?R:L.currentTime)+I;if(C>=0&&(!A||x||C<=A.duration)){L.currentTime=C;return}}}if(v){let A=u;if(d!=="primary"){const R=v[d].start,I=u-R;A=v.start+I}const L=!e.isInterstitial(v);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(L||v.event.appendInPlace)){const R=e.media||(x?T?.media:null);R&&(R.currentTime=A)}else if(y){const R=e.findItemIndex(y);if(E>R){const C=e.schedule.findJumpRestrictedIndex(R+1,E);if(C>R){e.setSchedulePosition(C);return}}let I=0;if(L)e.timelinePos=A,e.checkBuffer();else{const C=v.event.assetList,$=u-(v[d]||v).start;for(let K=C.length;K--;){const H=C[K];if(H.duration&&$>=H.startOffset&&$<H.startOffset+H.duration){I=K;break}}}e.setSchedulePosition(E,I)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var g;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),g=e.effectivePlayingItem;g&&g===d&&c(u+g.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return n()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(u);if(d.appendInPlace){const f=u.playout.start+u.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!V(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ce(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),h=`${f}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ce(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(d===r&&g){const f=o&&e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}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 s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(Ts("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Ei(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=Ei(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(Ts("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&qe(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,u=this.playingAsset,d=u?.identifier,g=d?this.getAssetPlayer(d):null;if(g&&d&&(!this.eventItemsMatch(n,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const f=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${h.assetList.length} ${Ut(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:f,event:h,schedule:i.slice(0),scheduleIndex:e,player:g}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(d,r),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${qe(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const p=this.findItemIndex(r);this.advanceSchedule(p,f,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=n.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const f=Ei(h,s-1);if(h.isAssetPastPlayoutLimit(f)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=f}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${qe(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=h.assetList[s];if(!g){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=h.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${h}`),d=this.createAssetPlayer(h,g,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Mn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Mn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.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,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${qe(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Ts("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${qe(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Ts("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.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 s=this.hls.levels[t.level];if(!s.details)return;const i=re(re({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=re(re({},this.altSelection),{},{audio:s});return}const r=re(re({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=re(re({},this.altSelection),{},{subtitles:s});return}const r=re(re({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=Q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${qe(e)} (was ${qe(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=Q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const g=r.event;if(u-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${qe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:dd(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ae({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const S=this.timelinePos-t.timelineStart;if(S>1){const x=t.duration;x&&S<x&&(h=S)}}const u=t.identifier,d=re(re({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=ae({},g,{contentId:ts(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const f=new md(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0;const y=S=>{if(S.live){var x;const L=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:L},I=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,I,s,L.message);return}const D=S.edge-S.fragmentStart,A=t.duration;(p||A===null||D>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${D}`),t.duration=D,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(S,{details:x})=>y(x)),f.on(m.LEVEL_PTS_UPDATED,(S,{details:x})=>y(x)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(S,x)=>{const D=this.getAssetPlayer(u);if(D&&x.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=x.tracks;const A=this.primaryMedia;this.bufferingAsset===D.assetItem&&A&&!D.media&&this.bufferAssetPlayer(D,A)}};f.on(m.BUFFER_CODECS,E);const v=()=>{var S;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),A=(S=this.schedule.items)==null?void 0:S[D];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};f.on(m.BUFFERED_TO_END,v);const T=S=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,S)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(S,x)=>{if(!this.schedule)return;const D=this.getAssetPlayer(u);if(x.details===_.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ut(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&qe(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Ut(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const u=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!ra(u,e.tracks)){const d=new Error(`Asset ${Ut(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),g={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===_.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&Ut(n)} ${e.error}`),!this.schedule)return;const o=n?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=ae({},e,{fatal:!1,errorAction:Gt(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${qe(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===n;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(d){var f;const p=this.schedule.findEventIndex(n),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.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(y)}this.setSchedulePosition(p)}else if(g?.identifier===n){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case _.ASSET_LIST_PARSING_ERROR:case _.ASSET_LIST_LOAD_ERROR:case _.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case _.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Nn=500;class vd extends ur{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",Y.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=P.IDLE,this.setInterval(Nn),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:s,success:i}=t;if(this.fragContextChanged(s)||(Te(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,Y.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===Y.SUBTITLE&&(t.details===_.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&oo(this.levels,t)){this.levels=t.map(s=>new rs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new rs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Y.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Nn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)n.hasProgramDateTime&&u.hasProgramDateTime?(Ys(n,u),l=n.fragmentStart):d&&(l=d.start,$i(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,$i(n,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(Pt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Kt(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,cr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=Q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const v=i.maxFragLookUpTolerance,T=o>g-v?0:v;f=Pt(p,u,Math.max(u[0].start,o),T),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,E=u[y-1];if(E&&E.cc===f.cc&&this.fragmentTracker.getState(E)===Ie.NOT_LOADED&&(f=E),this.fragmentTracker.getState(f)===Ie.NOT_LOADED){const v=this.mapToInitFragWhenRequired(f);v&&this.loadFragment(v,s,o)}}}loadFragment(e,t,s){Te(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Td(this.tracksBuffered[this.currentTrackId]||[])}}class Td{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Sd={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},Io=a=>String.fromCharCode(Sd[a]||a),je=15,ct=100,xd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ad={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Id={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ld={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Rd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class bd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ne.log(`${this.time} [${e}] ${s}`)}}}const _t=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Lo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class _d{constructor(){this.uchar=" ",this.penState=new Lo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Dd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Lo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ct;t++)this.chars.push(new _d);this.logger=e}equals(e){for(let t=0;t<ct;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ct;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ct;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ct&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ct)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Io(e);if(this.pos>=ct){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<ct;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<ct;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class vi{constructor(e){this.rows=[],this.currRow=je-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<je;t++)this.rows.push(new Dd(e));this.logger=e}reset(){for(let e=0;e<je;e++)this.rows[e].clear();this.currRow=je-1}equals(e){let t=!0;for(let s=0;s<je;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<je;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<je;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ce(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<je;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ce(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 s="",i=-1;for(let r=0;r<je;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(` 30 + `)),s}getTextAndFormat(){return this.rows}}class Bn{constructor(e,t,s){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 vi(s),this.nonDisplayedMemory=new vi(s),this.lastOutputScreen=new vi(s),this.currRollUpRow=this.displayedMemory.rows[je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[je-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ce(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 Un{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Pd(),this.logger=void 0;const i=this.logger=new bd;this.channels=[null,new Bn(e,t,i),new Bn(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+_t([t[s],t[s+1]])+"] -> ("+_t([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Cd(i,r,c)){Ss(null,null,c),this.logger.log(3,()=>"Repeated command ("+_t([i,r])+") is dropped");continue}Ss(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Ss(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+_t([i,r])+" orig: "+_t([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+_t([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?xd[e]:Id[e]:s=n===1?Ad[e]:Ld[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Io(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+_t(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Rd[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ss(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Ss(a,e,t){t.a=a,t.b=e}function Cd(a,e,t){return t.a===a&&t.b===e}function Pd(){return{a:null,b:null}}var Ar=(function(){if(Hs!=null&&Hs.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function n(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",g=!1,f=o,p=c,y=l,E=null,v="",T=!0,S="auto",x="start",D=50,A="middle",L=50,R="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return g},set:function(I){g=!!I}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");f=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(I){y=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return v},set:function(I){const C=s(I);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");v=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(I){T=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return S},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");x=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return L},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");L=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return R},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");R=C,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n})();class kd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ro(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.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 wd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function bo(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const ji=new Ar(0,0,""),xs=ji.align==="middle"?"middle":"center";function Od(a,e,t){const s=a;function i(){const o=Ro(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new wd;bo(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(d,f[0]),l.percent(d,f[0])&&l.set("snapToLines",!1),l.alt(d,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",xs,"end"]);break;case"position":f=g.split(","),l.percent(d,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",xs,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,g);break;case"align":l.alt(d,g,["start",xs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&ji.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",xs);let u=l.get("position","auto");u==="auto"&&ji.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function _o(a){return a.replace(/<br(?: \/)?>/gi,` 31 + `)}class Fd{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new kd,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 s(){let r=t.buffer,n=0;for(r=_o(r);n<r.length&&r[n]!=="\r"&&r[n]!==` 32 + `;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===` 33 + `&&++n,t.buffer=r.slice(n),o}function i(r){bo(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Ar(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Od(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!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+=` 34 + `),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+=` 35 + 36 + `,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 Md=/\r\n|\n\r|\n|\r/g,Ti=function(e,t,s=0){return e.slice(s,s+t.length)===t},Nd=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!V(t)||!V(s)||!V(i)||!V(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function Ir(a,e,t){return ts(a.toString())+ts(e.toString())+ts(t)}const Bd=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function Ud(a,e,t,s,i,r,n){const o=new Fd,c=Ve(new Uint8Array(a)).trim().replace(Md,` 37 + `).split(` 38 + `),l=[],h=e?Yh(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,p=!0;o.oncue=function(y){const E=t[s];let v=t.ccOffset;const T=(d-h)/9e4;if(E!=null&&E.new&&(g!==void 0?v=t.ccOffset=E.start:Bd(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}v=T-t.presentationOffset}const S=y.endTime-y.startTime,x=$e((y.startTime+v-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+S,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=Ir(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){n(f);return}r(l)},c.forEach(y=>{if(p)if(Ti(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{Ti(E,"LOCAL:")?u=E.slice(6):Ti(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=Nd(u)/1e3}catch(E){f=E}return}else y===""&&(p=!1);o.parse(y+` 39 + `)}),o.flush()}const Si="stpp.ttml.im1t",Do=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Co=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,$d={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(a,e,t,s){const i=ee(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ve(o)),n=Hh(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Gd(o,n)))}catch(o){s(o)}}function Gd(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Gn(xi(i,"styling","style")),l=Gn(xi(i,"layout","region")),h=xi(i,"body","[begin]");return[].map.call(h,u=>{const d=Po(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=Ii(u.getAttribute("begin"),n),f=Ii(u.getAttribute("dur"),n);let p=Ii(u.getAttribute("end"),n);if(g===null)throw Kn(u);if(p===null){if(f===null)throw Kn(u);p=g+f}const y=new Ar(g-e,p-e,d);y.id=Ir(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],v=c[u.getAttribute("style")],T=Kd(E,v,c),{textAlign:S}=T;if(S){const x=$d[S];x&&(y.lineAlign=x),y.align=S}return ae(y,T),y}).filter(u=>u!==null)}function xi(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gn(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Po(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+` 40 + `:(r=s.childNodes)!=null&&r.length?Po(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Kd(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=Ai(e,s,c)||Ai(a,s,c)||Ai(i,s,c);return l&&(o[c]=l),o},{})}function Ai(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Kn(a){return new Error(`Could not parse ttml timestamp ${a}`)}function Ii(a,e){if(!a)return null;let t=Ro(a);return t===null&&(Do.test(a)?t=Vd(a,e):Co.test(a)&&(t=Hd(a,e))),t}function Vd(a,e){const t=Do.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Hd(a,e){const t=Co.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class As{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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Yd{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=Hn(),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 As(this,"textTrack1"),t=new As(this,"textTrack2"),s=new As(this,"textTrack3"),i=new As(this,"textTrack4");this.cea608Parser1=new Un(1,e,t),this.cea608Parser2=new Un(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=Wd(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===Y.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.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:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Vn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,$t(s[e]),So(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{$t(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hn(),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 s=0;s<t.length;s++)$t(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Si);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(oo(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?ws(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Vn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)$t(h);else{const u=ko(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.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 n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Y.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===Y.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Si?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;$n(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?He(s.initSegment.data,new Uint8Array(i)).buffer:i;Ud(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||$n(t,this.initPTS[e.cc],()=>{s.textCodec=Si,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>xo(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===Y.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===Y.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>qi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>qi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function ko(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Vn(a,e){return!!a&&a.kind===ko(e)&&Vi(e,a)}function Wd(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Hn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const qd=/\s/,jd={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)qd.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=_o(l.trim()),f=Ir(e,t,g);a!=null&&(u=a.cues)!=null&&u.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=d+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>xo(a,d))),i}};function Xd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const zd=/(\d+)-(\d+)\/(\d+)/;class Yn{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||ef,this.controller=new self.AbortController,this.stats=new sr}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,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=Qd(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&V(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new tf(y||"fetch, bad network response",p,u)}i.loading.first=g,i.total=Jd(u.headers)||i.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&V(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,f):n?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:u,code:f.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!V(t.highWaterMark)&&E(i,e,u,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=u&&u.code||0,f=u?u.message:null;(d=this.callbacks)==null||d.onError({code:g,text:f},e,u?u.details:null,i)})}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,s,i=0,r){const n=new Ga,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Qd(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ae({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Zd(a){const e=zd.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Jd(a){const e=a.get("Content-Range");if(e){const s=Zd(e);if(V(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function ef(a,e){return new self.Request(a.url,e)}class tf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const sf=/^age:\s*[\d.]+\s*$/im;class wo{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 sr,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,s){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=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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),s.timeout=r&&V(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=h??t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(n=this.callbacks)==null?void 0:n.onProgress;y&&y(s,e,f,t);const E={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,g={url:e.url,data:void 0,code:l};if(Ks(u,d,!1,g))this.retry(u);else{var c;ne.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ks(e,t,!0))this.retry(e);else{var s;ne.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=ar(e,s.retry),s.retry++,ne.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.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&&sf.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 rf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},nf=re(re({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:wo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:pc,bufferController:au,capLevelController:Tr,errorController:Sc,fpsController:od,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:Ca,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:rf},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},af()),{},{subtitleStreamController:vd,subtitleTrackController:hd,timelineController:Yd,audioStreamController:su,audioTrackController:iu,emeController:Vt,cmcdController:id,contentSteeringController:nd,interstitialsController:Ed});function af(){return{cueHandler:jd,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 of(a,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 s=Xi(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${n}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const g=s[o].default;switch(e[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ce(e[o])}`)}),re(re({},s),e)}function Xi(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Xi):Object.keys(a).reduce((e,t)=>(e[t]=Xi(a[t]),e),{}):a}function lf(a,e){const t=a.loader;t!==Yn&&t!==wo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Xd()&&(a.loader=Yn,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Os=2,cf=.1,hf=.05,uf=100;class df extends La{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.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(uf),this.mediaSource=t.mediaSource;const s=this.media=t.media;we(s,"playing",this.onMediaPlaying),we(s,"waiting",this.onMediaWaiting),we(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Me(s,"playing",this.onMediaPlaying),Me(s,"waiting",this.onMediaWaiting),Me(s,"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 s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!Q.getBuffered(n).length){this.nudgeRetry=0;return}const u=Q.bufferInfo(n,e,0),d=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const D=Wn(this.hls.inFlightFragments,e),A=u.len>Os,L=!d||D||d-e>Os&&!g.getPartialFragment(e);if(A||L)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,R=!!(f!=null&&f.live)?f.targetduration*2:Os,I=Is(e,g);if(A>0&&(A<=R||I)){n.paused||this._trySkipBufferHole(I);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let v=this.stalled;if(v===null)if(E>0&&y-E<p)v=this.stalled=E;else{this.stalled=y;return}const T=y-v;if(!o&&(T>=p||E)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const x=Q.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=Q.bufferedInfo(Q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=Q.timeRangesToArray(i),o=Q.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=Q.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Is(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=Q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Is(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,Y.MAIN),n=s.getFragAtPos(i,Y.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ce(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=Q.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-n;if(d>0&&(h||u)){if(d>r.maxBufferHole){let f=!1;if(n===0){const p=s.getAppendedFrag(0,Y.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Wn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const v=Is(E,s);if(v)E+=v.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(c+hf,n+cf);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${g}`),p={type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wn(a,e){const t=qn(a.main);if(t&&t.start<=e)return t;const s=qn(a.audio);return s&&s.start<=e?s:null}function qn(a){if(!a)return null;switch(a.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return a.frag}function Is(a,e){return e.getAppendedFrag(a,Y.MAIN)||e.getPartialFragment(a)}const ff=.25;function zi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Li(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ce(i?re({type:i},s):s))}return r}const Ls=(()=>{const a=zi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class gf{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 s;this.media=t.media,((s=t.overrides)==null?void 0:s.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&&$t(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;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return So(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=zi();if(n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===Ke.emsg&&!s||!i)continue;const l=ja(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Ls&&(u=Ls),u-h<=0&&(u=h+ff);for(let g=0;g<l.length;g++){const f=l[g];if(!Xa(f)){this.updateId3CueEnds(h,c);const p=Li(n,h,u,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===Ls&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===Ke.audioId3&&c:i==="video"?l=h=>h.type===Ke.emsg&&o:l=h=>h.type===Ke.audioId3&&c||h.type===Ke.emsg&&o,qi(r,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=zi();if(s&&i&&!n){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=Li(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var g;const E=p[y],v=(g=u[E])==null?void 0:g.cues;delete u[E],v&&Object.keys(v).forEach(T=>{const S=v[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(h.length===0||!V(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],v=E.startTime,T=u[y],S=T?.cues||{};let x=T?.durationKnown||!1,D=Ls;const{duration:A,endDate:L}=E;if(L&&A!==null)D=v+A,x=!0;else if(E.endOnNext&&!x){const I=h.reduce((C,$)=>{if($!==E.id){const K=l[$];if(K.class===E.class&&K.startDate>E.startDate&&(!C||E.startDate<C.startDate))return K}return C},null);I&&(D=I.startTime,x=!0)}const R=Object.keys(E.attr);for(let I=0;I<R.length;I++){const C=R[I];if(!Oc(C))continue;const $=S[C];if($)x&&!(T!=null&&T.durationKnown)?$.endTime=D:Math.abs($.startTime-v)>.01&&($.startTime=v,$.endTime=D);else if(o){let K=E.attr[C];Fc(C)&&(K=na(K));const O=Li(o,v,D,{key:C,data:K},Ke.dateRange);O&&(O.id=y,this.id3Track.addCue(O),S[C]=O,n&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:S,dateRange:E,durationKnown:x}}}}}class mf{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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,g)}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:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}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 s=e.buffered.length;return(s?e.buffered.end(s-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 s;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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 pf extends vr{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 s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:g}=h;d&&(h.audioCodec=d=Bs(d,s)||void 0),g&&(g=h.videoCodec=Ql(g));const{width:f,height:p,unknownCodecs:y}=h,E=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!d),E||d&&!this.isAudioSupported(d)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":x,RESOLUTION:D,"VIDEO-RANGE":A}=u,R=`${`${x||"."}-`}${h.bitrate}-${D}-${T}-${v}-${A}-${S}`;if(r[R])if(r[R].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const I=n[R]+=1;h.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const C=this.createLevel(h);r[R]=C,i.push(C)}else r[R].addGroupId("audio",u.AUDIO),r[R].addGroupId("text",u.SUBTITLES);else{const I=this.createLevel(h);r[R]=I,n[R]=1,i.push(I)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new rs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=ya(i,[])}return t}isAudioSupported(e){return ss(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ss(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:v,videoRange:T,width:S,height:x})=>(!!v||!!(S&&x))&&oc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ce(t.levels.map(x=>x.attrs.CODECS).filter((x,D,A)=>A.indexOf(x)===D))}`,this.warn(T),v+=` (${T})`);const S=new Error(v);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),jn(o)),t.subtitles&&(c=t.subtitles,jn(c));const u=l.slice(0);l.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return Us.indexOf(v.videoRange)-Us.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){const S=Br(v.videoCodec),x=Br(T.videoCodec);if(S!==x)return x-S}if(v.uri===T.uri&&v.codecSet!==T.codecSet){const S=Ns(v.codecSet),x=Ns(T.codecSet);if(S!==x)return x-S}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let v=0;v<u.length;v++)if(u[v].pathwayId===l[0].pathwayId){d=u[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===d){var g;this._firstLevel=v;const T=d.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const x=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);x>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}const f=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!f&&o.some(v=>!!v.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i?.details,l);this.loadPlaylist(h)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Y.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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 s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ba(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}}function jn(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Oo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Fo(){if(!It())return!1;const e=Oo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function yf(){if(!Fo())return!1;const a=It();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(is(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(is(e,"audio"))))}function Ef(){var a;const e=Oo();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const vf=100;class Tf extends ur{constructor(e,t,s){super(e,t,s,"stream-controller",Y.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 i=this.media,r=i?i.currentTime:null;if(r===null||!V(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,Y.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.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:s,hls:i}=this;if(this.stopLoad(),this.setInterval(vf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.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 l=n.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&Te(g)&&this.fragmentTracker.getState(g)!==Ie.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,E=l.fragments[y-1];E&&g.cc===E.cc&&(g=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,E=(y===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,Y.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,Y.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ie.NOT_LOADED||i===Ie.PARTIAL?Te(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,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Y.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 s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;we(s,"playing",this.onMediaPlaying),we(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Me(s,"playing",this.onMediaPlaying),Me(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Ef(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=Q.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:g}=Q.bufferedInfo(u.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new ao(this.hls,Y.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new lr(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,p),E=this.initPTS[s.cc];g.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if($s(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=$s(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===Y.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Te(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&Q.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===te.LEVEL&&(this.state=P.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case _.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 _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==le.AUDIO||!this.altAudio){const s=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,Y.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 s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=Q.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:h,text:u,id3:d,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){const y=g.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,S,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}const E=g.initPTS,v=g.timescale,T=this.initPTS[o.cc];if(V(E)&&(!T||T.baseTime!==E||T.timescale!==v)){const S=g.trackId;this.initPTS[o.cc]={baseTime:E,timescale:v,trackId:S},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:v,trackId:S})}}if(h&&f){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],E=o.sn===f.startSN,v=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:x,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:S,startDTS:x,endDTS:D};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),L=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,R=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&L<R-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,S,o.start,D,!0)}else E&&T-(f.appliedTimelineOffset||0)>Os&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,S,x,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||v)}else if(E||v)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=p;c&&(c.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),o.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(p,o,c,r)}if(f&&d!=null&&d.samples.length){const y={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&u){const y={id:t,frag:o,details:f,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${Te(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=bs(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=Y.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=Y.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.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(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Y.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(Q.isBuffered(e,s)?t=this.getAppendedFrag(s):Q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.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 V(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(V(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Pt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}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 Sf extends Ye{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.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=_.KEY_LOAD_ERROR,s,i,r){return new ht({type:W.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Te(e)||!Te(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=Ds(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Qt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}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 s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=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,_.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=Ri(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+be(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={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,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=Ul(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${be(o)}`),At.setKeyIdForUri(e.decryptdata.uri,o)):(o=At.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${be(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Te(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const{frag:y,keyInfo:E}=f,v=Ri(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,n({frag:y,keyInfo:E})},onError:(d,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,re({url:c.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ri(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Ri(a){if(a.keyFormat!==_e.FAIRPLAY){const e=a.keyId;if(e)return be(e)}return a.uri}function Xn(a){const{type:e}=a;switch(e){case te.AUDIO_TRACK:return Y.AUDIO;case te.SUBTITLE_TRACK:return Y.SUBTITLE;default:return Y.MAIN}}function bi(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class xf{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,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:te.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[te.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[te.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===te.MANIFEST?r=s.manifestLoadPolicy.default:r=ae({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),V((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===te.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===te.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===te.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ae({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=l.data;h.parsing.start=performance.now(),st.isMediaPlaylist(f)||u.type!==te.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,g):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=bi(e,s),c=st.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f}=c;this.variableList=f,h.forEach(v=>{const{unknownCodecs:T}=v;if(T){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:x,videoCodec:D}=v;for(let A=T.length;A--;){const L=T[A];ss(L,"audio",S)?(v.audioCodec=x=x?`${x},${L}`:L,Yt.audio[x.substring(0,4)]=2,T.splice(A,1)):ss(L,"video",S)&&(v.videoCodec=D=D?`${D},${L}`:L,Yt.video[D.substring(0,4)]=2,T.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=st.parseMasterPlaylistMedia(n,o,c);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new fe({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,h=bi(e,s),u=V(c)?c:V(o)?o:0,d=Xn(s),g=st.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===te.MANIFEST){const f={attrs:new fe({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=t.loading.start+Fa(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===te.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===te.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===te.AUDIO_TRACK||e.type===te.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=_.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case te.MANIFEST:c=s?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,l=!0;break;case te.LEVEL:c=s?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,l=!1;break;case te.AUDIO_TRACK:c=s?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case te.SUBTITLE_TRACK:c=s?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:W.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=t?.url||e.url;u.response=re({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:g}=i,f=bi(t,i),p=Xn(i);let y=typeof i.level=="number"&&p===Y.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case te.MANIFEST:case te.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const v=o.levels.indexOf(h);v>-1&&(y=v)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:g,withoutMultiVariant:c===te.MANIFEST});break;case te.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break;case te.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break}}}class De{static get version(){return ns}static isMSESupported(){return Fo()}static isSupported(){return yf()}static getMediaSource(){return It()}static get Events(){return m}static get MetadataSchema(){return Ke}static get ErrorTypes(){return W}static get ErrorDetails(){return _}static get DefaultConfig(){return De.defaultConfig?De.defaultConfig:nf}static set DefaultConfig(e){De.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 dr,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=bl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=of(De.DefaultConfig,e,t);this.userConfig=e,s.progressive&&lf(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new xc(this),d=s.interstitialsController,g=d?this.interstitialsController=new d(this,De):null,f=this.bufferController=new r(this,u),p=this.capLevelController=new n(this),y=new c(this),E=new xf(this),v=s.contentSteeringController,T=v?new v(this):null,S=this.levelController=new pf(this,T),x=new gf(this),D=new Sf(this.config,this.logger),A=this.streamController=new Tf(this,u,D),L=this.gapController=new df(this,u);p.setStreamController(A),y.setStreamController(A);const R=[E,S,A];g&&R.splice(1,0,g),T&&R.splice(1,0,T),this.networkControllers=R;const I=[h,f,L,p,y,x,u];this.audioTrackController=this.createController(s.audioTrackController,R);const C=s.audioStreamController;C&&R.push(this.audioStreamController=new C(this,u,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,R);const $=s.subtitleStreamController;$&&R.push(this.subtititleStreamController=new $(this,u,D)),this.createController(s.timelineController,I),D.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(mf,I),this.coreComponents=I,R.push(l);const K=l.onErrorOut;typeof K=="function"&&this.on(m.ERROR,K,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),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:W.OTHER_ERROR,details:_.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,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}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,s=this._url,i=this._url=tr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||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?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Y.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Y.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Y.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=ud()),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){ac(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}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 s=Ta(t);return Ea(e,s,navigator.mediaCapabilities)}}De.defaultConfig=void 0;var Af=Oe('<div class="error-overlay svelte-zbxgh1"> </div>'),If=Oe('<div class="player-wrapper svelte-zbxgh1" role="region"><video playsinline="" class="svelte-zbxgh1"><track kind="captions"/></video> <div><div class="scrub-bar svelte-zbxgh1" role="slider"><div><img alt="scrub" class="frog-sprite svelte-zbxgh1" draggable="false"/></div></div></div> <button><img src="/frogeye.png" alt="fullscreen" class="frogeye svelte-zbxgh1"/></button> <!></div>',2);function Lf(a,e){Zi(e,!0);let t=ie(void 0),s=null,i=ie(""),r=ie(!1),n=ie(0),o=ie(0),c=ie(void 0),l=ie(!1),h=ie(0),u=ie(0),d=ie(!1),g=0,f=ie(!0),p=null,y=ie(!1);function E(){s&&(s.destroy(),s=null)}function v(){if(!F(t)||!e.src)return;E(),q(i,""),!!F(t).canPlayType("application/vnd.apple.mpegurl")?(F(t).addEventListener("loadedmetadata",()=>{F(t)?.play().catch(()=>{})}),F(t).src=e.src,F(t).load()):De.isSupported()?(s=new De({enableWorker:!0,lowLatencyMode:!1}),s.loadSource(e.src),s.attachMedia(F(t)),s.on(De.Events.MANIFEST_PARSED,()=>{F(t)?.play().catch(()=>{})}),s.on(De.Events.ERROR,(M,N)=>{if(console.error("HLS error:",N),N.fatal)switch(N.type){case De.ErrorTypes.NETWORK_ERROR:q(i,`Network error: ${N.details}`),s?.startLoad();break;case De.ErrorTypes.MEDIA_ERROR:q(i,`Media error: ${N.details}`),s?.recoverMediaError();break;default:q(i,`Fatal error: ${N.details}`),E();break}})):q(i,"HLS playback is not supported in this browser.")}ii(()=>(e.src,F(t)&&v(),E)),ii(()=>(document.addEventListener("fullscreenchange",R),()=>document.removeEventListener("fullscreenchange",R)));let T=0;function S(){if(!F(t)||F(l))return;q(n,F(t).currentTime,!0),q(o,F(t).duration||0,!0);const k=F(o)>0?F(n)/F(o):0,M=k-T;Math.abs(M)>.002&&(q(u,F(u)===0?1:0,!0),q(d,M<0),T=k),q(h,k,!0)}function x(){q(r,!0)}function D(){q(r,!1)}function A(){F(t)&&(F(t).paused?F(t).play().catch(()=>{}):F(t).pause())}function L(){const k=F(t)?.closest(".player-wrapper");k&&(document.fullscreenElement?document.exitFullscreen?.().catch(()=>{}):k.requestFullscreen?.().catch(()=>{}))}function R(){q(y,!!document.fullscreenElement)}function I(k){if(!F(c))return;const M=F(c).getBoundingClientRect(),N=Math.max(0,Math.min(1,(k.clientX-M.left)/M.width)),G=N-g;Math.abs(G)>.02&&(q(u,F(u)===0?1:0,!0),q(d,G<0),g=N),q(h,N,!0),F(t)&&F(o)>0&&(F(t).currentTime=N*F(o),q(n,N*F(o)))}function C(k){k.preventDefault(),q(l,!0),I(k),window.addEventListener("mousemove",K),window.addEventListener("mouseup",H)}function $(k){k.preventDefault(),k.stopPropagation(),q(l,!0),window.addEventListener("mousemove",K),window.addEventListener("mouseup",H)}function K(k){F(l)&&I(k)}function H(){q(l,!1),window.removeEventListener("mousemove",K),window.removeEventListener("mouseup",H)}function O(k){k.code==="Space"&&F(t)&&(k.preventDefault(),A())}ii(()=>(window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)));function w(){q(f,!0),p&&clearTimeout(p),p=setTimeout(()=>{F(r)&&q(f,!1)},2500)}Fs(a,{seed:"player-main",padding:4,children:(k,M)=>{var N=If(),G=de(N);Ms(G,ye=>q(t,ye),()=>F(t));var B=ve(G,2);let U;var j=de(B);dt(j,"aria-valuemin",0),dt(j,"tabindex",0);var J=de(j);let X;var Z=de(J);ue(J),ue(j),Ms(j,ye=>q(c,ye),()=>F(c)),ue(B);var oe=ve(B,2);let he;var xe=ve(oe,2);{var Ce=ye=>{var nt=Af(),kt=de(nt,!0);ue(nt),Ge(()=>Xe(kt,F(i))),ke(ye,nt)};mt(xe,ye=>{F(i)&&ye(Ce)})}ue(N),Ge(()=>{U=Zt(B,1,"controls svelte-zbxgh1",null,U,{visible:F(f)||!F(r)}),dt(j,"aria-valuenow",F(n)),dt(j,"aria-valuemax",F(o)),X=Zt(J,1,"scrub-frog svelte-zbxgh1",null,X,{flipped:F(d)}),Rs(J,`left: ${F(h)*100}%;`),dt(Z,"src",F(u)===0?"/froggiestand.png":"/froggiejump.png"),he=Zt(oe,1,"fullscreen-btn svelte-zbxgh1",null,he,{visible:F(f)||!F(r)}),dt(oe,"title",F(y)?"Exit fullscreen":"Fullscreen")}),ft("mousemove",N,w),xt("mouseenter",N,w),xt("mouseleave",N,()=>{F(r)&&q(f,!1)}),xt("timeupdate",G,S),xt("play",G,x),xt("pause",G,D),ft("click",G,A),ft("mousedown",j,C),ft("mousedown",J,$),ft("click",oe,L),ke(k,N)},$$slots:{default:!0}}),Ji()}er(["mousemove","click","mousedown"]);var Rf=Oe('<img class="thumb-img svelte-1nxalmg"/>'),bf=Oe('<div class="loading-spinner svelte-1nxalmg"><div class="spinner svelte-1nxalmg"></div></div>'),_f=Oe('<div class="scrub-bar svelte-1nxalmg"><div class="scrub-bar-fill svelte-1nxalmg"></div></div>'),Df=Oe('<div><img alt="hop" class="frog-sprite svelte-1nxalmg"/></div>'),Cf=Oe('<div class="thumbnail svelte-1nxalmg" role="img"><!> <canvas></canvas> <!> <!> <!> <div class="thumb-shadow svelte-1nxalmg"></div></div>'),Pf=Oe('<span class="duration-badge svelte-1nxalmg"> </span> <div class="thumb-wrapper svelte-1nxalmg"><!></div> <div class="info svelte-1nxalmg"><h3 class="title svelte-1nxalmg"> </h3> <p class="creator svelte-1nxalmg"> </p> <p class="date svelte-1nxalmg"> </p></div>',1),kf=Oe('<button class="card svelte-1nxalmg"><!></button>');function wf(a,e){Zi(e,!0);let t=ie(Di(e.video.value.creator)),s=ie(null);const i=e.video.uri.split("/").pop()||e.video.uri,r=ul(e.video.value.creator),n=`transform: rotate(${r.rotation}deg) translate(${r.translateX}px, ${r.translateY}px);`;let o=ie(void 0),c=ie(void 0),l=ie(!1),h=ie(0),u=ie(!1),d=ie(!1),g=ie(!1),f=null,p=null,y=0,E=!1,v=null;zn(()=>{Ci(e.video.value.creator).then(k=>q(t,k,!0)),dl(e.video).then(k=>q(s,k,!0))}),Mo(S);function T(){if(f)return;q(d,!0),f=document.createElement("video"),f.muted=!0,f.playsInline=!0,f.preload="auto",f.style.cssText="position:fixed;top:-9999px;left:-9999px;width:320px;height:180px;pointer-events:none;",document.body.appendChild(f),f.addEventListener("seeked",x);const k=ia(e.video.uri);!!f.canPlayType("application/vnd.apple.mpegurl")?(f.addEventListener("loadedmetadata",()=>{f&&(y=f.duration,q(u,!0),A(F(h)))}),f.src=k,f.load()):De.isSupported()&&(p=new De({enableWorker:!1,lowLatencyMode:!1,startLevel:0}),p.loadSource(k),p.attachMedia(f),p.on(De.Events.LEVEL_LOADED,(N,G)=>{y=G.details.totalduration,q(u,!0),A(F(h))}),p.on(De.Events.ERROR,(N,G)=>{G.fatal&&q(d,!1)}))}function S(){p&&(p.destroy(),p=null),f&&(f.removeEventListener("seeked",x),f.remove(),f=null),q(u,!1),q(d,!1),q(g,!1),E=!1,v=null,y=0}function x(){if(E=!1,q(d,!1),L(),v!==null){const k=v;v=null,D(k)}}function D(k){!f||!F(u)||(E=!0,f.currentTime=k)}function A(k){if(!F(u)||!y)return;const M=k*y;E?v=M:D(M)}function L(){if(!f||!F(c))return;const k=f.videoWidth,M=f.videoHeight;if(!k||!M)return;const N=F(c).getBoundingClientRect(),G=window.devicePixelRatio||1;F(c).width=N.width*G,F(c).height=N.height*G;const B=F(c).getContext("2d");B&&(B.drawImage(f,0,0,F(c).width,F(c).height),q(g,!0))}let R=ie(0),I=0,C=ie(!1);function $(){q(l,!0),T()}function K(k){if(!F(o))return;const M=F(o).getBoundingClientRect(),N=Math.max(0,Math.min(1,(k.clientX-M.left)/M.width)),G=N-I;Math.abs(G)>.03&&(q(R,F(R)===0?1:0,!0),q(C,G<0),I=N),q(h,N,!0),A(F(h))}function H(){q(l,!1)}var O=kf(),w=de(O);Fs(w,{get seed(){return i},fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:2.2,padding:"clamp(24px, 4vw, 36px)",children:(k,M)=>{var N=Pf(),G=Jn(N),B=de(G,!0);ue(G);var U=ve(G,2),j=de(U);{let ye=ea(()=>i+"-thumb");Fs(j,{get seed(){return F(ye)},fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:1.5,padding:0,children:(nt,kt)=>{var We=Cf(),Qs=de(We);{var se=me=>{var Ee=Rf();Ge(()=>{dt(Ee,"src",F(s)),dt(Ee,"alt",e.video.value.title)}),ke(me,Ee)};mt(Qs,me=>{F(s)&&me(se)})}var Se=ve(Qs,2);let Pe;Ms(Se,me=>q(c,me),()=>F(c));var ze=ve(Se,2);{var Ne=me=>{var Ee=bf();ke(me,Ee)};mt(ze,me=>{F(l)&&F(d)&&!F(g)&&me(Ne)})}var at=ve(ze,2);{var ot=me=>{var Ee=_f(),Rt=de(Ee);ue(Ee),Ge(()=>Rs(Rt,`width: ${F(h)*100}%`)),ke(me,Ee)};mt(at,me=>{F(l)&&F(u)&&me(ot)})}var cs=ve(at,2);{var wt=me=>{var Ee=Df();let Rt;var Zs=de(Ee);ue(Ee),Ge(()=>{Rt=Zt(Ee,1,"scrub-frog svelte-1nxalmg",null,Rt,{flipped:F(C)}),Rs(Ee,`left: ${F(h)*100}%;`),dt(Zs,"src",F(R)===0?"/froggiestand.png":"/froggiejump.png")}),ke(me,Ee)};mt(cs,me=>{F(l)&&me(wt)})}nl(2),ue(We),Ms(We,me=>q(o,me),()=>F(o)),Ge(()=>Pe=Zt(Se,1,"scrub-canvas svelte-1nxalmg",null,Pe,{visible:F(l)&&F(g)})),xt("mouseenter",We,$),ft("mousemove",We,K),xt("mouseleave",We,H),ke(nt,We)},$$slots:{default:!0}})}ue(U);var J=ve(U,2),X=de(J),Z=de(X,!0);ue(X);var oe=ve(X,2),he=de(oe,!0);ue(oe);var xe=ve(oe,2),Ce=de(xe,!0);ue(xe),ue(J),Ge((ye,nt)=>{Xe(B,ye),Xe(Z,e.video.value.title),Xe(he,F(t)),Xe(Ce,nt)},[()=>ta(e.video.value.duration),()=>sa(e.video.value.createdAt)]),ke(k,N)},$$slots:{default:!0}}),ue(O),Ge(()=>Rs(O,n)),ft("click",O,()=>e.onSelect(e.video)),ke(a,O),Ji()}er(["click","mousemove"]);var Of=Oe('<h2 class="player-title svelte-1uha8ag"> </h2> <p class="player-meta svelte-1uha8ag"><span class="creator-tag svelte-1uha8ag"> </span> <span class="dot svelte-1uha8ag">·</span> <span class="dot svelte-1uha8ag">·</span> </p>',1),Ff=Oe('<section class="player-section svelte-1uha8ag"><!> <div class="player-info svelte-1uha8ag"><!></div></section>'),Mf=Oe('<div class="error svelte-1uha8ag"> </div>'),Nf=Oe('<button class="page-btn svelte-1uha8ag">← previous</button>'),Bf=Oe('<button class="page-btn svelte-1uha8ag">next →</button>'),Uf=Oe('<div class="app svelte-1uha8ag"><!> <!> <!> <section class="grid svelte-1uha8ag"></section> <div class="pagination svelte-1uha8ag"><!> <span class="page-num svelte-1uha8ag"> </span> <!></div></div>');function zf(a,e){Zi(e,!0);const t=9;let s=ie(Di([])),i=ie(!1),r=ie(null),n=ie(""),o=ie(""),c=ie(Di([void 0])),l=ie(0),h=ie(!0);async function u(){q(i,!0),q(o,"");try{const O=await gl(F(c)[F(l)],t);q(s,O.records,!0),q(h,!!O.cursor&&O.records.length===t,!0),F(h)&&F(c).length<=F(l)+1&&q(c,[...F(c),O.cursor],!0)}catch(O){q(o,O.message,!0)}q(i,!1)}function d(){!F(h)||F(i)||(Cr(l),u(),window.scrollTo({top:0,behavior:"smooth"}))}function g(){F(l)<=0||F(i)||(Cr(l,-1),u(),window.scrollTo({top:0,behavior:"smooth"}))}function f(O){q(r,O,!0),Ci(O.value.creator).then(k=>q(n,k,!0));const w=new URL(window.location.href);w.searchParams.set("v",O.uri),window.history.pushState({},"",w.toString()),window.scrollTo({top:0,behavior:"smooth"})}function p(){q(r,null);const O=new URL(window.location.href);O.searchParams.delete("v"),window.history.pushState({},"",O.toString())}zn(async()=>{await u();const w=new URLSearchParams(window.location.search).get("v");if(w){const k=F(s).find(M=>M.uri===w);k&&f(k)}});function y(){const w=new URLSearchParams(window.location.search).get("v");if(w){const k=F(s).find(M=>M.uri===w);k&&(q(r,k,!0),Ci(k.value.creator).then(M=>q(n,M,!0)))}else q(r,null)}var E=Uf();xt("popstate",ol,y),cl("1uha8ag",O=>{al(()=>{ll.title="vod frog"})});var v=de(E);fl(v,{onHomeClick:p});var T=ve(v,2);{var S=O=>{var w=Ff(),k=de(w);{let G=ea(()=>ia(F(r).uri));Lf(k,{get src(){return F(G)}})}var M=ve(k,2),N=de(M);Fs(N,{seed:"player-info",fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:1.8,padding:48,children:(G,B)=>{var U=Of(),j=Jn(U),J=de(j,!0);ue(j);var X=ve(j,2),Z=de(X),oe=de(Z,!0);ue(Z);var he=ve(Z,3),xe=ve(he,2);ue(X),Ge((Ce,ye)=>{Xe(J,F(r).value.title),Xe(oe,F(n)||F(r).value.creator),Xe(he,` ${Ce??""} `),Xe(xe,` ${ye??""}`)},[()=>sa(F(r).value.createdAt),()=>ta(F(r).value.duration)]),ke(G,U)},$$slots:{default:!0}}),ue(M),ue(w),ke(O,w)};mt(T,O=>{F(r)&&O(S)})}var x=ve(T,2);{var D=O=>{var w=Mf(),k=de(w,!0);ue(w),Ge(()=>Xe(k,F(o))),ke(O,w)};mt(x,O=>{F(o)&&O(D)})}var A=ve(x,2);pl(A,21,()=>F(s),O=>O.uri,(O,w)=>{wf(O,{get video(){return F(w)},onSelect:f})}),ue(A);var L=ve(A,2),R=de(L);{var I=O=>{var w=Nf();Ge(()=>w.disabled=F(i)),ft("click",w,g),ke(O,w)};mt(R,O=>{F(l)>0&&O(I)})}var C=ve(R,2),$=de(C);ue(C);var K=ve(C,2);{var H=O=>{var w=Bf();Ge(()=>w.disabled=F(i)),ft("click",w,d),ke(O,w)};mt(K,O=>{F(h)&&O(H)})}ue(L),ue(E),Ge(()=>Xe($,`page ${F(l)+1}`)),ke(a,E),Ji()}er(["click"]);export{zf as component};
+1
.svelte-kit/output/client/_app/immutable/nodes/3.CW9t1woG.js
··· 1 + import{a as i,f as n}from"../chunks/DGbOEUpF.js";import{o as oa}from"../chunks/DxGD2b0U.js";import{a1 as la,a4 as va,a8 as ia,a5 as r,B as b,A as a,a9 as na,a7 as p,aa as y,a6 as o,ab as j,ac as da,a3 as c}from"../chunks/CkzjbUDB.js";import{s as _}from"../chunks/BsDbD4Ku.js";import{i as u,s as pa,a as ca}from"../chunks/XE2G8ySY.js";import{h as ma}from"../chunks/DmyE0d-6.js";import{F as fa,g as _a,W as N,s as w}from"../chunks/D_t83wNY.js";import{s as ua}from"../chunks/C0nNmPgn.js";const ga=!1,xa=!1,Ga=Object.freeze(Object.defineProperty({__proto__:null,prerender:ga,ssr:xa},Symbol.toStringTag,{value:"Module"})),ba=()=>{const m=ua;return{page:{subscribe:m.page.subscribe},navigating:{subscribe:m.navigating.subscribe},updated:m.updated}},ha={subscribe(m){return ba().page.subscribe(m)}};var $a=n('<div class="loading svelte-oxml5t"><img src="/froggiejump.png" alt="loading" class="loading-frog svelte-oxml5t"/> <p class="loading-text svelte-oxml5t">hopping over to fetch profile...</p></div>'),ka=n('<div class="error svelte-oxml5t"> </div>'),ya=n('<img alt="banner" class="banner-img svelte-oxml5t"/>'),wa=n('<img class="avatar svelte-oxml5t"/>'),Ca=n('<div class="avatar-wrapper svelte-oxml5t"><!></div>'),Fa=n('<p class="description svelte-oxml5t"> </p>'),Ba=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">followers</span></div>'),Pa=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">following</span></div>'),Wa=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">posts</span></div>'),Aa=n('<div class="profile-card svelte-oxml5t"><!> <h1 class="display-name svelte-oxml5t"> </h1> <p class="handle svelte-oxml5t"> </p> <!> <div class="stats svelte-oxml5t"><!> <!> <!></div> <a target="_blank" class="profile-link svelte-oxml5t">view on witchsky →</a></div>'),ja=n('<div class="profile-layout svelte-oxml5t"><!> <div class="profile-card-area svelte-oxml5t"><!></div></div>'),Na=n('<div class="profile-page svelte-oxml5t"><!> <!> <div class="back-link svelte-oxml5t"><a href="/" class="svelte-oxml5t">← back to vods</a></div></div>');function Ia(m,S){la(S,!0);const q=()=>ca(ha,"$page",G),[G,I]=pa();let e=j(null),C=j(!0),h=j(""),D=da(()=>q().params.handle);oa(async()=>{b(C,!0),b(h,"");try{b(e,await _a(a(D)),!0)}catch(l){b(h,l.message,!0)}b(C,!1)});var F=Na();ma("oxml5t",l=>{ia(()=>{na.title=`${(a(e)?.displayName||a(D))??""} — vod frog 🐸`})});var E=r(F);fa(E,{});var J=p(E,2);{var K=l=>{var d=$a();i(l,d)},L=l=>{var d=ka(),$=r(d,!0);o(d),c(()=>_($,a(h))),i(l,d)},Q=l=>{var d=ja(),$=r(d);{var R=g=>{N(g,{seed:"profile-banner",fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:2,padding:4,children:(O,k)=>{var x=ya();c(()=>w(x,"src",a(e).banner)),i(O,x)},$$slots:{default:!0}})};u($,g=>{a(e).banner&&g(R)})}var M=p($,2),U=r(M);N(U,{seed:"profile-card",fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:2,padding:48,children:(g,O)=>{var k=Aa(),x=r(k);{var V=t=>{var s=Ca(),v=r(s);N(v,{seed:"profile-avatar",fill:"#FFDEED",strokeColor:"#0A182B",strokeWidth:1.5,padding:4,children:(f,Sa)=>{var A=wa();c(()=>{w(A,"src",a(e).avatar),w(A,"alt",a(e).displayName||a(e).handle)}),i(f,A)},$$slots:{default:!0}}),o(s),i(t,s)};u(x,t=>{a(e).avatar&&t(V)})}var B=p(x,2),X=r(B,!0);o(B);var P=p(B,2),Y=r(P);o(P);var z=p(P,2);{var Z=t=>{var s=Fa(),v=r(s,!0);o(s),c(()=>_(v,a(e).description)),i(t,s)};u(z,t=>{a(e).description&&t(Z)})}var W=p(z,2),H=r(W);{var aa=t=>{var s=Ba(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).followersCount)),i(t,s)};u(H,t=>{a(e).followersCount!==void 0&&t(aa)})}var T=p(H,2);{var ea=t=>{var s=Pa(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).followsCount)),i(t,s)};u(T,t=>{a(e).followsCount!==void 0&&t(ea)})}var ta=p(T,2);{var sa=t=>{var s=Wa(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).postsCount)),i(t,s)};u(ta,t=>{a(e).postsCount!==void 0&&t(sa)})}o(W);var ra=p(W,2);o(k),c(()=>{_(X,a(e).displayName||a(e).handle),_(Y,`@${a(e).handle??""}`),w(ra,"href",`https://witchsky.app/profile/${a(e).handle??""}`)}),i(g,k)},$$slots:{default:!0}}),o(M),o(d),i(l,d)};u(J,l=>{a(C)?l(K):a(h)?l(L,1):a(e)&&l(Q,2)})}y(2),o(F),i(m,F),va(),I()}export{Ia as component,Ga as universal};
+1 -1
.svelte-kit/output/client/_app/version.json
··· 1 - {"version":"1774903841109"} 1 + {"version":"1774912484423"}
.svelte-kit/output/client/frogeye.png

This is a binary file and will not be displayed.

.svelte-kit/output/client/froggie.png

This is a binary file and will not be displayed.

.svelte-kit/output/client/froggiejump.png

This is a binary file and will not be displayed.

.svelte-kit/output/client/froggiestand.png

This is a binary file and will not be displayed.

.svelte-kit/output/client/frogicon.png

This is a binary file and will not be displayed.

.svelte-kit/output/client/leaves.png

This is a binary file and will not be displayed.

+23 -24
.svelte-kit/output/prerendered/pages/index.html
··· 1 1 <!doctype html> 2 2 <html lang="en"> 3 - <head> 4 - <meta charset="utf-8" /> 5 - <link rel="icon" href="/frogcursor.png" /> 6 - <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 - <title>VODS VODS VODS</title> 8 - <link href="./_app/immutable/entry/start.YsP-T6iU.js" rel="modulepreload"> 9 - <link href="./_app/immutable/chunks/D9RahMPT.js" rel="modulepreload"> 10 - <link href="./_app/immutable/chunks/w0kPbzMq.js" rel="modulepreload"> 11 - <link href="./_app/immutable/chunks/B43_79mg.js" rel="modulepreload"> 12 - <link href="./_app/immutable/entry/app.BiVWJwsp.js" rel="modulepreload"> 13 - <link href="./_app/immutable/chunks/BcVkVDn_.js" rel="modulepreload"> 14 - <link href="./_app/immutable/chunks/mmStoiki.js" rel="modulepreload"> 15 - <link href="./_app/immutable/chunks/C_B-Ij-b.js" rel="modulepreload"> 16 - <link href="./_app/immutable/chunks/C6hdjiAW.js" rel="modulepreload"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <link rel="icon" href="/frogicon.png" /> 6 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 + <title>vod frog</title> 8 + <link href="./_app/immutable/entry/start.BUzUbSG3.js" rel="modulepreload"> 9 + <link href="./_app/immutable/chunks/C0nNmPgn.js" rel="modulepreload"> 10 + <link href="./_app/immutable/chunks/CkzjbUDB.js" rel="modulepreload"> 11 + <link href="./_app/immutable/chunks/DxGD2b0U.js" rel="modulepreload"> 12 + <link href="./_app/immutable/entry/app.CwuxgLSd.js" rel="modulepreload"> 13 + <link href="./_app/immutable/chunks/BsDbD4Ku.js" rel="modulepreload"> 14 + <link href="./_app/immutable/chunks/DGbOEUpF.js" rel="modulepreload"> 15 + <link href="./_app/immutable/chunks/XE2G8ySY.js" rel="modulepreload"> 16 + <link href="./_app/immutable/chunks/CFYBLbZM.js" rel="modulepreload"> 17 + <link href="./_app/immutable/chunks/Dr80VTgO.js" rel="modulepreload"> 17 18 18 - </head> 19 - <body data-sveltekit-prerender="auto"> 20 - 19 + </head> 20 + <body> 21 + <div style="display: contents"> 21 22 <script> 22 23 { 23 - __sveltekit_1uytokf = { 24 + __sveltekit_1gh8pzr = { 24 25 base: new URL(".", location).pathname.slice(0, -1) 25 26 }; 26 27 27 28 const element = document.currentScript.parentElement; 28 29 29 30 Promise.all([ 30 - import("./_app/immutable/entry/start.YsP-T6iU.js"), 31 - import("./_app/immutable/entry/app.BiVWJwsp.js") 31 + import("./_app/immutable/entry/start.BUzUbSG3.js"), 32 + import("./_app/immutable/entry/app.CwuxgLSd.js") 32 33 ]).then(([kit, app]) => { 33 34 kit.start(app, element); 34 35 }); 35 36 } 36 37 </script> 37 - 38 - </body> 39 - </html> 40 - body> 38 + </div> 39 + </body> 41 40 </html>
+67 -15
.svelte-kit/output/server/.vite/manifest.json
··· 10 10 "_internal.js" 11 11 ] 12 12 }, 13 + "_FrogHeader.8kzFzgPu.css": { 14 + "file": "_app/immutable/assets/FrogHeader.8kzFzgPu.css", 15 + "src": "_FrogHeader.8kzFzgPu.css" 16 + }, 17 + "_FrogHeader.js": { 18 + "file": "chunks/FrogHeader.js", 19 + "name": "FrogHeader", 20 + "css": [ 21 + "_app/immutable/assets/FrogHeader.8kzFzgPu.css" 22 + ] 23 + }, 13 24 "_environment.js": { 14 25 "file": "chunks/environment.js", 15 26 "name": "environment" 16 27 }, 17 28 "_exports.js": { 18 29 "file": "chunks/exports.js", 19 - "name": "exports", 20 - "imports": [ 21 - "_index.js", 22 - "_root.js" 23 - ] 30 + "name": "exports" 24 31 }, 25 32 "_false.js": { 26 33 "file": "chunks/false.js", ··· 28 35 }, 29 36 "_index.js": { 30 37 "file": "chunks/index.js", 31 - "name": "index" 38 + "name": "index", 39 + "imports": [ 40 + "_index2.js" 41 + ] 42 + }, 43 + "_index2.js": { 44 + "file": "chunks/index2.js", 45 + "name": "index", 46 + "imports": [ 47 + "_false.js" 48 + ] 32 49 }, 33 50 "_internal.js": { 34 51 "file": "chunks/internal.js", ··· 42 59 "file": "chunks/root.js", 43 60 "name": "root", 44 61 "imports": [ 45 - "_index.js", 46 - "_false.js" 62 + "_index2.js" 47 63 ] 48 64 }, 49 65 "_shared.js": { ··· 51 67 "name": "shared", 52 68 "imports": [ 53 69 "_utils.js" 70 + ] 71 + }, 72 + "_state.svelte.js": { 73 + "file": "chunks/state.svelte.js", 74 + "name": "state.svelte", 75 + "imports": [ 76 + "_index2.js", 77 + "_exports.js", 78 + "_root.js" 54 79 ] 55 80 }, 56 81 "_utils.js": { ··· 74 99 "src": "node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte", 75 100 "isEntry": true, 76 101 "imports": [ 77 - "_index.js", 102 + "_index2.js", 103 + "_state.svelte.js", 78 104 "_exports.js", 79 - "_root.js", 80 - "_utils.js" 105 + "_utils.js", 106 + "_index.js", 107 + "_root.js" 81 108 ] 82 109 }, 83 110 "node_modules/@sveltejs/kit/src/runtime/server/index.js": { ··· 91 118 "_shared.js", 92 119 "_exports.js", 93 120 "_utils.js", 121 + "_index.js", 94 122 "_internal.js" 95 123 ] 96 124 }, ··· 100 128 "src": "src/routes/+layout.svelte", 101 129 "isEntry": true, 102 130 "imports": [ 103 - "_index.js" 131 + "_index2.js" 104 132 ], 105 133 "css": [ 106 - "_app/immutable/assets/_layout.CyGpFWYY.css" 134 + "_app/immutable/assets/_layout.DIlgUleF.css" 107 135 ] 108 136 }, 109 137 "src/routes/+layout.ts": { ··· 118 146 "src": "src/routes/+page.svelte", 119 147 "isEntry": true, 120 148 "imports": [ 121 - "_index.js" 149 + "_index2.js", 150 + "_FrogHeader.js" 151 + ], 152 + "css": [ 153 + "_app/immutable/assets/_page.BGMtm5aI.css" 154 + ] 155 + }, 156 + "src/routes/profile/[handle]/+page.svelte": { 157 + "file": "entries/pages/profile/_handle_/_page.svelte.js", 158 + "name": "entries/pages/profile/_handle_/_page.svelte", 159 + "src": "src/routes/profile/[handle]/+page.svelte", 160 + "isEntry": true, 161 + "imports": [ 162 + "_index2.js", 163 + "_exports.js", 164 + "_utils.js", 165 + "_root.js", 166 + "_state.svelte.js", 167 + "_FrogHeader.js" 122 168 ], 123 169 "css": [ 124 - "_app/immutable/assets/_page.C2OXUsD9.css" 170 + "_app/immutable/assets/_page.CjGf6tQE.css" 125 171 ] 172 + }, 173 + "src/routes/profile/[handle]/+page.ts": { 174 + "file": "entries/pages/profile/_handle_/_page.ts.js", 175 + "name": "entries/pages/profile/_handle_/_page.ts", 176 + "src": "src/routes/profile/[handle]/+page.ts", 177 + "isEntry": true 126 178 } 127 179 }
+1
.svelte-kit/output/server/_app/immutable/assets/FrogHeader.8kzFzgPu.css
··· 1 + .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-clipped.svelte-7frlgw{position:relative}.wavy-fill.svelte-7frlgw{position:absolute;inset:0;z-index:0}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.wavy-stroke.svelte-7frlgw{position:absolute;inset:0;width:100%;height:100%;z-index:3;pointer-events:none;overflow:visible}.frog-header.svelte-1kxia9k{padding:30px 20px;position:relative}.title-area.svelte-1kxia9k{position:relative;display:inline-block}.logo-link.svelte-1kxia9k{text-decoration:none;color:inherit}.logo-text.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px;position:relative;z-index:1}.header-frog.svelte-1kxia9k{position:absolute;right:-80px;top:-60px;width:clamp(120px,18vw,220px);height:auto;z-index:2;transform:rotate(-10deg);filter:drop-shadow(2px 4px 6px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px;position:relative;z-index:0}.subtitle-link.svelte-1kxia9k{color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.subtitle-link.svelte-1kxia9k:hover{color:#ff3992}.subtitle.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}.header-frog.svelte-1kxia9k{right:-100px;top:-20px}}
-1
.svelte-kit/output/server/_app/immutable/assets/_layout.CyGpFWYY.css
··· 1 - .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-1;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;top:0;bottom:0;width:100px;z-index:100;pointer-events:none;opacity:.85}.plant-overlay.left.svelte-11afcec{left:10px}.plant-overlay.right.svelte-11afcec{right:10px}.plant-overlay.svelte-11afcec svg:where(.svelte-11afcec){width:100%;height:100%}@media(max-width:900px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
+1
.svelte-kit/output/server/_app/immutable/assets/_layout.DIlgUleF.css
··· 1 + .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-2;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;inset:0;z-index:-1;pointer-events:none;overflow:hidden;mix-blend-mode:multiply}.leaves.svelte-11afcec{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}@media(max-width:768px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Nunito,Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
+1
.svelte-kit/output/server/_app/immutable/assets/_page.BGMtm5aI.css
··· 1 + .player-wrapper.svelte-zbxgh1{position:relative;width:100%;background:#0a182b;overflow:hidden}.player-wrapper.svelte-zbxgh1:fullscreen{display:flex;align-items:center;justify-content:center}.player-wrapper.svelte-zbxgh1:fullscreen video:where(.svelte-zbxgh1){max-height:100vh;max-width:100vw;object-fit:contain}video.svelte-zbxgh1{width:100%;display:block;max-height:70vh;cursor:pointer}.controls.svelte-zbxgh1{position:absolute;bottom:5%;left:10%;right:15%;opacity:0;transition:opacity .25s ease;pointer-events:none}.controls.visible.svelte-zbxgh1{opacity:1;pointer-events:auto}.scrub-bar.svelte-zbxgh1{position:relative;height:48px;cursor:pointer}.scrub-frog.svelte-zbxgh1{position:absolute;bottom:0;transform:translate(-50%);cursor:grab;transition:left .05s linear;z-index:2;padding:6px}.scrub-frog.svelte-zbxgh1:active{cursor:grabbing}.scrub-frog.flipped.svelte-zbxgh1{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-zbxgh1{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.5));pointer-events:none}.fullscreen-btn.svelte-zbxgh1{all:unset;position:absolute;bottom:5%;right:8%;cursor:pointer;opacity:0;transition:opacity .25s ease,transform .2s ease;z-index:5}.fullscreen-btn.visible.svelte-zbxgh1{opacity:1}.fullscreen-btn.svelte-zbxgh1:hover{transform:scale(1.15)}.frogeye.svelte-zbxgh1{width:44px;height:44px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4))}.error-overlay.svelte-zbxgh1{position:absolute;bottom:15%;left:10%;right:10%;background:#ff3992d9;color:#ffdeed;padding:8px 12px;border-radius:6px;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem}.card.svelte-1nxalmg{all:unset;cursor:url(/frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:8px;text-align:right}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.scrub-frog.svelte-1nxalmg{position:absolute;bottom:0%;z-index:4;pointer-events:none;transform:translate(-50%);transition:left .05s linear}.scrub-frog.flipped.svelte-1nxalmg{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-1nxalmg{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4));image-rendering:auto}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:14px 10px 8px}.title.svelte-1nxalmg{margin:0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.9rem;font-weight:700;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 clamp(24px,7vw,120px) 60px}.player-section.svelte-1uha8ag{margin-bottom:40px;margin-top:20px;padding:0 10px}.player-info.svelte-1uha8ag{padding:20px 4px}.player-title.svelte-1uha8ag{margin:0;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.4rem,3vw,2rem);color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(300px,100%),1fr));gap:clamp(32px,5vw,50px);padding:20px clamp(16px,3vw,24px)}.pagination.svelte-1uha8ag{display:flex;justify-content:center;align-items:center;gap:20px;padding:30px}.page-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:3px solid #0a182b;padding:12px 32px;border-radius:40px;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.page-btn.svelte-1uha8ag:hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.page-btn.svelte-1uha8ag:disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.page-num.svelte-1uha8ag{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #ff3992}
-1
.svelte-kit/output/server/_app/immutable/assets/_page.C2OXUsD9.css
··· 1 - .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-svg.svelte-7frlgw{position:absolute;inset:-8px;width:calc(100% + 16px);height:calc(100% + 16px);z-index:0;pointer-events:none}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.card.svelte-1nxalmg{all:unset;cursor:url(/frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Fang,system-ui,sans-serif;font-size:1rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:6px}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.thumb-img.hidden.svelte-1nxalmg{opacity:0}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:8px 2px 0}.title.svelte-1nxalmg{margin:0;font-family:Fang,system-ui,sans-serif;font-size:.9rem;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.frog-header.svelte-1kxia9k{padding:30px 20px 10px;position:relative}.title-row.svelte-1kxia9k{display:flex;align-items:flex-end;gap:10px}.logo-text.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px}.header-frog.svelte-1kxia9k{width:clamp(60px,10vw,120px);height:auto;transform:rotate(-10deg);filter:drop-shadow(2px 3px 4px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px}.subtitle.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 100px 60px}.player-section.svelte-1uha8ag{margin-bottom:30px;padding:0 10px}.player-info.svelte-1uha8ag{display:flex;justify-content:space-between;align-items:flex-start;padding:14px 4px;gap:16px}.player-title.svelte-1uha8ag{margin:0;font-family:Fang,system-ui,sans-serif;font-size:1.2rem;color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.close-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:2px solid #39FF44;border-radius:50%;width:36px;height:36px;font-size:1rem;cursor:pointer;flex-shrink:0;font-family:Fang,system-ui,sans-serif;transition:background .15s,color .15s}.close-btn.svelte-1uha8ag:hover{background:#ff3992;border-color:#ff3992;color:#ffdeed}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:30px;padding:20px 10px}.load-more.svelte-1uha8ag{text-align:center;padding:30px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag){background:#0a182b;color:#39ff44;border:3px solid #0A182B;padding:12px 36px;border-radius:40px;font-family:PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Fang,system-ui,sans-serif;border:2px solid #FF3992}@media(max-width:768px){.app.svelte-1uha8ag{padding:0 16px 40px}.grid.svelte-1uha8ag{grid-template-columns:1fr;gap:24px;padding:10px 0}}
+1
.svelte-kit/output/server/_app/immutable/assets/_page.CjGf6tQE.css
··· 1 + .profile-page.svelte-oxml5t{max-width:800px;margin:0 auto;padding:0 clamp(24px,7vw,80px) 60px}.loading.svelte-oxml5t{text-align:center;padding:60px 20px}.loading-frog.svelte-oxml5t{width:64px;height:auto;animation:svelte-oxml5t-hop .6s ease-in-out infinite alternate}@keyframes svelte-oxml5t-hop{0%{transform:translateY(0)}to{transform:translateY(-12px)}}.loading-text.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.2rem;color:#0a182b;margin-top:12px}.error.svelte-oxml5t{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:20px 0;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #FF3992}.profile-layout.svelte-oxml5t{display:flex;flex-direction:column;gap:24px}.banner-img.svelte-oxml5t{width:100%;display:block;aspect-ratio:3 / 1;object-fit:cover}.profile-card-area.svelte-oxml5t{margin-top:-20px}.profile-card.svelte-oxml5t{display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px}.avatar-wrapper.svelte-oxml5t{width:clamp(80px,15vw,120px);margin-bottom:8px}.avatar.svelte-oxml5t{width:100%;display:block;aspect-ratio:1;object-fit:cover;border-radius:0}.display-name.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.8rem,4vw,2.8rem);color:#0a182b;margin:0;line-height:1.1}.handle.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:1rem;color:#0a182b;opacity:.7;margin:0}.description.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.95rem;color:#0a182b;margin:8px 0;max-width:500px;line-height:1.5}.stats.svelte-oxml5t{display:flex;gap:clamp(16px,4vw,32px);margin:12px 0}.stat.svelte-oxml5t{display:flex;flex-direction:column;align-items:center}.stat-num.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#0a182b;font-weight:700}.stat-label.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#0a182b;opacity:.6}.profile-link.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;margin-top:8px;transition:color .15s}.profile-link.svelte-oxml5t:hover{color:#ff3992}.back-link.svelte-oxml5t{text-align:center;padding:30px}.back-link.svelte-oxml5t a:where(.svelte-oxml5t){font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.back-link.svelte-oxml5t a:where(.svelte-oxml5t):hover{color:#ff3992}
+10
.svelte-kit/output/server/chunks/FrogHeader.js
··· 1 + import "clsx"; 2 + function FrogHeader($$renderer, $$props) { 3 + $$renderer.component(($$renderer2) => { 4 + let { onHomeClick } = $$props; 5 + $$renderer2.push(`<header class="frog-header svelte-1kxia9k"><div class="title-area svelte-1kxia9k"><a href="/" class="logo-link svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1></a> <img src="/froggie.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k"><a href="https://witchsky.app/profile/goose.art" target="_blank" class="subtitle-link svelte-1kxia9k">@goose.art</a> using <a href="https://witchsky.app/profile/stream.place" target="_blank" class="subtitle-link svelte-1kxia9k">@stream.place</a></p></div></header>`); 6 + }); 7 + } 8 + export { 9 + FrogHeader as F 10 + };
+4 -61
.svelte-kit/output/server/chunks/exports.js
··· 1 - import { n as noop } from "./index.js"; 2 - import { s as safe_not_equal } from "./root.js"; 3 1 const SCHEME = /^[a-z][a-z\d+\-.]+:/i; 4 2 const internal = new URL("sveltekit-internal://"); 5 3 function resolve(base, path) { ··· 97 95 }; 98 96 } 99 97 } 100 - const subscriber_queue = []; 101 - function readable(value, start) { 102 - return { 103 - subscribe: writable(value, start).subscribe 104 - }; 105 - } 106 - function writable(value, start = noop) { 107 - let stop = null; 108 - const subscribers = /* @__PURE__ */ new Set(); 109 - function set(new_value) { 110 - if (safe_not_equal(value, new_value)) { 111 - value = new_value; 112 - if (stop) { 113 - const run_queue = !subscriber_queue.length; 114 - for (const subscriber of subscribers) { 115 - subscriber[1](); 116 - subscriber_queue.push(subscriber, value); 117 - } 118 - if (run_queue) { 119 - for (let i = 0; i < subscriber_queue.length; i += 2) { 120 - subscriber_queue[i][0](subscriber_queue[i + 1]); 121 - } 122 - subscriber_queue.length = 0; 123 - } 124 - } 125 - } 126 - } 127 - function update(fn) { 128 - set(fn( 129 - /** @type {T} */ 130 - value 131 - )); 132 - } 133 - function subscribe(run, invalidate = noop) { 134 - const subscriber = [run, invalidate]; 135 - subscribers.add(subscriber); 136 - if (subscribers.size === 1) { 137 - stop = start(set, update) || noop; 138 - } 139 - run( 140 - /** @type {T} */ 141 - value 142 - ); 143 - return () => { 144 - subscribers.delete(subscriber); 145 - if (subscribers.size === 0 && stop) { 146 - stop(); 147 - stop = null; 148 - } 149 - }; 150 - } 151 - return { set, update, subscribe }; 152 - } 153 98 function validator(expected) { 154 99 function validate(module, file) { 155 100 if (!module) return; ··· 220 165 validate_page_server_exports as c, 221 166 disable_search as d, 222 167 validate_page_exports as e, 223 - resolve as f, 224 - decode_pathname as g, 225 - validate_server_exports as h, 168 + decode_pathname as f, 169 + validate_server_exports as g, 226 170 make_trackable as m, 227 171 normalize_path as n, 228 - readable as r, 229 - validate_layout_server_exports as v, 230 - writable as w 172 + resolve as r, 173 + validate_layout_server_exports as v 231 174 };
+42 -1251
.svelte-kit/output/server/chunks/index.js
··· 1 - import { clsx as clsx$1 } from "clsx"; 2 - import * as devalue from "devalue"; 3 - var is_array = Array.isArray; 4 - var index_of = Array.prototype.indexOf; 5 - var includes = Array.prototype.includes; 6 - var array_from = Array.from; 7 - var define_property = Object.defineProperty; 8 - var get_descriptor = Object.getOwnPropertyDescriptor; 9 - var object_prototype = Object.prototype; 10 - var array_prototype = Array.prototype; 11 - var get_prototype_of = Object.getPrototypeOf; 12 - var is_extensible = Object.isExtensible; 13 - var has_own_property = Object.prototype.hasOwnProperty; 14 - const noop = () => { 15 - }; 16 - function run_all(arr) { 17 - for (var i = 0; i < arr.length; i++) { 18 - arr[i](); 19 - } 20 - } 21 - function deferred() { 22 - var resolve; 23 - var reject; 24 - var promise = new Promise((res, rej) => { 25 - resolve = res; 26 - reject = rej; 27 - }); 28 - return { promise, resolve, reject }; 29 - } 30 - const DERIVED = 1 << 1; 31 - const EFFECT = 1 << 2; 32 - const RENDER_EFFECT = 1 << 3; 33 - const MANAGED_EFFECT = 1 << 24; 34 - const BLOCK_EFFECT = 1 << 4; 35 - const BRANCH_EFFECT = 1 << 5; 36 - const ROOT_EFFECT = 1 << 6; 37 - const BOUNDARY_EFFECT = 1 << 7; 38 - const CONNECTED = 1 << 9; 39 - const CLEAN = 1 << 10; 40 - const DIRTY = 1 << 11; 41 - const MAYBE_DIRTY = 1 << 12; 42 - const INERT = 1 << 13; 43 - const DESTROYED = 1 << 14; 44 - const REACTION_RAN = 1 << 15; 45 - const DESTROYING = 1 << 25; 46 - const EFFECT_TRANSPARENT = 1 << 16; 47 - const EAGER_EFFECT = 1 << 17; 48 - const HEAD_EFFECT = 1 << 18; 49 - const EFFECT_PRESERVED = 1 << 19; 50 - const USER_EFFECT = 1 << 20; 51 - const WAS_MARKED = 1 << 16; 52 - const REACTION_IS_UPDATING = 1 << 21; 53 - const ASYNC = 1 << 22; 54 - const ERROR_VALUE = 1 << 23; 55 - const STATE_SYMBOL = /* @__PURE__ */ Symbol("$state"); 56 - const LEGACY_PROPS = /* @__PURE__ */ Symbol("legacy props"); 57 - const STALE_REACTION = new class StaleReactionError extends Error { 58 - name = "StaleReactionError"; 59 - message = "The reaction that called `getAbortSignal()` was re-run or destroyed"; 60 - }(); 61 - const COMMENT_NODE = 8; 62 - function lifecycle_outside_component(name) { 63 - { 64 - throw new Error(`https://svelte.dev/e/lifecycle_outside_component`); 65 - } 66 - } 67 - const HYDRATION_START = "["; 68 - const HYDRATION_START_ELSE = "[!"; 69 - const HYDRATION_START_FAILED = "[?"; 70 - const HYDRATION_END = "]"; 71 - const HYDRATION_ERROR = {}; 72 - const ELEMENT_IS_NAMESPACED = 1; 73 - const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; 74 - const ELEMENT_IS_INPUT = 1 << 2; 75 - const UNINITIALIZED = /* @__PURE__ */ Symbol(); 76 - const DOM_BOOLEAN_ATTRIBUTES = [ 77 - "allowfullscreen", 78 - "async", 79 - "autofocus", 80 - "autoplay", 81 - "checked", 82 - "controls", 83 - "default", 84 - "disabled", 85 - "formnovalidate", 86 - "indeterminate", 87 - "inert", 88 - "ismap", 89 - "loop", 90 - "multiple", 91 - "muted", 92 - "nomodule", 93 - "novalidate", 94 - "open", 95 - "playsinline", 96 - "readonly", 97 - "required", 98 - "reversed", 99 - "seamless", 100 - "selected", 101 - "webkitdirectory", 102 - "defer", 103 - "disablepictureinpicture", 104 - "disableremoteplayback" 105 - ]; 106 - function is_boolean_attribute(name) { 107 - return DOM_BOOLEAN_ATTRIBUTES.includes(name); 108 - } 109 - const PASSIVE_EVENTS = ["touchstart", "touchmove"]; 110 - function is_passive_event(name) { 111 - return PASSIVE_EVENTS.includes(name); 112 - } 113 - const ATTR_REGEX = /[&"<]/g; 114 - const CONTENT_REGEX = /[&<]/g; 115 - function escape_html(value, is_attr) { 116 - const str = String(value ?? ""); 117 - const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; 118 - pattern.lastIndex = 0; 119 - let escaped = ""; 120 - let last = 0; 121 - while (pattern.test(str)) { 122 - const i = pattern.lastIndex - 1; 123 - const ch = str[i]; 124 - escaped += str.substring(last, i) + (ch === "&" ? "&amp;" : ch === '"' ? "&quot;" : "&lt;"); 125 - last = i + 1; 126 - } 127 - return escaped + str.substring(last); 128 - } 129 - const replacements = { 130 - translate: /* @__PURE__ */ new Map([ 131 - [true, "yes"], 132 - [false, "no"] 133 - ]) 134 - }; 135 - function attr(name, value, is_boolean = false) { 136 - if (name === "hidden" && value !== "until-found") { 137 - is_boolean = true; 138 - } 139 - if (value == null || !value && is_boolean) return ""; 140 - const normalized = has_own_property.call(replacements, name) && replacements[name].get(value) || value; 141 - const assignment = is_boolean ? `=""` : `="${escape_html(normalized, true)}"`; 142 - return ` ${name}${assignment}`; 143 - } 144 - function clsx(value) { 145 - if (typeof value === "object") { 146 - return clsx$1(value); 147 - } else { 148 - return value ?? ""; 149 - } 150 - } 151 - const whitespace = [..." \n\r\f \v\uFEFF"]; 152 - function to_class(value, hash, directives) { 153 - var classname = value == null ? "" : "" + value; 154 - if (hash) { 155 - classname = classname ? classname + " " + hash : hash; 156 - } 157 - if (directives) { 158 - for (var key of Object.keys(directives)) { 159 - if (directives[key]) { 160 - classname = classname ? classname + " " + key : key; 161 - } else if (classname.length) { 162 - var len = key.length; 163 - var a = 0; 164 - while ((a = classname.indexOf(key, a)) >= 0) { 165 - var b = a + len; 166 - if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) { 167 - classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1); 168 - } else { 169 - a = b; 170 - } 171 - } 172 - } 173 - } 174 - } 175 - return classname === "" ? null : classname; 1 + import { n as noop, s as safe_not_equal } from "./index2.js"; 2 + const subscriber_queue = []; 3 + function readable(value, start) { 4 + return { 5 + subscribe: writable(value, start).subscribe 6 + }; 176 7 } 177 - function append_styles(styles, important = false) { 178 - var separator = important ? " !important;" : ";"; 179 - var css = ""; 180 - for (var key of Object.keys(styles)) { 181 - var value = styles[key]; 182 - if (value != null && value !== "") { 183 - css += " " + key + ": " + value + separator; 184 - } 185 - } 186 - return css; 187 - } 188 - function to_css_name(name) { 189 - if (name[0] !== "-" || name[1] !== "-") { 190 - return name.toLowerCase(); 191 - } 192 - return name; 193 - } 194 - function to_style(value, styles) { 195 - if (styles) { 196 - var new_style = ""; 197 - var normal_styles; 198 - var important_styles; 199 - if (Array.isArray(styles)) { 200 - normal_styles = styles[0]; 201 - important_styles = styles[1]; 202 - } else { 203 - normal_styles = styles; 204 - } 205 - if (value) { 206 - value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim(); 207 - var in_str = false; 208 - var in_apo = 0; 209 - var in_comment = false; 210 - var reserved_names = []; 211 - if (normal_styles) { 212 - reserved_names.push(...Object.keys(normal_styles).map(to_css_name)); 213 - } 214 - if (important_styles) { 215 - reserved_names.push(...Object.keys(important_styles).map(to_css_name)); 216 - } 217 - var start_index = 0; 218 - var name_index = -1; 219 - const len = value.length; 220 - for (var i = 0; i < len; i++) { 221 - var c = value[i]; 222 - if (in_comment) { 223 - if (c === "/" && value[i - 1] === "*") { 224 - in_comment = false; 225 - } 226 - } else if (in_str) { 227 - if (in_str === c) { 228 - in_str = false; 229 - } 230 - } else if (c === "/" && value[i + 1] === "*") { 231 - in_comment = true; 232 - } else if (c === '"' || c === "'") { 233 - in_str = c; 234 - } else if (c === "(") { 235 - in_apo++; 236 - } else if (c === ")") { 237 - in_apo--; 8 + function writable(value, start = noop) { 9 + let stop = null; 10 + const subscribers = /* @__PURE__ */ new Set(); 11 + function set(new_value) { 12 + if (safe_not_equal(value, new_value)) { 13 + value = new_value; 14 + if (stop) { 15 + const run_queue = !subscriber_queue.length; 16 + for (const subscriber of subscribers) { 17 + subscriber[1](); 18 + subscriber_queue.push(subscriber, value); 238 19 } 239 - if (!in_comment && in_str === false && in_apo === 0) { 240 - if (c === ":" && name_index === -1) { 241 - name_index = i; 242 - } else if (c === ";" || i === len - 1) { 243 - if (name_index !== -1) { 244 - var name = to_css_name(value.substring(start_index, name_index).trim()); 245 - if (!reserved_names.includes(name)) { 246 - if (c !== ";") { 247 - i++; 248 - } 249 - var property = value.substring(start_index, i).trim(); 250 - new_style += " " + property + ";"; 251 - } 252 - } 253 - start_index = i + 1; 254 - name_index = -1; 20 + if (run_queue) { 21 + for (let i = 0; i < subscriber_queue.length; i += 2) { 22 + subscriber_queue[i][0](subscriber_queue[i + 1]); 255 23 } 24 + subscriber_queue.length = 0; 256 25 } 257 26 } 258 27 } 259 - if (normal_styles) { 260 - new_style += append_styles(normal_styles); 261 - } 262 - if (important_styles) { 263 - new_style += append_styles(important_styles, true); 264 - } 265 - new_style = new_style.trim(); 266 - return new_style === "" ? null : new_style; 267 28 } 268 - return value == null ? null : String(value); 269 - } 270 - const BLOCK_OPEN = `<!--${HYDRATION_START}-->`; 271 - const BLOCK_CLOSE = `<!--${HYDRATION_END}-->`; 272 - const EMPTY_COMMENT = `<!---->`; 273 - let controller = null; 274 - function abort() { 275 - controller?.abort(STALE_REACTION); 276 - controller = null; 277 - } 278 - function await_invalid() { 279 - const error = new Error(`await_invalid 280 - Encountered asynchronous work while rendering synchronously. 281 - https://svelte.dev/e/await_invalid`); 282 - error.name = "Svelte error"; 283 - throw error; 284 - } 285 - function invalid_csp() { 286 - const error = new Error(`invalid_csp 287 - \`csp.nonce\` was set while \`csp.hash\` was \`true\`. These options cannot be used simultaneously. 288 - https://svelte.dev/e/invalid_csp`); 289 - error.name = "Svelte error"; 290 - throw error; 291 - } 292 - function server_context_required() { 293 - const error = new Error(`server_context_required 294 - Could not resolve \`render\` context. 295 - https://svelte.dev/e/server_context_required`); 296 - error.name = "Svelte error"; 297 - throw error; 298 - } 299 - var ssr_context = null; 300 - function set_ssr_context(v) { 301 - ssr_context = v; 302 - } 303 - function getContext(key) { 304 - const context_map = get_or_init_context_map(); 305 - const result = ( 306 - /** @type {T} */ 307 - context_map.get(key) 308 - ); 309 - return result; 310 - } 311 - function setContext(key, context) { 312 - get_or_init_context_map().set(key, context); 313 - return context; 314 - } 315 - function get_or_init_context_map(name) { 316 - if (ssr_context === null) { 317 - lifecycle_outside_component(); 29 + function update(fn) { 30 + set(fn( 31 + /** @type {T} */ 32 + value 33 + )); 318 34 } 319 - return ssr_context.c ??= new Map(get_parent_context(ssr_context) || void 0); 320 - } 321 - function push(fn) { 322 - ssr_context = { p: ssr_context, c: null, r: null }; 323 - } 324 - function pop() { 325 - ssr_context = /** @type {SSRContext} */ 326 - ssr_context.p; 327 - } 328 - function get_parent_context(ssr_context2) { 329 - let parent = ssr_context2.p; 330 - while (parent !== null) { 331 - const context_map = parent.c; 332 - if (context_map !== null) { 333 - return context_map; 35 + function subscribe(run, invalidate = noop) { 36 + const subscriber = [run, invalidate]; 37 + subscribers.add(subscriber); 38 + if (subscribers.size === 1) { 39 + stop = start(set, update) || noop; 334 40 } 335 - parent = parent.p; 336 - } 337 - return null; 338 - } 339 - function unresolved_hydratable(key, stack) { 340 - { 341 - console.warn(`https://svelte.dev/e/unresolved_hydratable`); 342 - } 343 - } 344 - function get_render_context() { 345 - const store = als?.getStore(); 346 - { 347 - server_context_required(); 348 - } 349 - return store; 350 - } 351 - let als = null; 352 - let text_encoder; 353 - let crypto; 354 - const obfuscated_import = (module_name) => import( 355 - /* @vite-ignore */ 356 - module_name 357 - ); 358 - async function sha256(data) { 359 - text_encoder ??= new TextEncoder(); 360 - crypto ??= globalThis.crypto?.subtle?.digest ? globalThis.crypto : ( 361 - // @ts-ignore - we don't install node types in the prod build 362 - // don't use import('node:crypto') directly because static analysers will think we rely on node when we don't 363 - (await obfuscated_import("node:crypto")).webcrypto 364 - ); 365 - const hash_buffer = await crypto.subtle.digest("SHA-256", text_encoder.encode(data)); 366 - return base64_encode(hash_buffer); 367 - } 368 - function base64_encode(bytes) { 369 - if (globalThis.Buffer) { 370 - return globalThis.Buffer.from(bytes).toString("base64"); 371 - } 372 - let binary = ""; 373 - for (let i = 0; i < bytes.length; i++) { 374 - binary += String.fromCharCode(bytes[i]); 375 - } 376 - return btoa(binary); 377 - } 378 - class Renderer { 379 - /** 380 - * The contents of the renderer. 381 - * @type {RendererItem[]} 382 - */ 383 - #out = []; 384 - /** 385 - * Any `onDestroy` callbacks registered during execution of this renderer. 386 - * @type {(() => void)[] | undefined} 387 - */ 388 - #on_destroy = void 0; 389 - /** 390 - * Whether this renderer is a component body. 391 - * @type {boolean} 392 - */ 393 - #is_component_body = false; 394 - /** 395 - * If set, this renderer is an error boundary. When async collection 396 - * of the children fails, the failed snippet is rendered instead. 397 - * @type {{ 398 - * failed: (renderer: Renderer, error: unknown, reset: () => void) => void; 399 - * transformError: (error: unknown) => unknown; 400 - * context: SSRContext | null; 401 - * } | null} 402 - */ 403 - #boundary = null; 404 - /** 405 - * The type of string content that this renderer is accumulating. 406 - * @type {RendererType} 407 - */ 408 - type; 409 - /** @type {Renderer | undefined} */ 410 - #parent; 411 - /** 412 - * Asynchronous work associated with this renderer 413 - * @type {Promise<void> | undefined} 414 - */ 415 - promise = void 0; 416 - /** 417 - * State which is associated with the content tree as a whole. 418 - * It will be re-exposed, uncopied, on all children. 419 - * @type {SSRState} 420 - * @readonly 421 - */ 422 - global; 423 - /** 424 - * State that is local to the branch it is declared in. 425 - * It will be shallow-copied to all children. 426 - * 427 - * @type {{ select_value: string | undefined }} 428 - */ 429 - local; 430 - /** 431 - * @param {SSRState} global 432 - * @param {Renderer | undefined} [parent] 433 - */ 434 - constructor(global, parent) { 435 - this.#parent = parent; 436 - this.global = global; 437 - this.local = parent ? { ...parent.local } : { select_value: void 0 }; 438 - this.type = parent ? parent.type : "body"; 439 - } 440 - /** 441 - * @param {(renderer: Renderer) => void} fn 442 - */ 443 - head(fn) { 444 - const head2 = new Renderer(this.global, this); 445 - head2.type = "head"; 446 - this.#out.push(head2); 447 - head2.child(fn); 448 - } 449 - /** 450 - * @param {Array<Promise<void>>} blockers 451 - * @param {(renderer: Renderer) => void} fn 452 - */ 453 - async_block(blockers, fn) { 454 - this.#out.push(BLOCK_OPEN); 455 - this.async(blockers, fn); 456 - this.#out.push(BLOCK_CLOSE); 457 - } 458 - /** 459 - * @param {Array<Promise<void>>} blockers 460 - * @param {(renderer: Renderer) => void} fn 461 - */ 462 - async(blockers, fn) { 463 - let callback = fn; 464 - if (blockers.length > 0) { 465 - const context = ssr_context; 466 - callback = (renderer) => { 467 - return Promise.all(blockers).then(() => { 468 - const previous_context = ssr_context; 469 - try { 470 - set_ssr_context(context); 471 - return fn(renderer); 472 - } finally { 473 - set_ssr_context(previous_context); 474 - } 475 - }); 476 - }; 477 - } 478 - this.child(callback); 479 - } 480 - /** 481 - * @param {Array<() => void>} thunks 482 - */ 483 - run(thunks) { 484 - const context = ssr_context; 485 - let promise = Promise.resolve(thunks[0]()); 486 - const promises = [promise]; 487 - for (const fn of thunks.slice(1)) { 488 - promise = promise.then(() => { 489 - const previous_context = ssr_context; 490 - set_ssr_context(context); 491 - try { 492 - return fn(); 493 - } finally { 494 - set_ssr_context(previous_context); 495 - } 496 - }); 497 - promises.push(promise); 498 - } 499 - promise.catch(noop); 500 - this.promise = promise; 501 - return promises; 502 - } 503 - /** 504 - * @param {(renderer: Renderer) => MaybePromise<void>} fn 505 - */ 506 - child_block(fn) { 507 - this.#out.push(BLOCK_OPEN); 508 - this.child(fn); 509 - this.#out.push(BLOCK_CLOSE); 510 - } 511 - /** 512 - * Create a child renderer. The child renderer inherits the state from the parent, 513 - * but has its own content. 514 - * @param {(renderer: Renderer) => MaybePromise<void>} fn 515 - */ 516 - child(fn) { 517 - const child = new Renderer(this.global, this); 518 - this.#out.push(child); 519 - const parent = ssr_context; 520 - set_ssr_context({ 521 - ...ssr_context, 522 - p: parent, 523 - c: null, 524 - r: child 525 - }); 526 - const result = fn(child); 527 - set_ssr_context(parent); 528 - if (result instanceof Promise) { 529 - result.catch(noop); 530 - result.finally(() => set_ssr_context(null)).catch(noop); 531 - if (child.global.mode === "sync") { 532 - await_invalid(); 533 - } 534 - child.promise = result; 535 - } 536 - return child; 537 - } 538 - /** 539 - * Render children inside an error boundary. If the children throw and the API-level 540 - * `transformError` transform handles the error (doesn't re-throw), the `failed` snippet is 541 - * rendered instead. Otherwise the error propagates. 542 - * 543 - * @param {{ failed?: (renderer: Renderer, error: unknown, reset: () => void) => void }} props 544 - * @param {(renderer: Renderer) => MaybePromise<void>} children_fn 545 - */ 546 - boundary(props, children_fn) { 547 - const child = new Renderer(this.global, this); 548 - this.#out.push(child); 549 - const parent_context = ssr_context; 550 - if (props.failed) { 551 - child.#boundary = { 552 - failed: props.failed, 553 - transformError: this.global.transformError, 554 - context: parent_context 555 - }; 556 - } 557 - set_ssr_context({ 558 - ...ssr_context, 559 - p: parent_context, 560 - c: null, 561 - r: child 562 - }); 563 - try { 564 - const result = children_fn(child); 565 - set_ssr_context(parent_context); 566 - if (result instanceof Promise) { 567 - if (child.global.mode === "sync") { 568 - await_invalid(); 569 - } 570 - result.catch(noop); 571 - child.promise = result; 572 - } 573 - } catch (error) { 574 - set_ssr_context(parent_context); 575 - const failed_snippet = props.failed; 576 - if (!failed_snippet) throw error; 577 - const result = this.global.transformError(error); 578 - child.#out.length = 0; 579 - child.#boundary = null; 580 - if (result instanceof Promise) { 581 - if (this.global.mode === "sync") { 582 - await_invalid(); 583 - } 584 - child.promise = /** @type {Promise<unknown>} */ 585 - result.then((transformed) => { 586 - set_ssr_context(parent_context); 587 - child.#out.push(Renderer.#serialize_failed_boundary(transformed)); 588 - failed_snippet(child, transformed, noop); 589 - child.#out.push(BLOCK_CLOSE); 590 - }); 591 - child.promise.catch(noop); 592 - } else { 593 - child.#out.push(Renderer.#serialize_failed_boundary(result)); 594 - failed_snippet(child, result, noop); 595 - child.#out.push(BLOCK_CLOSE); 596 - } 597 - } 598 - } 599 - /** 600 - * Create a component renderer. The component renderer inherits the state from the parent, 601 - * but has its own content. It is treated as an ordering boundary for ondestroy callbacks. 602 - * @param {(renderer: Renderer) => MaybePromise<void>} fn 603 - * @param {Function} [component_fn] 604 - * @returns {void} 605 - */ 606 - component(fn, component_fn) { 607 - push(); 608 - const child = this.child(fn); 609 - child.#is_component_body = true; 610 - pop(); 611 - } 612 - /** 613 - * @param {Record<string, any>} attrs 614 - * @param {(renderer: Renderer) => void} fn 615 - * @param {string | undefined} [css_hash] 616 - * @param {Record<string, boolean> | undefined} [classes] 617 - * @param {Record<string, string> | undefined} [styles] 618 - * @param {number | undefined} [flags] 619 - * @param {boolean | undefined} [is_rich] 620 - * @returns {void} 621 - */ 622 - select(attrs, fn, css_hash, classes, styles, flags, is_rich) { 623 - const { value, ...select_attrs } = attrs; 624 - this.push(`<select${attributes(select_attrs, css_hash, classes, styles, flags)}>`); 625 - this.child((renderer) => { 626 - renderer.local.select_value = value; 627 - fn(renderer); 628 - }); 629 - this.push(`${is_rich ? "<!>" : ""}</select>`); 630 - } 631 - /** 632 - * @param {Record<string, any>} attrs 633 - * @param {string | number | boolean | ((renderer: Renderer) => void)} body 634 - * @param {string | undefined} [css_hash] 635 - * @param {Record<string, boolean> | undefined} [classes] 636 - * @param {Record<string, string> | undefined} [styles] 637 - * @param {number | undefined} [flags] 638 - * @param {boolean | undefined} [is_rich] 639 - */ 640 - option(attrs, body, css_hash, classes, styles, flags, is_rich) { 641 - this.#out.push(`<option${attributes(attrs, css_hash, classes, styles, flags)}`); 642 - const close = (renderer, value, { head: head2, body: body2 }) => { 643 - if (has_own_property.call(attrs, "value")) { 644 - value = attrs.value; 645 - } 646 - if (value === this.local.select_value) { 647 - renderer.#out.push(' selected=""'); 648 - } 649 - renderer.#out.push(`>${body2}${is_rich ? "<!>" : ""}</option>`); 650 - if (head2) { 651 - renderer.head((child) => child.push(head2)); 652 - } 653 - }; 654 - if (typeof body === "function") { 655 - this.child((renderer) => { 656 - const r = new Renderer(this.global, this); 657 - body(r); 658 - if (this.global.mode === "async") { 659 - return r.#collect_content_async().then((content) => { 660 - close(renderer, content.body.replaceAll("<!---->", ""), content); 661 - }); 662 - } else { 663 - const content = r.#collect_content(); 664 - close(renderer, content.body.replaceAll("<!---->", ""), content); 665 - } 666 - }); 667 - } else { 668 - close(this, body, { body: escape_html(body) }); 669 - } 670 - } 671 - /** 672 - * @param {(renderer: Renderer) => void} fn 673 - */ 674 - title(fn) { 675 - const path = this.get_path(); 676 - const close = (head2) => { 677 - this.global.set_title(head2, path); 678 - }; 679 - this.child((renderer) => { 680 - const r = new Renderer(renderer.global, renderer); 681 - fn(r); 682 - if (renderer.global.mode === "async") { 683 - return r.#collect_content_async().then((content) => { 684 - close(content.head); 685 - }); 686 - } else { 687 - const content = r.#collect_content(); 688 - close(content.head); 689 - } 690 - }); 691 - } 692 - /** 693 - * @param {string | (() => Promise<string>)} content 694 - */ 695 - push(content) { 696 - if (typeof content === "function") { 697 - this.child(async (renderer) => renderer.push(await content())); 698 - } else { 699 - this.#out.push(content); 700 - } 701 - } 702 - /** 703 - * @param {() => void} fn 704 - */ 705 - on_destroy(fn) { 706 - (this.#on_destroy ??= []).push(fn); 707 - } 708 - /** 709 - * @returns {number[]} 710 - */ 711 - get_path() { 712 - return this.#parent ? [...this.#parent.get_path(), this.#parent.#out.indexOf(this)] : []; 713 - } 714 - /** 715 - * @deprecated this is needed for legacy component bindings 716 - */ 717 - copy() { 718 - const copy = new Renderer(this.global, this.#parent); 719 - copy.#out = this.#out.map((item) => item instanceof Renderer ? item.copy() : item); 720 - copy.promise = this.promise; 721 - return copy; 722 - } 723 - /** 724 - * @param {Renderer} other 725 - * @deprecated this is needed for legacy component bindings 726 - */ 727 - subsume(other) { 728 - if (this.global.mode !== other.global.mode) { 729 - throw new Error( 730 - "invariant: A renderer cannot switch modes. If you're seeing this, there's a compiler bug. File an issue!" 731 - ); 732 - } 733 - this.local = other.local; 734 - this.#out = other.#out.map((item, i) => { 735 - const current = this.#out[i]; 736 - if (current instanceof Renderer && item instanceof Renderer) { 737 - current.subsume(item); 738 - return current; 739 - } 740 - return item; 741 - }); 742 - this.promise = other.promise; 743 - this.type = other.type; 744 - } 745 - get length() { 746 - return this.#out.length; 747 - } 748 - /** 749 - * Creates the hydration comment that marks the start of a failed boundary. 750 - * The error is JSON-serialized and embedded inside an HTML comment for the client 751 - * to parse during hydration. The JSON is escaped to prevent `-->` or `<!--` sequences 752 - * from breaking out of the comment (XSS). Uses unicode escapes which `JSON.parse()` 753 - * handles transparently. 754 - * @param {unknown} error 755 - * @returns {string} 756 - */ 757 - static #serialize_failed_boundary(error) { 758 - var json = JSON.stringify(error); 759 - var escaped = json.replace(/>/g, "\\u003e").replace(/</g, "\\u003c"); 760 - return `<!--${HYDRATION_START_FAILED}${escaped}-->`; 761 - } 762 - /** 763 - * Only available on the server and when compiling with the `server` option. 764 - * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. 765 - * @template {Record<string, any>} Props 766 - * @param {Component<Props>} component 767 - * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} [options] 768 - * @returns {RenderOutput} 769 - */ 770 - static render(component, options = {}) { 771 - let sync; 772 - const result = ( 773 - /** @type {RenderOutput} */ 774 - {} 41 + run( 42 + /** @type {T} */ 43 + value 775 44 ); 776 - Object.defineProperties(result, { 777 - html: { 778 - get: () => { 779 - return (sync ??= Renderer.#render(component, options)).body; 780 - } 781 - }, 782 - head: { 783 - get: () => { 784 - return (sync ??= Renderer.#render(component, options)).head; 785 - } 786 - }, 787 - body: { 788 - get: () => { 789 - return (sync ??= Renderer.#render(component, options)).body; 790 - } 791 - }, 792 - hashes: { 793 - value: { 794 - script: "" 795 - } 796 - }, 797 - then: { 798 - value: ( 799 - /** 800 - * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. 801 - * 802 - * @template TResult1 803 - * @template [TResult2=never] 804 - * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled 805 - * @param { (reason: unknown) => TResult2 } onrejected 806 - */ 807 - (onfulfilled, onrejected) => { 808 - { 809 - const result2 = sync ??= Renderer.#render(component, options); 810 - const user_result = onfulfilled({ 811 - head: result2.head, 812 - body: result2.body, 813 - html: result2.body, 814 - hashes: { script: [] } 815 - }); 816 - return Promise.resolve(user_result); 817 - } 818 - } 819 - ) 820 - } 821 - }); 822 - return result; 823 - } 824 - /** 825 - * Collect all of the `onDestroy` callbacks registered during rendering. In an async context, this is only safe to call 826 - * after awaiting `collect_async`. 827 - * 828 - * Child renderers are "porous" and don't affect execution order, but component body renderers 829 - * create ordering boundaries. Within a renderer, callbacks run in order until hitting a component boundary. 830 - * @returns {Iterable<() => void>} 831 - */ 832 - *#collect_on_destroy() { 833 - for (const component of this.#traverse_components()) { 834 - yield* component.#collect_ondestroy(); 835 - } 836 - } 837 - /** 838 - * Performs a depth-first search of renderers, yielding the deepest components first, then additional components as we backtrack up the tree. 839 - * @returns {Iterable<Renderer>} 840 - */ 841 - *#traverse_components() { 842 - for (const child of this.#out) { 843 - if (typeof child !== "string") { 844 - yield* child.#traverse_components(); 845 - } 846 - } 847 - if (this.#is_component_body) { 848 - yield this; 849 - } 850 - } 851 - /** 852 - * @returns {Iterable<() => void>} 853 - */ 854 - *#collect_ondestroy() { 855 - if (this.#on_destroy) { 856 - for (const fn of this.#on_destroy) { 857 - yield fn; 858 - } 859 - } 860 - for (const child of this.#out) { 861 - if (child instanceof Renderer && !child.#is_component_body) { 862 - yield* child.#collect_ondestroy(); 863 - } 864 - } 865 - } 866 - /** 867 - * Render a component. Throws if any of the children are performing asynchronous work. 868 - * 869 - * @template {Record<string, any>} Props 870 - * @param {Component<Props>} component 871 - * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string }} options 872 - * @returns {AccumulatedContent} 873 - */ 874 - static #render(component, options) { 875 - var previous_context = ssr_context; 876 - try { 877 - const renderer = Renderer.#open_render("sync", component, options); 878 - const content = renderer.#collect_content(); 879 - return Renderer.#close_render(content, renderer); 880 - } finally { 881 - abort(); 882 - set_ssr_context(previous_context); 883 - } 884 - } 885 - /** 886 - * Render a component. 887 - * 888 - * @template {Record<string, any>} Props 889 - * @param {Component<Props>} component 890 - * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} options 891 - * @returns {Promise<AccumulatedContent & { hashes: { script: Sha256Source[] } }>} 892 - */ 893 - static async #render_async(component, options) { 894 - const previous_context = ssr_context; 895 - try { 896 - const renderer = Renderer.#open_render("async", component, options); 897 - const content = await renderer.#collect_content_async(); 898 - const hydratables = await renderer.#collect_hydratables(); 899 - if (hydratables !== null) { 900 - content.head = hydratables + content.head; 901 - } 902 - return Renderer.#close_render(content, renderer); 903 - } finally { 904 - set_ssr_context(previous_context); 905 - abort(); 906 - } 907 - } 908 - /** 909 - * Collect all of the code from the `out` array and return it as a string, or a promise resolving to a string. 910 - * @param {AccumulatedContent} content 911 - * @returns {AccumulatedContent} 912 - */ 913 - #collect_content(content = { head: "", body: "" }) { 914 - for (const item of this.#out) { 915 - if (typeof item === "string") { 916 - content[this.type] += item; 917 - } else if (item instanceof Renderer) { 918 - item.#collect_content(content); 919 - } 920 - } 921 - return content; 922 - } 923 - /** 924 - * Collect all of the code from the `out` array and return it as a string. 925 - * @param {AccumulatedContent} content 926 - * @returns {Promise<AccumulatedContent>} 927 - */ 928 - async #collect_content_async(content = { head: "", body: "" }) { 929 - await this.promise; 930 - for (const item of this.#out) { 931 - if (typeof item === "string") { 932 - content[this.type] += item; 933 - } else if (item instanceof Renderer) { 934 - if (item.#boundary) { 935 - const boundary_content = { head: "", body: "" }; 936 - try { 937 - await item.#collect_content_async(boundary_content); 938 - content.head += boundary_content.head; 939 - content.body += boundary_content.body; 940 - } catch (error) { 941 - const { context, failed, transformError } = item.#boundary; 942 - set_ssr_context(context); 943 - let transformed = await transformError(error); 944 - const failed_renderer = new Renderer(item.global, item); 945 - failed_renderer.type = item.type; 946 - failed_renderer.#out.push(Renderer.#serialize_failed_boundary(transformed)); 947 - failed(failed_renderer, transformed, noop); 948 - failed_renderer.#out.push(BLOCK_CLOSE); 949 - await failed_renderer.#collect_content_async(content); 950 - } 951 - } else { 952 - await item.#collect_content_async(content); 953 - } 954 - } 955 - } 956 - return content; 957 - } 958 - async #collect_hydratables() { 959 - const ctx = get_render_context().hydratable; 960 - for (const [_, key] of ctx.unresolved_promises) { 961 - unresolved_hydratable(key, ctx.lookup.get(key)?.stack ?? "<missing stack trace>"); 962 - } 963 - for (const comparison of ctx.comparisons) { 964 - await comparison; 965 - } 966 - return await this.#hydratable_block(ctx); 967 - } 968 - /** 969 - * @template {Record<string, any>} Props 970 - * @param {'sync' | 'async'} mode 971 - * @param {import('svelte').Component<Props>} component 972 - * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp; transformError?: (error: unknown) => unknown }} options 973 - * @returns {Renderer} 974 - */ 975 - static #open_render(mode, component, options) { 976 - var previous_context = ssr_context; 977 - try { 978 - const renderer = new Renderer( 979 - new SSRState( 980 - mode, 981 - options.idPrefix ? options.idPrefix + "-" : "", 982 - options.csp, 983 - options.transformError 984 - ) 985 - ); 986 - const context = { p: null, c: options.context ?? null, r: renderer }; 987 - set_ssr_context(context); 988 - renderer.push(BLOCK_OPEN); 989 - component(renderer, options.props ?? {}); 990 - renderer.push(BLOCK_CLOSE); 991 - return renderer; 992 - } finally { 993 - set_ssr_context(previous_context); 994 - } 995 - } 996 - /** 997 - * @param {AccumulatedContent} content 998 - * @param {Renderer} renderer 999 - * @returns {AccumulatedContent & { hashes: { script: Sha256Source[] } }} 1000 - */ 1001 - static #close_render(content, renderer) { 1002 - for (const cleanup of renderer.#collect_on_destroy()) { 1003 - cleanup(); 1004 - } 1005 - let head2 = content.head + renderer.global.get_title(); 1006 - let body = content.body; 1007 - for (const { hash, code } of renderer.global.css) { 1008 - head2 += `<style id="${hash}">${code}</style>`; 1009 - } 1010 - return { 1011 - head: head2, 1012 - body, 1013 - hashes: { 1014 - script: renderer.global.csp.script_hashes 45 + return () => { 46 + subscribers.delete(subscriber); 47 + if (subscribers.size === 0 && stop) { 48 + stop(); 49 + stop = null; 1015 50 } 1016 51 }; 1017 52 } 1018 - /** 1019 - * @param {HydratableContext} ctx 1020 - */ 1021 - async #hydratable_block(ctx) { 1022 - if (ctx.lookup.size === 0) { 1023 - return null; 1024 - } 1025 - let entries = []; 1026 - let has_promises = false; 1027 - for (const [k, v] of ctx.lookup) { 1028 - if (v.promises) { 1029 - has_promises = true; 1030 - for (const p of v.promises) await p; 1031 - } 1032 - entries.push(`[${devalue.uneval(k)},${v.serialized}]`); 1033 - } 1034 - let prelude = `const h = (window.__svelte ??= {}).h ??= new Map();`; 1035 - if (has_promises) { 1036 - prelude = `const r = (v) => Promise.resolve(v); 1037 - ${prelude}`; 1038 - } 1039 - const body = ` 1040 - { 1041 - ${prelude} 1042 - 1043 - for (const [k, v] of [ 1044 - ${entries.join(",\n ")} 1045 - ]) { 1046 - h.set(k, v); 1047 - } 1048 - } 1049 - `; 1050 - let csp_attr = ""; 1051 - if (this.global.csp.nonce) { 1052 - csp_attr = ` nonce="${this.global.csp.nonce}"`; 1053 - } else if (this.global.csp.hash) { 1054 - const hash = await sha256(body); 1055 - this.global.csp.script_hashes.push(`sha256-${hash}`); 1056 - } 1057 - return ` 1058 - <script${csp_attr}>${body}<\/script>`; 1059 - } 1060 - } 1061 - class SSRState { 1062 - /** @readonly @type {Csp & { script_hashes: Sha256Source[] }} */ 1063 - csp; 1064 - /** @readonly @type {'sync' | 'async'} */ 1065 - mode; 1066 - /** @readonly @type {() => string} */ 1067 - uid; 1068 - /** @readonly @type {Set<{ hash: string; code: string }>} */ 1069 - css = /* @__PURE__ */ new Set(); 1070 - /** 1071 - * `transformError` passed to `render`. Called when an error boundary catches an error. 1072 - * Throws by default if unset in `render`. 1073 - * @type {(error: unknown) => unknown} 1074 - */ 1075 - transformError; 1076 - /** @type {{ path: number[], value: string }} */ 1077 - #title = { path: [], value: "" }; 1078 - /** 1079 - * @param {'sync' | 'async'} mode 1080 - * @param {string} id_prefix 1081 - * @param {Csp} csp 1082 - * @param {((error: unknown) => unknown) | undefined} [transformError] 1083 - */ 1084 - constructor(mode, id_prefix = "", csp = { hash: false }, transformError) { 1085 - this.mode = mode; 1086 - this.csp = { ...csp, script_hashes: [] }; 1087 - this.transformError = transformError ?? ((error) => { 1088 - throw error; 1089 - }); 1090 - let uid = 1; 1091 - this.uid = () => `${id_prefix}s${uid++}`; 1092 - } 1093 - get_title() { 1094 - return this.#title.value; 1095 - } 1096 - /** 1097 - * Performs a depth-first (lexicographic) comparison using the path. Rejects sets 1098 - * from earlier than or equal to the current value. 1099 - * @param {string} value 1100 - * @param {number[]} path 1101 - */ 1102 - set_title(value, path) { 1103 - const current = this.#title.path; 1104 - let i = 0; 1105 - let l = Math.min(path.length, current.length); 1106 - while (i < l && path[i] === current[i]) i += 1; 1107 - if (path[i] === void 0) return; 1108 - if (current[i] === void 0 || path[i] > current[i]) { 1109 - this.#title.path = path; 1110 - this.#title.value = value; 1111 - } 1112 - } 1113 - } 1114 - const INVALID_ATTR_NAME_CHAR_REGEX = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u; 1115 - function render(component, options = {}) { 1116 - if (options.csp?.hash && options.csp.nonce) { 1117 - invalid_csp(); 1118 - } 1119 - return Renderer.render( 1120 - /** @type {Component<Props>} */ 1121 - component, 1122 - options 1123 - ); 1124 - } 1125 - function head(hash, renderer, fn) { 1126 - renderer.head((renderer2) => { 1127 - renderer2.push(`<!--${hash}-->`); 1128 - renderer2.child(fn); 1129 - renderer2.push(EMPTY_COMMENT); 1130 - }); 1131 - } 1132 - function attributes(attrs, css_hash, classes, styles, flags = 0) { 1133 - if (styles) { 1134 - attrs.style = to_style(attrs.style, styles); 1135 - } 1136 - if (attrs.class) { 1137 - attrs.class = clsx(attrs.class); 1138 - } 1139 - if (css_hash || classes) { 1140 - attrs.class = to_class(attrs.class, css_hash, classes); 1141 - } 1142 - let attr_str = ""; 1143 - let name; 1144 - const is_html = (flags & ELEMENT_IS_NAMESPACED) === 0; 1145 - const lowercase = (flags & ELEMENT_PRESERVE_ATTRIBUTE_CASE) === 0; 1146 - const is_input = (flags & ELEMENT_IS_INPUT) !== 0; 1147 - for (name of Object.keys(attrs)) { 1148 - if (typeof attrs[name] === "function") continue; 1149 - if (name[0] === "$" && name[1] === "$") continue; 1150 - if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue; 1151 - var value = attrs[name]; 1152 - var lower = name.toLowerCase(); 1153 - if (lowercase) name = lower; 1154 - if (lower.length > 2 && lower.startsWith("on")) continue; 1155 - if (is_input) { 1156 - if (name === "defaultvalue" || name === "defaultchecked") { 1157 - name = name === "defaultvalue" ? "value" : "checked"; 1158 - if (attrs[name]) continue; 1159 - } 1160 - } 1161 - attr_str += attr(name, value, is_html && is_boolean_attribute(name)); 1162 - } 1163 - return attr_str; 1164 - } 1165 - function stringify(value) { 1166 - return typeof value === "string" ? value : value == null ? "" : value + ""; 1167 - } 1168 - function attr_class(value, hash, directives) { 1169 - var result = to_class(value, hash, directives); 1170 - return result ? ` class="${escape_html(result, true)}"` : ""; 1171 - } 1172 - function attr_style(value, directives) { 1173 - var result = to_style(value, directives); 1174 - return result ? ` style="${escape_html(result, true)}"` : ""; 1175 - } 1176 - function ensure_array_like(array_like_or_iterator) { 1177 - if (array_like_or_iterator) { 1178 - return array_like_or_iterator.length !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator); 1179 - } 1180 - return []; 1181 - } 1182 - function once(get_value) { 1183 - let value = ( 1184 - /** @type {V} */ 1185 - UNINITIALIZED 1186 - ); 1187 - return () => { 1188 - if (value === UNINITIALIZED) { 1189 - value = get_value(); 1190 - } 1191 - return value; 1192 - }; 1193 - } 1194 - function derived(fn) { 1195 - const get_value = ssr_context === null ? fn : once(fn); 1196 - let updated_value; 1197 - return function(new_value) { 1198 - if (arguments.length === 0) { 1199 - return updated_value ?? get_value(); 1200 - } 1201 - updated_value = new_value; 1202 - return updated_value; 1203 - }; 53 + return { set, update, subscribe }; 1204 54 } 1205 55 export { 1206 - LEGACY_PROPS as $, 1207 - ASYNC as A, 1208 - BOUNDARY_EFFECT as B, 1209 - COMMENT_NODE as C, 1210 - DIRTY as D, 1211 - ERROR_VALUE as E, 1212 - STATE_SYMBOL as F, 1213 - object_prototype as G, 1214 - HYDRATION_ERROR as H, 1215 - INERT as I, 1216 - array_prototype as J, 1217 - get_descriptor as K, 1218 - get_prototype_of as L, 1219 - MAYBE_DIRTY as M, 1220 - is_array as N, 1221 - is_extensible as O, 1222 - HEAD_EFFECT as P, 1223 - DESTROYING as Q, 1224 - REACTION_RAN as R, 1225 - STALE_REACTION as S, 1226 - USER_EFFECT as T, 1227 - UNINITIALIZED as U, 1228 - REACTION_IS_UPDATING as V, 1229 - WAS_MARKED as W, 1230 - index_of as X, 1231 - define_property as Y, 1232 - array_from as Z, 1233 - is_passive_event as _, 1234 - attr_class as a, 1235 - render as a0, 1236 - setContext as a1, 1237 - derived as a2, 1238 - ssr_context as a3, 1239 - attr_style as a4, 1240 - attr as a5, 1241 - ensure_array_like as a6, 1242 - HYDRATION_END as b, 1243 - HYDRATION_START as c, 1244 - HYDRATION_START_ELSE as d, 1245 - escape_html as e, 1246 - EFFECT as f, 1247 - getContext as g, 1248 - head as h, 1249 - CONNECTED as i, 1250 - CLEAN as j, 1251 - DERIVED as k, 1252 - BLOCK_EFFECT as l, 1253 - DESTROYED as m, 1254 - noop as n, 1255 - EAGER_EFFECT as o, 1256 - deferred as p, 1257 - RENDER_EFFECT as q, 1258 - run_all as r, 1259 - stringify as s, 1260 - MANAGED_EFFECT as t, 1261 - ROOT_EFFECT as u, 1262 - BRANCH_EFFECT as v, 1263 - includes as w, 1264 - HYDRATION_START_FAILED as x, 1265 - EFFECT_TRANSPARENT as y, 1266 - EFFECT_PRESERVED as z 56 + readable as r, 57 + writable as w 1267 58 };
+3185
.svelte-kit/output/server/chunks/index2.js
··· 1 + import { clsx as clsx$1 } from "clsx"; 2 + import { B as BROWSER } from "./false.js"; 3 + import * as devalue from "devalue"; 4 + var is_array = Array.isArray; 5 + var index_of = Array.prototype.indexOf; 6 + var includes = Array.prototype.includes; 7 + var array_from = Array.from; 8 + var define_property = Object.defineProperty; 9 + var get_descriptor = Object.getOwnPropertyDescriptor; 10 + var object_prototype = Object.prototype; 11 + var array_prototype = Array.prototype; 12 + var get_prototype_of = Object.getPrototypeOf; 13 + var is_extensible = Object.isExtensible; 14 + var has_own_property = Object.prototype.hasOwnProperty; 15 + const noop = () => { 16 + }; 17 + function run_all(arr) { 18 + for (var i = 0; i < arr.length; i++) { 19 + arr[i](); 20 + } 21 + } 22 + function deferred() { 23 + var resolve; 24 + var reject; 25 + var promise = new Promise((res, rej) => { 26 + resolve = res; 27 + reject = rej; 28 + }); 29 + return { promise, resolve, reject }; 30 + } 31 + function equals(value) { 32 + return value === this.v; 33 + } 34 + function safe_not_equal(a, b) { 35 + return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function"; 36 + } 37 + function safe_equals(value) { 38 + return !safe_not_equal(value, this.v); 39 + } 40 + const DERIVED = 1 << 1; 41 + const EFFECT = 1 << 2; 42 + const RENDER_EFFECT = 1 << 3; 43 + const MANAGED_EFFECT = 1 << 24; 44 + const BLOCK_EFFECT = 1 << 4; 45 + const BRANCH_EFFECT = 1 << 5; 46 + const ROOT_EFFECT = 1 << 6; 47 + const BOUNDARY_EFFECT = 1 << 7; 48 + const CONNECTED = 1 << 9; 49 + const CLEAN = 1 << 10; 50 + const DIRTY = 1 << 11; 51 + const MAYBE_DIRTY = 1 << 12; 52 + const INERT = 1 << 13; 53 + const DESTROYED = 1 << 14; 54 + const REACTION_RAN = 1 << 15; 55 + const DESTROYING = 1 << 25; 56 + const EFFECT_TRANSPARENT = 1 << 16; 57 + const EAGER_EFFECT = 1 << 17; 58 + const HEAD_EFFECT = 1 << 18; 59 + const EFFECT_PRESERVED = 1 << 19; 60 + const USER_EFFECT = 1 << 20; 61 + const WAS_MARKED = 1 << 16; 62 + const REACTION_IS_UPDATING = 1 << 21; 63 + const ASYNC = 1 << 22; 64 + const ERROR_VALUE = 1 << 23; 65 + const STATE_SYMBOL = /* @__PURE__ */ Symbol("$state"); 66 + const LEGACY_PROPS = /* @__PURE__ */ Symbol("legacy props"); 67 + const STALE_REACTION = new class StaleReactionError extends Error { 68 + name = "StaleReactionError"; 69 + message = "The reaction that called `getAbortSignal()` was re-run or destroyed"; 70 + }(); 71 + const COMMENT_NODE = 8; 72 + function lifecycle_outside_component(name) { 73 + { 74 + throw new Error(`https://svelte.dev/e/lifecycle_outside_component`); 75 + } 76 + } 77 + function effect_update_depth_exceeded() { 78 + { 79 + throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); 80 + } 81 + } 82 + function hydration_failed() { 83 + { 84 + throw new Error(`https://svelte.dev/e/hydration_failed`); 85 + } 86 + } 87 + function state_descriptors_fixed() { 88 + { 89 + throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); 90 + } 91 + } 92 + function state_prototype_fixed() { 93 + { 94 + throw new Error(`https://svelte.dev/e/state_prototype_fixed`); 95 + } 96 + } 97 + function state_unsafe_mutation() { 98 + { 99 + throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); 100 + } 101 + } 102 + function svelte_boundary_reset_onerror() { 103 + { 104 + throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`); 105 + } 106 + } 107 + const HYDRATION_START = "["; 108 + const HYDRATION_START_ELSE = "[!"; 109 + const HYDRATION_START_FAILED = "[?"; 110 + const HYDRATION_END = "]"; 111 + const HYDRATION_ERROR = {}; 112 + const ELEMENT_IS_NAMESPACED = 1; 113 + const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; 114 + const ELEMENT_IS_INPUT = 1 << 2; 115 + const UNINITIALIZED = /* @__PURE__ */ Symbol(); 116 + let tracing_mode_flag = false; 117 + let component_context = null; 118 + function set_component_context(context) { 119 + component_context = context; 120 + } 121 + function push$1(props, runes = false, fn) { 122 + component_context = { 123 + p: component_context, 124 + i: false, 125 + c: null, 126 + e: null, 127 + s: props, 128 + x: null, 129 + r: ( 130 + /** @type {Effect} */ 131 + active_effect 132 + ), 133 + l: null 134 + }; 135 + } 136 + function pop$1(component) { 137 + var context = ( 138 + /** @type {ComponentContext} */ 139 + component_context 140 + ); 141 + var effects = context.e; 142 + if (effects !== null) { 143 + context.e = null; 144 + for (var fn of effects) { 145 + create_user_effect(fn); 146 + } 147 + } 148 + context.i = true; 149 + component_context = context.p; 150 + return ( 151 + /** @type {T} */ 152 + {} 153 + ); 154 + } 155 + function is_runes() { 156 + return true; 157 + } 158 + let micro_tasks = []; 159 + function run_micro_tasks() { 160 + var tasks = micro_tasks; 161 + micro_tasks = []; 162 + run_all(tasks); 163 + } 164 + function queue_micro_task(fn) { 165 + if (micro_tasks.length === 0 && !is_flushing_sync) { 166 + var tasks = micro_tasks; 167 + queueMicrotask(() => { 168 + if (tasks === micro_tasks) run_micro_tasks(); 169 + }); 170 + } 171 + micro_tasks.push(fn); 172 + } 173 + function flush_tasks() { 174 + while (micro_tasks.length > 0) { 175 + run_micro_tasks(); 176 + } 177 + } 178 + function handle_error(error) { 179 + var effect = active_effect; 180 + if (effect === null) { 181 + active_reaction.f |= ERROR_VALUE; 182 + return error; 183 + } 184 + if ((effect.f & REACTION_RAN) === 0 && (effect.f & EFFECT) === 0) { 185 + throw error; 186 + } 187 + invoke_error_boundary(error, effect); 188 + } 189 + function invoke_error_boundary(error, effect) { 190 + while (effect !== null) { 191 + if ((effect.f & BOUNDARY_EFFECT) !== 0) { 192 + if ((effect.f & REACTION_RAN) === 0) { 193 + throw error; 194 + } 195 + try { 196 + effect.b.error(error); 197 + return; 198 + } catch (e) { 199 + error = e; 200 + } 201 + } 202 + effect = effect.parent; 203 + } 204 + throw error; 205 + } 206 + const STATUS_MASK = -7169; 207 + function set_signal_status(signal, status) { 208 + signal.f = signal.f & STATUS_MASK | status; 209 + } 210 + function update_derived_status(derived2) { 211 + if ((derived2.f & CONNECTED) !== 0 || derived2.deps === null) { 212 + set_signal_status(derived2, CLEAN); 213 + } else { 214 + set_signal_status(derived2, MAYBE_DIRTY); 215 + } 216 + } 217 + function clear_marked(deps) { 218 + if (deps === null) return; 219 + for (const dep of deps) { 220 + if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) { 221 + continue; 222 + } 223 + dep.f ^= WAS_MARKED; 224 + clear_marked( 225 + /** @type {Derived} */ 226 + dep.deps 227 + ); 228 + } 229 + } 230 + function defer_effect(effect, dirty_effects, maybe_dirty_effects) { 231 + if ((effect.f & DIRTY) !== 0) { 232 + dirty_effects.add(effect); 233 + } else if ((effect.f & MAYBE_DIRTY) !== 0) { 234 + maybe_dirty_effects.add(effect); 235 + } 236 + clear_marked(effect.deps); 237 + set_signal_status(effect, CLEAN); 238 + } 239 + const batches = /* @__PURE__ */ new Set(); 240 + let current_batch = null; 241 + let batch_values = null; 242 + let last_scheduled_effect = null; 243 + let is_flushing_sync = false; 244 + let is_processing = false; 245 + let collected_effects = null; 246 + let legacy_updates = null; 247 + var flush_count = 0; 248 + let uid = 1; 249 + class Batch { 250 + id = uid++; 251 + /** 252 + * The current values of any signals that are updated in this batch. 253 + * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment) 254 + * They keys of this map are identical to `this.#previous` 255 + * @type {Map<Value, [any, boolean]>} 256 + */ 257 + current = /* @__PURE__ */ new Map(); 258 + /** 259 + * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place. 260 + * They keys of this map are identical to `this.#current` 261 + * @type {Map<Value, any>} 262 + */ 263 + previous = /* @__PURE__ */ new Map(); 264 + /** 265 + * When the batch is committed (and the DOM is updated), we need to remove old branches 266 + * and append new ones by calling the functions added inside (if/each/key/etc) blocks 267 + * @type {Set<(batch: Batch) => void>} 268 + */ 269 + #commit_callbacks = /* @__PURE__ */ new Set(); 270 + /** 271 + * If a fork is discarded, we need to destroy any effects that are no longer needed 272 + * @type {Set<(batch: Batch) => void>} 273 + */ 274 + #discard_callbacks = /* @__PURE__ */ new Set(); 275 + /** 276 + * Async effects that are currently in flight 277 + * @type {Map<Effect, number>} 278 + */ 279 + #pending = /* @__PURE__ */ new Map(); 280 + /** 281 + * Async effects that are currently in flight, _not_ inside a pending boundary 282 + * @type {Map<Effect, number>} 283 + */ 284 + #blocking_pending = /* @__PURE__ */ new Map(); 285 + /** 286 + * A deferred that resolves when the batch is committed, used with `settled()` 287 + * TODO replace with Promise.withResolvers once supported widely enough 288 + * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null} 289 + */ 290 + #deferred = null; 291 + /** 292 + * The root effects that need to be flushed 293 + * @type {Effect[]} 294 + */ 295 + #roots = []; 296 + /** 297 + * Effects created while this batch was active. 298 + * @type {Effect[]} 299 + */ 300 + #new_effects = []; 301 + /** 302 + * Deferred effects (which run after async work has completed) that are DIRTY 303 + * @type {Set<Effect>} 304 + */ 305 + #dirty_effects = /* @__PURE__ */ new Set(); 306 + /** 307 + * Deferred effects that are MAYBE_DIRTY 308 + * @type {Set<Effect>} 309 + */ 310 + #maybe_dirty_effects = /* @__PURE__ */ new Set(); 311 + /** 312 + * A map of branches that still exist, but will be destroyed when this batch 313 + * is committed — we skip over these during `process`. 314 + * The value contains child effects that were dirty/maybe_dirty before being reset, 315 + * so they can be rescheduled if the branch survives. 316 + * @type {Map<Effect, { d: Effect[], m: Effect[] }>} 317 + */ 318 + #skipped_branches = /* @__PURE__ */ new Map(); 319 + is_fork = false; 320 + #decrement_queued = false; 321 + /** @type {Set<Batch>} */ 322 + #blockers = /* @__PURE__ */ new Set(); 323 + #is_deferred() { 324 + return this.is_fork || this.#blocking_pending.size > 0; 325 + } 326 + #is_blocked() { 327 + for (const batch of this.#blockers) { 328 + for (const effect of batch.#blocking_pending.keys()) { 329 + var skipped = false; 330 + var e = effect; 331 + while (e.parent !== null) { 332 + if (this.#skipped_branches.has(e)) { 333 + skipped = true; 334 + break; 335 + } 336 + e = e.parent; 337 + } 338 + if (!skipped) { 339 + return true; 340 + } 341 + } 342 + } 343 + return false; 344 + } 345 + /** 346 + * Add an effect to the #skipped_branches map and reset its children 347 + * @param {Effect} effect 348 + */ 349 + skip_effect(effect) { 350 + if (!this.#skipped_branches.has(effect)) { 351 + this.#skipped_branches.set(effect, { d: [], m: [] }); 352 + } 353 + } 354 + /** 355 + * Remove an effect from the #skipped_branches map and reschedule 356 + * any tracked dirty/maybe_dirty child effects 357 + * @param {Effect} effect 358 + */ 359 + unskip_effect(effect) { 360 + var tracked = this.#skipped_branches.get(effect); 361 + if (tracked) { 362 + this.#skipped_branches.delete(effect); 363 + for (var e of tracked.d) { 364 + set_signal_status(e, DIRTY); 365 + this.schedule(e); 366 + } 367 + for (e of tracked.m) { 368 + set_signal_status(e, MAYBE_DIRTY); 369 + this.schedule(e); 370 + } 371 + } 372 + } 373 + #process() { 374 + if (flush_count++ > 1e3) { 375 + batches.delete(this); 376 + infinite_loop_guard(); 377 + } 378 + if (!this.#is_deferred()) { 379 + for (const e of this.#dirty_effects) { 380 + this.#maybe_dirty_effects.delete(e); 381 + set_signal_status(e, DIRTY); 382 + this.schedule(e); 383 + } 384 + for (const e of this.#maybe_dirty_effects) { 385 + set_signal_status(e, MAYBE_DIRTY); 386 + this.schedule(e); 387 + } 388 + } 389 + const roots = this.#roots; 390 + this.#roots = []; 391 + this.apply(); 392 + var effects = collected_effects = []; 393 + var render_effects = []; 394 + var updates = legacy_updates = []; 395 + for (const root of roots) { 396 + try { 397 + this.#traverse(root, effects, render_effects); 398 + } catch (e) { 399 + reset_all(root); 400 + throw e; 401 + } 402 + } 403 + current_batch = null; 404 + if (updates.length > 0) { 405 + var batch = Batch.ensure(); 406 + for (const e of updates) { 407 + batch.schedule(e); 408 + } 409 + } 410 + collected_effects = null; 411 + legacy_updates = null; 412 + if (this.#is_deferred() || this.#is_blocked()) { 413 + this.#defer_effects(render_effects); 414 + this.#defer_effects(effects); 415 + for (const [e, t] of this.#skipped_branches) { 416 + reset_branch(e, t); 417 + } 418 + } else { 419 + if (this.#pending.size === 0) { 420 + batches.delete(this); 421 + } 422 + this.#dirty_effects.clear(); 423 + this.#maybe_dirty_effects.clear(); 424 + for (const fn of this.#commit_callbacks) fn(this); 425 + this.#commit_callbacks.clear(); 426 + flush_queued_effects(render_effects); 427 + flush_queued_effects(effects); 428 + this.#deferred?.resolve(); 429 + } 430 + var next_batch = ( 431 + /** @type {Batch | null} */ 432 + /** @type {unknown} */ 433 + current_batch 434 + ); 435 + if (this.#roots.length > 0) { 436 + const batch2 = next_batch ??= this; 437 + batch2.#roots.push(...this.#roots.filter((r) => !batch2.#roots.includes(r))); 438 + } 439 + if (next_batch !== null) { 440 + batches.add(next_batch); 441 + next_batch.#process(); 442 + } 443 + if (!batches.has(this)) { 444 + this.#commit(); 445 + } 446 + } 447 + /** 448 + * Traverse the effect tree, executing effects or stashing 449 + * them for later execution as appropriate 450 + * @param {Effect} root 451 + * @param {Effect[]} effects 452 + * @param {Effect[]} render_effects 453 + */ 454 + #traverse(root, effects, render_effects) { 455 + root.f ^= CLEAN; 456 + var effect = root.first; 457 + while (effect !== null) { 458 + var flags = effect.f; 459 + var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0; 460 + var is_skippable_branch = is_branch && (flags & CLEAN) !== 0; 461 + var skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect); 462 + if (!skip && effect.fn !== null) { 463 + if (is_branch) { 464 + effect.f ^= CLEAN; 465 + } else if ((flags & EFFECT) !== 0) { 466 + effects.push(effect); 467 + } else if (is_dirty(effect)) { 468 + if ((flags & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect); 469 + update_effect(effect); 470 + } 471 + var child = effect.first; 472 + if (child !== null) { 473 + effect = child; 474 + continue; 475 + } 476 + } 477 + while (effect !== null) { 478 + var next = effect.next; 479 + if (next !== null) { 480 + effect = next; 481 + break; 482 + } 483 + effect = effect.parent; 484 + } 485 + } 486 + } 487 + /** 488 + * @param {Effect[]} effects 489 + */ 490 + #defer_effects(effects) { 491 + for (var i = 0; i < effects.length; i += 1) { 492 + defer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects); 493 + } 494 + } 495 + /** 496 + * Associate a change to a given source with the current 497 + * batch, noting its previous and current values 498 + * @param {Value} source 499 + * @param {any} old_value 500 + * @param {boolean} [is_derived] 501 + */ 502 + capture(source2, old_value, is_derived = false) { 503 + if (old_value !== UNINITIALIZED && !this.previous.has(source2)) { 504 + this.previous.set(source2, old_value); 505 + } 506 + if ((source2.f & ERROR_VALUE) === 0) { 507 + this.current.set(source2, [source2.v, is_derived]); 508 + batch_values?.set(source2, source2.v); 509 + } 510 + } 511 + activate() { 512 + current_batch = this; 513 + } 514 + deactivate() { 515 + current_batch = null; 516 + batch_values = null; 517 + } 518 + flush() { 519 + try { 520 + is_processing = true; 521 + current_batch = this; 522 + this.#process(); 523 + } finally { 524 + flush_count = 0; 525 + last_scheduled_effect = null; 526 + collected_effects = null; 527 + legacy_updates = null; 528 + is_processing = false; 529 + current_batch = null; 530 + batch_values = null; 531 + old_values.clear(); 532 + } 533 + } 534 + discard() { 535 + for (const fn of this.#discard_callbacks) fn(this); 536 + this.#discard_callbacks.clear(); 537 + batches.delete(this); 538 + } 539 + /** 540 + * @param {Effect} effect 541 + */ 542 + register_created_effect(effect) { 543 + this.#new_effects.push(effect); 544 + } 545 + #commit() { 546 + for (const batch of batches) { 547 + var is_earlier = batch.id < this.id; 548 + var sources = []; 549 + for (const [source3, [value, is_derived]] of this.current) { 550 + if (batch.current.has(source3)) { 551 + var batch_value = ( 552 + /** @type {[any, boolean]} */ 553 + batch.current.get(source3)[0] 554 + ); 555 + if (is_earlier && value !== batch_value) { 556 + batch.current.set(source3, [value, is_derived]); 557 + } else { 558 + continue; 559 + } 560 + } 561 + sources.push(source3); 562 + } 563 + var others = [...batch.current.keys()].filter((s) => !this.current.has(s)); 564 + if (others.length === 0) { 565 + if (is_earlier) { 566 + batch.discard(); 567 + } 568 + } else if (sources.length > 0) { 569 + batch.activate(); 570 + var marked = /* @__PURE__ */ new Set(); 571 + var checked = /* @__PURE__ */ new Map(); 572 + for (var source2 of sources) { 573 + mark_effects(source2, others, marked, checked); 574 + } 575 + checked = /* @__PURE__ */ new Map(); 576 + var current_unequal = [...batch.current.keys()].filter( 577 + (c) => this.current.has(c) ? ( 578 + /** @type {[any, boolean]} */ 579 + this.current.get(c)[0] !== c 580 + ) : true 581 + ); 582 + for (const effect of this.#new_effects) { 583 + if ((effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 && depends_on(effect, current_unequal, checked)) { 584 + if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) { 585 + set_signal_status(effect, DIRTY); 586 + batch.schedule(effect); 587 + } else { 588 + batch.#dirty_effects.add(effect); 589 + } 590 + } 591 + } 592 + if (batch.#roots.length > 0) { 593 + batch.apply(); 594 + for (var root of batch.#roots) { 595 + batch.#traverse(root, [], []); 596 + } 597 + batch.#roots = []; 598 + } 599 + batch.deactivate(); 600 + } 601 + } 602 + for (const batch of batches) { 603 + if (batch.#blockers.has(this)) { 604 + batch.#blockers.delete(this); 605 + if (batch.#blockers.size === 0 && !batch.#is_deferred()) { 606 + batch.activate(); 607 + batch.#process(); 608 + } 609 + } 610 + } 611 + } 612 + /** 613 + * @param {boolean} blocking 614 + * @param {Effect} effect 615 + */ 616 + increment(blocking, effect) { 617 + let pending_count = this.#pending.get(effect) ?? 0; 618 + this.#pending.set(effect, pending_count + 1); 619 + if (blocking) { 620 + let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0; 621 + this.#blocking_pending.set(effect, blocking_pending_count + 1); 622 + } 623 + } 624 + /** 625 + * @param {boolean} blocking 626 + * @param {Effect} effect 627 + * @param {boolean} skip - whether to skip updates (because this is triggered by a stale reaction) 628 + */ 629 + decrement(blocking, effect, skip) { 630 + let pending_count = this.#pending.get(effect) ?? 0; 631 + if (pending_count === 1) { 632 + this.#pending.delete(effect); 633 + } else { 634 + this.#pending.set(effect, pending_count - 1); 635 + } 636 + if (blocking) { 637 + let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0; 638 + if (blocking_pending_count === 1) { 639 + this.#blocking_pending.delete(effect); 640 + } else { 641 + this.#blocking_pending.set(effect, blocking_pending_count - 1); 642 + } 643 + } 644 + if (this.#decrement_queued || skip) return; 645 + this.#decrement_queued = true; 646 + queue_micro_task(() => { 647 + this.#decrement_queued = false; 648 + this.flush(); 649 + }); 650 + } 651 + /** 652 + * @param {Set<Effect>} dirty_effects 653 + * @param {Set<Effect>} maybe_dirty_effects 654 + */ 655 + transfer_effects(dirty_effects, maybe_dirty_effects) { 656 + for (const e of dirty_effects) { 657 + this.#dirty_effects.add(e); 658 + } 659 + for (const e of maybe_dirty_effects) { 660 + this.#maybe_dirty_effects.add(e); 661 + } 662 + dirty_effects.clear(); 663 + maybe_dirty_effects.clear(); 664 + } 665 + /** @param {(batch: Batch) => void} fn */ 666 + oncommit(fn) { 667 + this.#commit_callbacks.add(fn); 668 + } 669 + /** @param {(batch: Batch) => void} fn */ 670 + ondiscard(fn) { 671 + this.#discard_callbacks.add(fn); 672 + } 673 + settled() { 674 + return (this.#deferred ??= deferred()).promise; 675 + } 676 + static ensure() { 677 + if (current_batch === null) { 678 + const batch = current_batch = new Batch(); 679 + if (!is_processing) { 680 + batches.add(current_batch); 681 + if (!is_flushing_sync) { 682 + queue_micro_task(() => { 683 + if (current_batch !== batch) { 684 + return; 685 + } 686 + batch.flush(); 687 + }); 688 + } 689 + } 690 + } 691 + return current_batch; 692 + } 693 + apply() { 694 + { 695 + batch_values = null; 696 + return; 697 + } 698 + } 699 + /** 700 + * 701 + * @param {Effect} effect 702 + */ 703 + schedule(effect) { 704 + last_scheduled_effect = effect; 705 + if (effect.b?.is_pending && (effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 && (effect.f & REACTION_RAN) === 0) { 706 + effect.b.defer_effect(effect); 707 + return; 708 + } 709 + var e = effect; 710 + while (e.parent !== null) { 711 + e = e.parent; 712 + var flags = e.f; 713 + if (collected_effects !== null && e === active_effect) { 714 + if ((active_reaction === null || (active_reaction.f & DERIVED) === 0) && true) { 715 + return; 716 + } 717 + } 718 + if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { 719 + if ((flags & CLEAN) === 0) { 720 + return; 721 + } 722 + e.f ^= CLEAN; 723 + } 724 + } 725 + this.#roots.push(e); 726 + } 727 + } 728 + function flushSync(fn) { 729 + var was_flushing_sync = is_flushing_sync; 730 + is_flushing_sync = true; 731 + try { 732 + var result; 733 + if (fn) ; 734 + while (true) { 735 + flush_tasks(); 736 + if (current_batch === null) { 737 + return ( 738 + /** @type {T} */ 739 + result 740 + ); 741 + } 742 + current_batch.flush(); 743 + } 744 + } finally { 745 + is_flushing_sync = was_flushing_sync; 746 + } 747 + } 748 + function infinite_loop_guard() { 749 + try { 750 + effect_update_depth_exceeded(); 751 + } catch (error) { 752 + invoke_error_boundary(error, last_scheduled_effect); 753 + } 754 + } 755 + let eager_block_effects = null; 756 + function flush_queued_effects(effects) { 757 + var length = effects.length; 758 + if (length === 0) return; 759 + var i = 0; 760 + while (i < length) { 761 + var effect = effects[i++]; 762 + if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) { 763 + eager_block_effects = /* @__PURE__ */ new Set(); 764 + update_effect(effect); 765 + if (effect.deps === null && effect.first === null && effect.nodes === null && effect.teardown === null && effect.ac === null) { 766 + unlink_effect(effect); 767 + } 768 + if (eager_block_effects?.size > 0) { 769 + old_values.clear(); 770 + for (const e of eager_block_effects) { 771 + if ((e.f & (DESTROYED | INERT)) !== 0) continue; 772 + const ordered_effects = [e]; 773 + let ancestor = e.parent; 774 + while (ancestor !== null) { 775 + if (eager_block_effects.has(ancestor)) { 776 + eager_block_effects.delete(ancestor); 777 + ordered_effects.push(ancestor); 778 + } 779 + ancestor = ancestor.parent; 780 + } 781 + for (let j = ordered_effects.length - 1; j >= 0; j--) { 782 + const e2 = ordered_effects[j]; 783 + if ((e2.f & (DESTROYED | INERT)) !== 0) continue; 784 + update_effect(e2); 785 + } 786 + } 787 + eager_block_effects.clear(); 788 + } 789 + } 790 + } 791 + eager_block_effects = null; 792 + } 793 + function mark_effects(value, sources, marked, checked) { 794 + if (marked.has(value)) return; 795 + marked.add(value); 796 + if (value.reactions !== null) { 797 + for (const reaction of value.reactions) { 798 + const flags = reaction.f; 799 + if ((flags & DERIVED) !== 0) { 800 + mark_effects( 801 + /** @type {Derived} */ 802 + reaction, 803 + sources, 804 + marked, 805 + checked 806 + ); 807 + } else if ((flags & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags & DIRTY) === 0 && depends_on(reaction, sources, checked)) { 808 + set_signal_status(reaction, DIRTY); 809 + schedule_effect( 810 + /** @type {Effect} */ 811 + reaction 812 + ); 813 + } 814 + } 815 + } 816 + } 817 + function depends_on(reaction, sources, checked) { 818 + const depends = checked.get(reaction); 819 + if (depends !== void 0) return depends; 820 + if (reaction.deps !== null) { 821 + for (const dep of reaction.deps) { 822 + if (includes.call(sources, dep)) { 823 + return true; 824 + } 825 + if ((dep.f & DERIVED) !== 0 && depends_on( 826 + /** @type {Derived} */ 827 + dep, 828 + sources, 829 + checked 830 + )) { 831 + checked.set( 832 + /** @type {Derived} */ 833 + dep, 834 + true 835 + ); 836 + return true; 837 + } 838 + } 839 + } 840 + checked.set(reaction, false); 841 + return false; 842 + } 843 + function schedule_effect(effect) { 844 + current_batch.schedule(effect); 845 + } 846 + function reset_branch(effect, tracked) { 847 + if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) { 848 + return; 849 + } 850 + if ((effect.f & DIRTY) !== 0) { 851 + tracked.d.push(effect); 852 + } else if ((effect.f & MAYBE_DIRTY) !== 0) { 853 + tracked.m.push(effect); 854 + } 855 + set_signal_status(effect, CLEAN); 856 + var e = effect.first; 857 + while (e !== null) { 858 + reset_branch(e, tracked); 859 + e = e.next; 860 + } 861 + } 862 + function reset_all(effect) { 863 + set_signal_status(effect, CLEAN); 864 + var e = effect.first; 865 + while (e !== null) { 866 + reset_all(e); 867 + e = e.next; 868 + } 869 + } 870 + function destroy_derived_effects(derived2) { 871 + var effects = derived2.effects; 872 + if (effects !== null) { 873 + derived2.effects = null; 874 + for (var i = 0; i < effects.length; i += 1) { 875 + destroy_effect( 876 + /** @type {Effect} */ 877 + effects[i] 878 + ); 879 + } 880 + } 881 + } 882 + function get_derived_parent_effect(derived2) { 883 + var parent = derived2.parent; 884 + while (parent !== null) { 885 + if ((parent.f & DERIVED) === 0) { 886 + return (parent.f & DESTROYED) === 0 ? ( 887 + /** @type {Effect} */ 888 + parent 889 + ) : null; 890 + } 891 + parent = parent.parent; 892 + } 893 + return null; 894 + } 895 + function execute_derived(derived2) { 896 + var value; 897 + var prev_active_effect = active_effect; 898 + set_active_effect(get_derived_parent_effect(derived2)); 899 + { 900 + try { 901 + derived2.f &= ~WAS_MARKED; 902 + destroy_derived_effects(derived2); 903 + value = update_reaction(derived2); 904 + } finally { 905 + set_active_effect(prev_active_effect); 906 + } 907 + } 908 + return value; 909 + } 910 + function update_derived(derived2) { 911 + var old_value = derived2.v; 912 + var value = execute_derived(derived2); 913 + if (!derived2.equals(value)) { 914 + derived2.wv = increment_write_version(); 915 + if (!current_batch?.is_fork || derived2.deps === null) { 916 + derived2.v = value; 917 + current_batch?.capture(derived2, old_value, true); 918 + if (derived2.deps === null) { 919 + set_signal_status(derived2, CLEAN); 920 + return; 921 + } 922 + } 923 + } 924 + if (is_destroying_effect) { 925 + return; 926 + } 927 + if (batch_values !== null) { 928 + if (effect_tracking() || current_batch?.is_fork) { 929 + batch_values.set(derived2, value); 930 + } 931 + } else { 932 + update_derived_status(derived2); 933 + } 934 + } 935 + function freeze_derived_effects(derived2) { 936 + if (derived2.effects === null) return; 937 + for (const e of derived2.effects) { 938 + if (e.teardown || e.ac) { 939 + e.teardown?.(); 940 + e.ac?.abort(STALE_REACTION); 941 + e.teardown = noop; 942 + e.ac = null; 943 + remove_reactions(e, 0); 944 + destroy_effect_children(e); 945 + } 946 + } 947 + } 948 + function unfreeze_derived_effects(derived2) { 949 + if (derived2.effects === null) return; 950 + for (const e of derived2.effects) { 951 + if (e.teardown) { 952 + update_effect(e); 953 + } 954 + } 955 + } 956 + let eager_effects = /* @__PURE__ */ new Set(); 957 + const old_values = /* @__PURE__ */ new Map(); 958 + let eager_effects_deferred = false; 959 + function source(v, stack) { 960 + var signal = { 961 + f: 0, 962 + // TODO ideally we could skip this altogether, but it causes type errors 963 + v, 964 + reactions: null, 965 + equals, 966 + rv: 0, 967 + wv: 0 968 + }; 969 + return signal; 970 + } 971 + // @__NO_SIDE_EFFECTS__ 972 + function state(v, stack) { 973 + const s = source(v); 974 + push_reaction_value(s); 975 + return s; 976 + } 977 + // @__NO_SIDE_EFFECTS__ 978 + function mutable_source(initial_value, immutable = false, trackable = true) { 979 + const s = source(initial_value); 980 + if (!immutable) { 981 + s.equals = safe_equals; 982 + } 983 + return s; 984 + } 985 + function set(source2, value, should_proxy = false) { 986 + if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check 987 + // to ensure we error if state is set inside an inspect effect 988 + (!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !includes.call(current_sources, source2))) { 989 + state_unsafe_mutation(); 990 + } 991 + let new_value = should_proxy ? proxy(value) : value; 992 + return internal_set(source2, new_value, legacy_updates); 993 + } 994 + function internal_set(source2, value, updated_during_traversal = null) { 995 + if (!source2.equals(value)) { 996 + var old_value = source2.v; 997 + if (is_destroying_effect) { 998 + old_values.set(source2, value); 999 + } else { 1000 + old_values.set(source2, old_value); 1001 + } 1002 + source2.v = value; 1003 + var batch = Batch.ensure(); 1004 + batch.capture(source2, old_value); 1005 + if ((source2.f & DERIVED) !== 0) { 1006 + const derived2 = ( 1007 + /** @type {Derived} */ 1008 + source2 1009 + ); 1010 + if ((source2.f & DIRTY) !== 0) { 1011 + execute_derived(derived2); 1012 + } 1013 + if (batch_values === null) { 1014 + update_derived_status(derived2); 1015 + } 1016 + } 1017 + source2.wv = increment_write_version(); 1018 + mark_reactions(source2, DIRTY, updated_during_traversal); 1019 + if (active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) { 1020 + if (untracked_writes === null) { 1021 + set_untracked_writes([source2]); 1022 + } else { 1023 + untracked_writes.push(source2); 1024 + } 1025 + } 1026 + if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) { 1027 + flush_eager_effects(); 1028 + } 1029 + } 1030 + return value; 1031 + } 1032 + function flush_eager_effects() { 1033 + eager_effects_deferred = false; 1034 + for (const effect of eager_effects) { 1035 + if ((effect.f & CLEAN) !== 0) { 1036 + set_signal_status(effect, MAYBE_DIRTY); 1037 + } 1038 + if (is_dirty(effect)) { 1039 + update_effect(effect); 1040 + } 1041 + } 1042 + eager_effects.clear(); 1043 + } 1044 + function increment(source2) { 1045 + set(source2, source2.v + 1); 1046 + } 1047 + function mark_reactions(signal, status, updated_during_traversal) { 1048 + var reactions = signal.reactions; 1049 + if (reactions === null) return; 1050 + var length = reactions.length; 1051 + for (var i = 0; i < length; i++) { 1052 + var reaction = reactions[i]; 1053 + var flags = reaction.f; 1054 + var not_dirty = (flags & DIRTY) === 0; 1055 + if (not_dirty) { 1056 + set_signal_status(reaction, status); 1057 + } 1058 + if ((flags & DERIVED) !== 0) { 1059 + var derived2 = ( 1060 + /** @type {Derived} */ 1061 + reaction 1062 + ); 1063 + batch_values?.delete(derived2); 1064 + if ((flags & WAS_MARKED) === 0) { 1065 + if (flags & CONNECTED) { 1066 + reaction.f |= WAS_MARKED; 1067 + } 1068 + mark_reactions(derived2, MAYBE_DIRTY, updated_during_traversal); 1069 + } 1070 + } else if (not_dirty) { 1071 + var effect = ( 1072 + /** @type {Effect} */ 1073 + reaction 1074 + ); 1075 + if ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) { 1076 + eager_block_effects.add(effect); 1077 + } 1078 + if (updated_during_traversal !== null) { 1079 + updated_during_traversal.push(effect); 1080 + } else { 1081 + schedule_effect(effect); 1082 + } 1083 + } 1084 + } 1085 + } 1086 + function proxy(value) { 1087 + if (typeof value !== "object" || value === null || STATE_SYMBOL in value) { 1088 + return value; 1089 + } 1090 + const prototype = get_prototype_of(value); 1091 + if (prototype !== object_prototype && prototype !== array_prototype) { 1092 + return value; 1093 + } 1094 + var sources = /* @__PURE__ */ new Map(); 1095 + var is_proxied_array = is_array(value); 1096 + var version = /* @__PURE__ */ state(0); 1097 + var parent_version = update_version; 1098 + var with_parent = (fn) => { 1099 + if (update_version === parent_version) { 1100 + return fn(); 1101 + } 1102 + var reaction = active_reaction; 1103 + var version2 = update_version; 1104 + set_active_reaction(null); 1105 + set_update_version(parent_version); 1106 + var result = fn(); 1107 + set_active_reaction(reaction); 1108 + set_update_version(version2); 1109 + return result; 1110 + }; 1111 + if (is_proxied_array) { 1112 + sources.set("length", /* @__PURE__ */ state( 1113 + /** @type {any[]} */ 1114 + value.length 1115 + )); 1116 + } 1117 + return new Proxy( 1118 + /** @type {any} */ 1119 + value, 1120 + { 1121 + defineProperty(_, prop, descriptor) { 1122 + if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) { 1123 + state_descriptors_fixed(); 1124 + } 1125 + var s = sources.get(prop); 1126 + if (s === void 0) { 1127 + with_parent(() => { 1128 + var s2 = /* @__PURE__ */ state(descriptor.value); 1129 + sources.set(prop, s2); 1130 + return s2; 1131 + }); 1132 + } else { 1133 + set(s, descriptor.value, true); 1134 + } 1135 + return true; 1136 + }, 1137 + deleteProperty(target, prop) { 1138 + var s = sources.get(prop); 1139 + if (s === void 0) { 1140 + if (prop in target) { 1141 + const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); 1142 + sources.set(prop, s2); 1143 + increment(version); 1144 + } 1145 + } else { 1146 + set(s, UNINITIALIZED); 1147 + increment(version); 1148 + } 1149 + return true; 1150 + }, 1151 + get(target, prop, receiver) { 1152 + if (prop === STATE_SYMBOL) { 1153 + return value; 1154 + } 1155 + var s = sources.get(prop); 1156 + var exists = prop in target; 1157 + if (s === void 0 && (!exists || get_descriptor(target, prop)?.writable)) { 1158 + s = with_parent(() => { 1159 + var p = proxy(exists ? target[prop] : UNINITIALIZED); 1160 + var s2 = /* @__PURE__ */ state(p); 1161 + return s2; 1162 + }); 1163 + sources.set(prop, s); 1164 + } 1165 + if (s !== void 0) { 1166 + var v = get(s); 1167 + return v === UNINITIALIZED ? void 0 : v; 1168 + } 1169 + return Reflect.get(target, prop, receiver); 1170 + }, 1171 + getOwnPropertyDescriptor(target, prop) { 1172 + var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); 1173 + if (descriptor && "value" in descriptor) { 1174 + var s = sources.get(prop); 1175 + if (s) descriptor.value = get(s); 1176 + } else if (descriptor === void 0) { 1177 + var source2 = sources.get(prop); 1178 + var value2 = source2?.v; 1179 + if (source2 !== void 0 && value2 !== UNINITIALIZED) { 1180 + return { 1181 + enumerable: true, 1182 + configurable: true, 1183 + value: value2, 1184 + writable: true 1185 + }; 1186 + } 1187 + } 1188 + return descriptor; 1189 + }, 1190 + has(target, prop) { 1191 + if (prop === STATE_SYMBOL) { 1192 + return true; 1193 + } 1194 + var s = sources.get(prop); 1195 + var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop); 1196 + if (s !== void 0 || active_effect !== null && (!has || get_descriptor(target, prop)?.writable)) { 1197 + if (s === void 0) { 1198 + s = with_parent(() => { 1199 + var p = has ? proxy(target[prop]) : UNINITIALIZED; 1200 + var s2 = /* @__PURE__ */ state(p); 1201 + return s2; 1202 + }); 1203 + sources.set(prop, s); 1204 + } 1205 + var value2 = get(s); 1206 + if (value2 === UNINITIALIZED) { 1207 + return false; 1208 + } 1209 + } 1210 + return has; 1211 + }, 1212 + set(target, prop, value2, receiver) { 1213 + var s = sources.get(prop); 1214 + var has = prop in target; 1215 + if (is_proxied_array && prop === "length") { 1216 + for (var i = value2; i < /** @type {Source<number>} */ 1217 + s.v; i += 1) { 1218 + var other_s = sources.get(i + ""); 1219 + if (other_s !== void 0) { 1220 + set(other_s, UNINITIALIZED); 1221 + } else if (i in target) { 1222 + other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); 1223 + sources.set(i + "", other_s); 1224 + } 1225 + } 1226 + } 1227 + if (s === void 0) { 1228 + if (!has || get_descriptor(target, prop)?.writable) { 1229 + s = with_parent(() => /* @__PURE__ */ state(void 0)); 1230 + set(s, proxy(value2)); 1231 + sources.set(prop, s); 1232 + } 1233 + } else { 1234 + has = s.v !== UNINITIALIZED; 1235 + var p = with_parent(() => proxy(value2)); 1236 + set(s, p); 1237 + } 1238 + var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); 1239 + if (descriptor?.set) { 1240 + descriptor.set.call(receiver, value2); 1241 + } 1242 + if (!has) { 1243 + if (is_proxied_array && typeof prop === "string") { 1244 + var ls = ( 1245 + /** @type {Source<number>} */ 1246 + sources.get("length") 1247 + ); 1248 + var n = Number(prop); 1249 + if (Number.isInteger(n) && n >= ls.v) { 1250 + set(ls, n + 1); 1251 + } 1252 + } 1253 + increment(version); 1254 + } 1255 + return true; 1256 + }, 1257 + ownKeys(target) { 1258 + get(version); 1259 + var own_keys = Reflect.ownKeys(target).filter((key2) => { 1260 + var source3 = sources.get(key2); 1261 + return source3 === void 0 || source3.v !== UNINITIALIZED; 1262 + }); 1263 + for (var [key, source2] of sources) { 1264 + if (source2.v !== UNINITIALIZED && !(key in target)) { 1265 + own_keys.push(key); 1266 + } 1267 + } 1268 + return own_keys; 1269 + }, 1270 + setPrototypeOf() { 1271 + state_prototype_fixed(); 1272 + } 1273 + } 1274 + ); 1275 + } 1276 + var $window; 1277 + var first_child_getter; 1278 + var next_sibling_getter; 1279 + function init_operations() { 1280 + if ($window !== void 0) { 1281 + return; 1282 + } 1283 + $window = window; 1284 + var element_prototype = Element.prototype; 1285 + var node_prototype = Node.prototype; 1286 + var text_prototype = Text.prototype; 1287 + first_child_getter = get_descriptor(node_prototype, "firstChild").get; 1288 + next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get; 1289 + if (is_extensible(element_prototype)) { 1290 + element_prototype.__click = void 0; 1291 + element_prototype.__className = void 0; 1292 + element_prototype.__attributes = null; 1293 + element_prototype.__style = void 0; 1294 + element_prototype.__e = void 0; 1295 + } 1296 + if (is_extensible(text_prototype)) { 1297 + text_prototype.__t = void 0; 1298 + } 1299 + } 1300 + function create_text(value = "") { 1301 + return document.createTextNode(value); 1302 + } 1303 + // @__NO_SIDE_EFFECTS__ 1304 + function get_first_child(node) { 1305 + return ( 1306 + /** @type {TemplateNode | null} */ 1307 + first_child_getter.call(node) 1308 + ); 1309 + } 1310 + // @__NO_SIDE_EFFECTS__ 1311 + function get_next_sibling(node) { 1312 + return ( 1313 + /** @type {TemplateNode | null} */ 1314 + next_sibling_getter.call(node) 1315 + ); 1316 + } 1317 + function clear_text_content(node) { 1318 + node.textContent = ""; 1319 + } 1320 + function without_reactive_context(fn) { 1321 + var previous_reaction = active_reaction; 1322 + var previous_effect = active_effect; 1323 + set_active_reaction(null); 1324 + set_active_effect(null); 1325 + try { 1326 + return fn(); 1327 + } finally { 1328 + set_active_reaction(previous_reaction); 1329 + set_active_effect(previous_effect); 1330 + } 1331 + } 1332 + function push_effect(effect, parent_effect) { 1333 + var parent_last = parent_effect.last; 1334 + if (parent_last === null) { 1335 + parent_effect.last = parent_effect.first = effect; 1336 + } else { 1337 + parent_last.next = effect; 1338 + effect.prev = parent_last; 1339 + parent_effect.last = effect; 1340 + } 1341 + } 1342 + function create_effect(type, fn) { 1343 + var parent = active_effect; 1344 + if (parent !== null && (parent.f & INERT) !== 0) { 1345 + type |= INERT; 1346 + } 1347 + var effect = { 1348 + ctx: component_context, 1349 + deps: null, 1350 + nodes: null, 1351 + f: type | DIRTY | CONNECTED, 1352 + first: null, 1353 + fn, 1354 + last: null, 1355 + next: null, 1356 + parent, 1357 + b: parent && parent.b, 1358 + prev: null, 1359 + teardown: null, 1360 + wv: 0, 1361 + ac: null 1362 + }; 1363 + current_batch?.register_created_effect(effect); 1364 + var e = effect; 1365 + if ((type & EFFECT) !== 0) { 1366 + if (collected_effects !== null) { 1367 + collected_effects.push(effect); 1368 + } else { 1369 + Batch.ensure().schedule(effect); 1370 + } 1371 + } else if (fn !== null) { 1372 + try { 1373 + update_effect(effect); 1374 + } catch (e2) { 1375 + destroy_effect(effect); 1376 + throw e2; 1377 + } 1378 + if (e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child 1379 + (e.f & EFFECT_PRESERVED) === 0) { 1380 + e = e.first; 1381 + if ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) { 1382 + e.f |= EFFECT_TRANSPARENT; 1383 + } 1384 + } 1385 + } 1386 + if (e !== null) { 1387 + e.parent = parent; 1388 + if (parent !== null) { 1389 + push_effect(e, parent); 1390 + } 1391 + if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) { 1392 + var derived2 = ( 1393 + /** @type {Derived} */ 1394 + active_reaction 1395 + ); 1396 + (derived2.effects ??= []).push(e); 1397 + } 1398 + } 1399 + return effect; 1400 + } 1401 + function effect_tracking() { 1402 + return active_reaction !== null && !untracking; 1403 + } 1404 + function create_user_effect(fn) { 1405 + return create_effect(EFFECT | USER_EFFECT, fn); 1406 + } 1407 + function component_root(fn) { 1408 + Batch.ensure(); 1409 + const effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn); 1410 + return (options = {}) => { 1411 + return new Promise((fulfil) => { 1412 + if (options.outro) { 1413 + pause_effect(effect, () => { 1414 + destroy_effect(effect); 1415 + fulfil(void 0); 1416 + }); 1417 + } else { 1418 + destroy_effect(effect); 1419 + fulfil(void 0); 1420 + } 1421 + }); 1422 + }; 1423 + } 1424 + function render_effect(fn, flags = 0) { 1425 + return create_effect(RENDER_EFFECT | flags, fn); 1426 + } 1427 + function block(fn, flags = 0) { 1428 + var effect = create_effect(BLOCK_EFFECT | flags, fn); 1429 + return effect; 1430 + } 1431 + function branch(fn) { 1432 + return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn); 1433 + } 1434 + function execute_effect_teardown(effect) { 1435 + var teardown = effect.teardown; 1436 + if (teardown !== null) { 1437 + const previously_destroying_effect = is_destroying_effect; 1438 + const previous_reaction = active_reaction; 1439 + set_is_destroying_effect(true); 1440 + set_active_reaction(null); 1441 + try { 1442 + teardown.call(null); 1443 + } finally { 1444 + set_is_destroying_effect(previously_destroying_effect); 1445 + set_active_reaction(previous_reaction); 1446 + } 1447 + } 1448 + } 1449 + function destroy_effect_children(signal, remove_dom = false) { 1450 + var effect = signal.first; 1451 + signal.first = signal.last = null; 1452 + while (effect !== null) { 1453 + const controller2 = effect.ac; 1454 + if (controller2 !== null) { 1455 + without_reactive_context(() => { 1456 + controller2.abort(STALE_REACTION); 1457 + }); 1458 + } 1459 + var next = effect.next; 1460 + if ((effect.f & ROOT_EFFECT) !== 0) { 1461 + effect.parent = null; 1462 + } else { 1463 + destroy_effect(effect, remove_dom); 1464 + } 1465 + effect = next; 1466 + } 1467 + } 1468 + function destroy_block_effect_children(signal) { 1469 + var effect = signal.first; 1470 + while (effect !== null) { 1471 + var next = effect.next; 1472 + if ((effect.f & BRANCH_EFFECT) === 0) { 1473 + destroy_effect(effect); 1474 + } 1475 + effect = next; 1476 + } 1477 + } 1478 + function destroy_effect(effect, remove_dom = true) { 1479 + var removed = false; 1480 + if ((remove_dom || (effect.f & HEAD_EFFECT) !== 0) && effect.nodes !== null && effect.nodes.end !== null) { 1481 + remove_effect_dom( 1482 + effect.nodes.start, 1483 + /** @type {TemplateNode} */ 1484 + effect.nodes.end 1485 + ); 1486 + removed = true; 1487 + } 1488 + set_signal_status(effect, DESTROYING); 1489 + destroy_effect_children(effect, remove_dom && !removed); 1490 + remove_reactions(effect, 0); 1491 + var transitions = effect.nodes && effect.nodes.t; 1492 + if (transitions !== null) { 1493 + for (const transition of transitions) { 1494 + transition.stop(); 1495 + } 1496 + } 1497 + execute_effect_teardown(effect); 1498 + effect.f ^= DESTROYING; 1499 + effect.f |= DESTROYED; 1500 + var parent = effect.parent; 1501 + if (parent !== null && parent.first !== null) { 1502 + unlink_effect(effect); 1503 + } 1504 + effect.next = effect.prev = effect.teardown = effect.ctx = effect.deps = effect.fn = effect.nodes = effect.ac = effect.b = null; 1505 + } 1506 + function remove_effect_dom(node, end) { 1507 + while (node !== null) { 1508 + var next = node === end ? null : /* @__PURE__ */ get_next_sibling(node); 1509 + node.remove(); 1510 + node = next; 1511 + } 1512 + } 1513 + function unlink_effect(effect) { 1514 + var parent = effect.parent; 1515 + var prev = effect.prev; 1516 + var next = effect.next; 1517 + if (prev !== null) prev.next = next; 1518 + if (next !== null) next.prev = prev; 1519 + if (parent !== null) { 1520 + if (parent.first === effect) parent.first = next; 1521 + if (parent.last === effect) parent.last = prev; 1522 + } 1523 + } 1524 + function pause_effect(effect, callback, destroy = true) { 1525 + var transitions = []; 1526 + pause_children(effect, transitions, true); 1527 + var fn = () => { 1528 + if (destroy) destroy_effect(effect); 1529 + if (callback) callback(); 1530 + }; 1531 + var remaining = transitions.length; 1532 + if (remaining > 0) { 1533 + var check = () => --remaining || fn(); 1534 + for (var transition of transitions) { 1535 + transition.out(check); 1536 + } 1537 + } else { 1538 + fn(); 1539 + } 1540 + } 1541 + function pause_children(effect, transitions, local) { 1542 + if ((effect.f & INERT) !== 0) return; 1543 + effect.f ^= INERT; 1544 + var t = effect.nodes && effect.nodes.t; 1545 + if (t !== null) { 1546 + for (const transition of t) { 1547 + if (transition.is_global || local) { 1548 + transitions.push(transition); 1549 + } 1550 + } 1551 + } 1552 + var child = effect.first; 1553 + while (child !== null) { 1554 + var sibling = child.next; 1555 + var transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent, 1556 + // it means the parent block effect was pruned. In that case, 1557 + // transparency information was transferred to the branch effect. 1558 + (child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0; 1559 + pause_children(child, transitions, transparent ? local : false); 1560 + child = sibling; 1561 + } 1562 + } 1563 + function move_effect(effect, fragment) { 1564 + if (!effect.nodes) return; 1565 + var node = effect.nodes.start; 1566 + var end = effect.nodes.end; 1567 + while (node !== null) { 1568 + var next = node === end ? null : /* @__PURE__ */ get_next_sibling(node); 1569 + fragment.append(node); 1570 + node = next; 1571 + } 1572 + } 1573 + let is_updating_effect = false; 1574 + let is_destroying_effect = false; 1575 + function set_is_destroying_effect(value) { 1576 + is_destroying_effect = value; 1577 + } 1578 + let active_reaction = null; 1579 + let untracking = false; 1580 + function set_active_reaction(reaction) { 1581 + active_reaction = reaction; 1582 + } 1583 + let active_effect = null; 1584 + function set_active_effect(effect) { 1585 + active_effect = effect; 1586 + } 1587 + let current_sources = null; 1588 + function push_reaction_value(value) { 1589 + if (active_reaction !== null && true) { 1590 + if (current_sources === null) { 1591 + current_sources = [value]; 1592 + } else { 1593 + current_sources.push(value); 1594 + } 1595 + } 1596 + } 1597 + let new_deps = null; 1598 + let skipped_deps = 0; 1599 + let untracked_writes = null; 1600 + function set_untracked_writes(value) { 1601 + untracked_writes = value; 1602 + } 1603 + let write_version = 1; 1604 + let read_version = 0; 1605 + let update_version = read_version; 1606 + function set_update_version(value) { 1607 + update_version = value; 1608 + } 1609 + function increment_write_version() { 1610 + return ++write_version; 1611 + } 1612 + function is_dirty(reaction) { 1613 + var flags = reaction.f; 1614 + if ((flags & DIRTY) !== 0) { 1615 + return true; 1616 + } 1617 + if (flags & DERIVED) { 1618 + reaction.f &= ~WAS_MARKED; 1619 + } 1620 + if ((flags & MAYBE_DIRTY) !== 0) { 1621 + var dependencies = ( 1622 + /** @type {Value[]} */ 1623 + reaction.deps 1624 + ); 1625 + var length = dependencies.length; 1626 + for (var i = 0; i < length; i++) { 1627 + var dependency = dependencies[i]; 1628 + if (is_dirty( 1629 + /** @type {Derived} */ 1630 + dependency 1631 + )) { 1632 + update_derived( 1633 + /** @type {Derived} */ 1634 + dependency 1635 + ); 1636 + } 1637 + if (dependency.wv > reaction.wv) { 1638 + return true; 1639 + } 1640 + } 1641 + if ((flags & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that 1642 + // traversal of the graph in the other batches still happens 1643 + batch_values === null) { 1644 + set_signal_status(reaction, CLEAN); 1645 + } 1646 + } 1647 + return false; 1648 + } 1649 + function schedule_possible_effect_self_invalidation(signal, effect, root = true) { 1650 + var reactions = signal.reactions; 1651 + if (reactions === null) return; 1652 + if (current_sources !== null && includes.call(current_sources, signal)) { 1653 + return; 1654 + } 1655 + for (var i = 0; i < reactions.length; i++) { 1656 + var reaction = reactions[i]; 1657 + if ((reaction.f & DERIVED) !== 0) { 1658 + schedule_possible_effect_self_invalidation( 1659 + /** @type {Derived} */ 1660 + reaction, 1661 + effect, 1662 + false 1663 + ); 1664 + } else if (effect === reaction) { 1665 + if (root) { 1666 + set_signal_status(reaction, DIRTY); 1667 + } else if ((reaction.f & CLEAN) !== 0) { 1668 + set_signal_status(reaction, MAYBE_DIRTY); 1669 + } 1670 + schedule_effect( 1671 + /** @type {Effect} */ 1672 + reaction 1673 + ); 1674 + } 1675 + } 1676 + } 1677 + function update_reaction(reaction) { 1678 + var previous_deps = new_deps; 1679 + var previous_skipped_deps = skipped_deps; 1680 + var previous_untracked_writes = untracked_writes; 1681 + var previous_reaction = active_reaction; 1682 + var previous_sources = current_sources; 1683 + var previous_component_context = component_context; 1684 + var previous_untracking = untracking; 1685 + var previous_update_version = update_version; 1686 + var flags = reaction.f; 1687 + new_deps = /** @type {null | Value[]} */ 1688 + null; 1689 + skipped_deps = 0; 1690 + untracked_writes = null; 1691 + active_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; 1692 + current_sources = null; 1693 + set_component_context(reaction.ctx); 1694 + untracking = false; 1695 + update_version = ++read_version; 1696 + if (reaction.ac !== null) { 1697 + without_reactive_context(() => { 1698 + reaction.ac.abort(STALE_REACTION); 1699 + }); 1700 + reaction.ac = null; 1701 + } 1702 + try { 1703 + reaction.f |= REACTION_IS_UPDATING; 1704 + var fn = ( 1705 + /** @type {Function} */ 1706 + reaction.fn 1707 + ); 1708 + var result = fn(); 1709 + reaction.f |= REACTION_RAN; 1710 + var deps = reaction.deps; 1711 + var is_fork = current_batch?.is_fork; 1712 + if (new_deps !== null) { 1713 + var i; 1714 + if (!is_fork) { 1715 + remove_reactions(reaction, skipped_deps); 1716 + } 1717 + if (deps !== null && skipped_deps > 0) { 1718 + deps.length = skipped_deps + new_deps.length; 1719 + for (i = 0; i < new_deps.length; i++) { 1720 + deps[skipped_deps + i] = new_deps[i]; 1721 + } 1722 + } else { 1723 + reaction.deps = deps = new_deps; 1724 + } 1725 + if (effect_tracking() && (reaction.f & CONNECTED) !== 0) { 1726 + for (i = skipped_deps; i < deps.length; i++) { 1727 + (deps[i].reactions ??= []).push(reaction); 1728 + } 1729 + } 1730 + } else if (!is_fork && deps !== null && skipped_deps < deps.length) { 1731 + remove_reactions(reaction, skipped_deps); 1732 + deps.length = skipped_deps; 1733 + } 1734 + if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) { 1735 + for (i = 0; i < /** @type {Source[]} */ 1736 + untracked_writes.length; i++) { 1737 + schedule_possible_effect_self_invalidation( 1738 + untracked_writes[i], 1739 + /** @type {Effect} */ 1740 + reaction 1741 + ); 1742 + } 1743 + } 1744 + if (previous_reaction !== null && previous_reaction !== reaction) { 1745 + read_version++; 1746 + if (previous_reaction.deps !== null) { 1747 + for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) { 1748 + previous_reaction.deps[i2].rv = read_version; 1749 + } 1750 + } 1751 + if (previous_deps !== null) { 1752 + for (const dep of previous_deps) { 1753 + dep.rv = read_version; 1754 + } 1755 + } 1756 + if (untracked_writes !== null) { 1757 + if (previous_untracked_writes === null) { 1758 + previous_untracked_writes = untracked_writes; 1759 + } else { 1760 + previous_untracked_writes.push(.../** @type {Source[]} */ 1761 + untracked_writes); 1762 + } 1763 + } 1764 + } 1765 + if ((reaction.f & ERROR_VALUE) !== 0) { 1766 + reaction.f ^= ERROR_VALUE; 1767 + } 1768 + return result; 1769 + } catch (error) { 1770 + return handle_error(error); 1771 + } finally { 1772 + reaction.f ^= REACTION_IS_UPDATING; 1773 + new_deps = previous_deps; 1774 + skipped_deps = previous_skipped_deps; 1775 + untracked_writes = previous_untracked_writes; 1776 + active_reaction = previous_reaction; 1777 + current_sources = previous_sources; 1778 + set_component_context(previous_component_context); 1779 + untracking = previous_untracking; 1780 + update_version = previous_update_version; 1781 + } 1782 + } 1783 + function remove_reaction(signal, dependency) { 1784 + let reactions = dependency.reactions; 1785 + if (reactions !== null) { 1786 + var index = index_of.call(reactions, signal); 1787 + if (index !== -1) { 1788 + var new_length = reactions.length - 1; 1789 + if (new_length === 0) { 1790 + reactions = dependency.reactions = null; 1791 + } else { 1792 + reactions[index] = reactions[new_length]; 1793 + reactions.pop(); 1794 + } 1795 + } 1796 + } 1797 + if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear 1798 + // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` 1799 + // allows us to skip the expensive work of disconnecting and immediately reconnecting it 1800 + (new_deps === null || !includes.call(new_deps, dependency))) { 1801 + var derived2 = ( 1802 + /** @type {Derived} */ 1803 + dependency 1804 + ); 1805 + if ((derived2.f & CONNECTED) !== 0) { 1806 + derived2.f ^= CONNECTED; 1807 + derived2.f &= ~WAS_MARKED; 1808 + } 1809 + update_derived_status(derived2); 1810 + freeze_derived_effects(derived2); 1811 + remove_reactions(derived2, 0); 1812 + } 1813 + } 1814 + function remove_reactions(signal, start_index) { 1815 + var dependencies = signal.deps; 1816 + if (dependencies === null) return; 1817 + for (var i = start_index; i < dependencies.length; i++) { 1818 + remove_reaction(signal, dependencies[i]); 1819 + } 1820 + } 1821 + function update_effect(effect) { 1822 + var flags = effect.f; 1823 + if ((flags & DESTROYED) !== 0) { 1824 + return; 1825 + } 1826 + set_signal_status(effect, CLEAN); 1827 + var previous_effect = active_effect; 1828 + var was_updating_effect = is_updating_effect; 1829 + active_effect = effect; 1830 + is_updating_effect = true; 1831 + try { 1832 + if ((flags & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) { 1833 + destroy_block_effect_children(effect); 1834 + } else { 1835 + destroy_effect_children(effect); 1836 + } 1837 + execute_effect_teardown(effect); 1838 + var teardown = update_reaction(effect); 1839 + effect.teardown = typeof teardown === "function" ? teardown : null; 1840 + effect.wv = write_version; 1841 + var dep; 1842 + if (BROWSER && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) ; 1843 + } finally { 1844 + is_updating_effect = was_updating_effect; 1845 + active_effect = previous_effect; 1846 + } 1847 + } 1848 + function get(signal) { 1849 + var flags = signal.f; 1850 + var is_derived = (flags & DERIVED) !== 0; 1851 + if (active_reaction !== null && !untracking) { 1852 + var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0; 1853 + if (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) { 1854 + var deps = active_reaction.deps; 1855 + if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) { 1856 + if (signal.rv < read_version) { 1857 + signal.rv = read_version; 1858 + if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { 1859 + skipped_deps++; 1860 + } else if (new_deps === null) { 1861 + new_deps = [signal]; 1862 + } else { 1863 + new_deps.push(signal); 1864 + } 1865 + } 1866 + } else { 1867 + (active_reaction.deps ??= []).push(signal); 1868 + var reactions = signal.reactions; 1869 + if (reactions === null) { 1870 + signal.reactions = [active_reaction]; 1871 + } else if (!includes.call(reactions, active_reaction)) { 1872 + reactions.push(active_reaction); 1873 + } 1874 + } 1875 + } 1876 + } 1877 + if (is_destroying_effect && old_values.has(signal)) { 1878 + return old_values.get(signal); 1879 + } 1880 + if (is_derived) { 1881 + var derived2 = ( 1882 + /** @type {Derived} */ 1883 + signal 1884 + ); 1885 + if (is_destroying_effect) { 1886 + var value = derived2.v; 1887 + if ((derived2.f & CLEAN) === 0 && derived2.reactions !== null || depends_on_old_values(derived2)) { 1888 + value = execute_derived(derived2); 1889 + } 1890 + old_values.set(derived2, value); 1891 + return value; 1892 + } 1893 + var should_connect = (derived2.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0); 1894 + var is_new = (derived2.f & REACTION_RAN) === 0; 1895 + if (is_dirty(derived2)) { 1896 + if (should_connect) { 1897 + derived2.f |= CONNECTED; 1898 + } 1899 + update_derived(derived2); 1900 + } 1901 + if (should_connect && !is_new) { 1902 + unfreeze_derived_effects(derived2); 1903 + reconnect(derived2); 1904 + } 1905 + } 1906 + if (batch_values?.has(signal)) { 1907 + return batch_values.get(signal); 1908 + } 1909 + if ((signal.f & ERROR_VALUE) !== 0) { 1910 + throw signal.v; 1911 + } 1912 + return signal.v; 1913 + } 1914 + function reconnect(derived2) { 1915 + derived2.f |= CONNECTED; 1916 + if (derived2.deps === null) return; 1917 + for (const dep of derived2.deps) { 1918 + (dep.reactions ??= []).push(derived2); 1919 + if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) { 1920 + unfreeze_derived_effects( 1921 + /** @type {Derived} */ 1922 + dep 1923 + ); 1924 + reconnect( 1925 + /** @type {Derived} */ 1926 + dep 1927 + ); 1928 + } 1929 + } 1930 + } 1931 + function depends_on_old_values(derived2) { 1932 + if (derived2.v === UNINITIALIZED) return true; 1933 + if (derived2.deps === null) return false; 1934 + for (const dep of derived2.deps) { 1935 + if (old_values.has(dep)) { 1936 + return true; 1937 + } 1938 + if ((dep.f & DERIVED) !== 0 && depends_on_old_values( 1939 + /** @type {Derived} */ 1940 + dep 1941 + )) { 1942 + return true; 1943 + } 1944 + } 1945 + return false; 1946 + } 1947 + function untrack(fn) { 1948 + var previous_untracking = untracking; 1949 + try { 1950 + untracking = true; 1951 + return fn(); 1952 + } finally { 1953 + untracking = previous_untracking; 1954 + } 1955 + } 1956 + function subscribe_to_store(store, run, invalidate) { 1957 + if (store == null) { 1958 + run(void 0); 1959 + return noop; 1960 + } 1961 + const unsub = untrack( 1962 + () => store.subscribe( 1963 + run, 1964 + // @ts-expect-error 1965 + invalidate 1966 + ) 1967 + ); 1968 + return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; 1969 + } 1970 + const DOM_BOOLEAN_ATTRIBUTES = [ 1971 + "allowfullscreen", 1972 + "async", 1973 + "autofocus", 1974 + "autoplay", 1975 + "checked", 1976 + "controls", 1977 + "default", 1978 + "disabled", 1979 + "formnovalidate", 1980 + "indeterminate", 1981 + "inert", 1982 + "ismap", 1983 + "loop", 1984 + "multiple", 1985 + "muted", 1986 + "nomodule", 1987 + "novalidate", 1988 + "open", 1989 + "playsinline", 1990 + "readonly", 1991 + "required", 1992 + "reversed", 1993 + "seamless", 1994 + "selected", 1995 + "webkitdirectory", 1996 + "defer", 1997 + "disablepictureinpicture", 1998 + "disableremoteplayback" 1999 + ]; 2000 + function is_boolean_attribute(name) { 2001 + return DOM_BOOLEAN_ATTRIBUTES.includes(name); 2002 + } 2003 + const PASSIVE_EVENTS = ["touchstart", "touchmove"]; 2004 + function is_passive_event(name) { 2005 + return PASSIVE_EVENTS.includes(name); 2006 + } 2007 + const ATTR_REGEX = /[&"<]/g; 2008 + const CONTENT_REGEX = /[&<]/g; 2009 + function escape_html(value, is_attr) { 2010 + const str = String(value ?? ""); 2011 + const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; 2012 + pattern.lastIndex = 0; 2013 + let escaped = ""; 2014 + let last = 0; 2015 + while (pattern.test(str)) { 2016 + const i = pattern.lastIndex - 1; 2017 + const ch = str[i]; 2018 + escaped += str.substring(last, i) + (ch === "&" ? "&amp;" : ch === '"' ? "&quot;" : "&lt;"); 2019 + last = i + 1; 2020 + } 2021 + return escaped + str.substring(last); 2022 + } 2023 + const replacements = { 2024 + translate: /* @__PURE__ */ new Map([ 2025 + [true, "yes"], 2026 + [false, "no"] 2027 + ]) 2028 + }; 2029 + function attr(name, value, is_boolean = false) { 2030 + if (name === "hidden" && value !== "until-found") { 2031 + is_boolean = true; 2032 + } 2033 + if (value == null || !value && is_boolean) return ""; 2034 + const normalized = has_own_property.call(replacements, name) && replacements[name].get(value) || value; 2035 + const assignment = is_boolean ? `=""` : `="${escape_html(normalized, true)}"`; 2036 + return ` ${name}${assignment}`; 2037 + } 2038 + function clsx(value) { 2039 + if (typeof value === "object") { 2040 + return clsx$1(value); 2041 + } else { 2042 + return value ?? ""; 2043 + } 2044 + } 2045 + const whitespace = [..." \n\r\f \v\uFEFF"]; 2046 + function to_class(value, hash, directives) { 2047 + var classname = value == null ? "" : "" + value; 2048 + if (hash) { 2049 + classname = classname ? classname + " " + hash : hash; 2050 + } 2051 + if (directives) { 2052 + for (var key of Object.keys(directives)) { 2053 + if (directives[key]) { 2054 + classname = classname ? classname + " " + key : key; 2055 + } else if (classname.length) { 2056 + var len = key.length; 2057 + var a = 0; 2058 + while ((a = classname.indexOf(key, a)) >= 0) { 2059 + var b = a + len; 2060 + if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) { 2061 + classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1); 2062 + } else { 2063 + a = b; 2064 + } 2065 + } 2066 + } 2067 + } 2068 + } 2069 + return classname === "" ? null : classname; 2070 + } 2071 + function append_styles(styles, important = false) { 2072 + var separator = important ? " !important;" : ";"; 2073 + var css = ""; 2074 + for (var key of Object.keys(styles)) { 2075 + var value = styles[key]; 2076 + if (value != null && value !== "") { 2077 + css += " " + key + ": " + value + separator; 2078 + } 2079 + } 2080 + return css; 2081 + } 2082 + function to_css_name(name) { 2083 + if (name[0] !== "-" || name[1] !== "-") { 2084 + return name.toLowerCase(); 2085 + } 2086 + return name; 2087 + } 2088 + function to_style(value, styles) { 2089 + if (styles) { 2090 + var new_style = ""; 2091 + var normal_styles; 2092 + var important_styles; 2093 + if (Array.isArray(styles)) { 2094 + normal_styles = styles[0]; 2095 + important_styles = styles[1]; 2096 + } else { 2097 + normal_styles = styles; 2098 + } 2099 + if (value) { 2100 + value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim(); 2101 + var in_str = false; 2102 + var in_apo = 0; 2103 + var in_comment = false; 2104 + var reserved_names = []; 2105 + if (normal_styles) { 2106 + reserved_names.push(...Object.keys(normal_styles).map(to_css_name)); 2107 + } 2108 + if (important_styles) { 2109 + reserved_names.push(...Object.keys(important_styles).map(to_css_name)); 2110 + } 2111 + var start_index = 0; 2112 + var name_index = -1; 2113 + const len = value.length; 2114 + for (var i = 0; i < len; i++) { 2115 + var c = value[i]; 2116 + if (in_comment) { 2117 + if (c === "/" && value[i - 1] === "*") { 2118 + in_comment = false; 2119 + } 2120 + } else if (in_str) { 2121 + if (in_str === c) { 2122 + in_str = false; 2123 + } 2124 + } else if (c === "/" && value[i + 1] === "*") { 2125 + in_comment = true; 2126 + } else if (c === '"' || c === "'") { 2127 + in_str = c; 2128 + } else if (c === "(") { 2129 + in_apo++; 2130 + } else if (c === ")") { 2131 + in_apo--; 2132 + } 2133 + if (!in_comment && in_str === false && in_apo === 0) { 2134 + if (c === ":" && name_index === -1) { 2135 + name_index = i; 2136 + } else if (c === ";" || i === len - 1) { 2137 + if (name_index !== -1) { 2138 + var name = to_css_name(value.substring(start_index, name_index).trim()); 2139 + if (!reserved_names.includes(name)) { 2140 + if (c !== ";") { 2141 + i++; 2142 + } 2143 + var property = value.substring(start_index, i).trim(); 2144 + new_style += " " + property + ";"; 2145 + } 2146 + } 2147 + start_index = i + 1; 2148 + name_index = -1; 2149 + } 2150 + } 2151 + } 2152 + } 2153 + if (normal_styles) { 2154 + new_style += append_styles(normal_styles); 2155 + } 2156 + if (important_styles) { 2157 + new_style += append_styles(important_styles, true); 2158 + } 2159 + new_style = new_style.trim(); 2160 + return new_style === "" ? null : new_style; 2161 + } 2162 + return value == null ? null : String(value); 2163 + } 2164 + const BLOCK_OPEN = `<!--${HYDRATION_START}-->`; 2165 + const BLOCK_CLOSE = `<!--${HYDRATION_END}-->`; 2166 + const EMPTY_COMMENT = `<!---->`; 2167 + let controller = null; 2168 + function abort() { 2169 + controller?.abort(STALE_REACTION); 2170 + controller = null; 2171 + } 2172 + function await_invalid() { 2173 + const error = new Error(`await_invalid 2174 + Encountered asynchronous work while rendering synchronously. 2175 + https://svelte.dev/e/await_invalid`); 2176 + error.name = "Svelte error"; 2177 + throw error; 2178 + } 2179 + function invalid_csp() { 2180 + const error = new Error(`invalid_csp 2181 + \`csp.nonce\` was set while \`csp.hash\` was \`true\`. These options cannot be used simultaneously. 2182 + https://svelte.dev/e/invalid_csp`); 2183 + error.name = "Svelte error"; 2184 + throw error; 2185 + } 2186 + function server_context_required() { 2187 + const error = new Error(`server_context_required 2188 + Could not resolve \`render\` context. 2189 + https://svelte.dev/e/server_context_required`); 2190 + error.name = "Svelte error"; 2191 + throw error; 2192 + } 2193 + var ssr_context = null; 2194 + function set_ssr_context(v) { 2195 + ssr_context = v; 2196 + } 2197 + function getContext(key) { 2198 + const context_map = get_or_init_context_map(); 2199 + const result = ( 2200 + /** @type {T} */ 2201 + context_map.get(key) 2202 + ); 2203 + return result; 2204 + } 2205 + function setContext(key, context) { 2206 + get_or_init_context_map().set(key, context); 2207 + return context; 2208 + } 2209 + function get_or_init_context_map(name) { 2210 + if (ssr_context === null) { 2211 + lifecycle_outside_component(); 2212 + } 2213 + return ssr_context.c ??= new Map(get_parent_context(ssr_context) || void 0); 2214 + } 2215 + function push(fn) { 2216 + ssr_context = { p: ssr_context, c: null, r: null }; 2217 + } 2218 + function pop() { 2219 + ssr_context = /** @type {SSRContext} */ 2220 + ssr_context.p; 2221 + } 2222 + function get_parent_context(ssr_context2) { 2223 + let parent = ssr_context2.p; 2224 + while (parent !== null) { 2225 + const context_map = parent.c; 2226 + if (context_map !== null) { 2227 + return context_map; 2228 + } 2229 + parent = parent.p; 2230 + } 2231 + return null; 2232 + } 2233 + function unresolved_hydratable(key, stack) { 2234 + { 2235 + console.warn(`https://svelte.dev/e/unresolved_hydratable`); 2236 + } 2237 + } 2238 + function get_render_context() { 2239 + const store = als?.getStore(); 2240 + { 2241 + server_context_required(); 2242 + } 2243 + return store; 2244 + } 2245 + let als = null; 2246 + let text_encoder; 2247 + let crypto; 2248 + const obfuscated_import = (module_name) => import( 2249 + /* @vite-ignore */ 2250 + module_name 2251 + ); 2252 + async function sha256(data) { 2253 + text_encoder ??= new TextEncoder(); 2254 + crypto ??= globalThis.crypto?.subtle?.digest ? globalThis.crypto : ( 2255 + // @ts-ignore - we don't install node types in the prod build 2256 + // don't use import('node:crypto') directly because static analysers will think we rely on node when we don't 2257 + (await obfuscated_import("node:crypto")).webcrypto 2258 + ); 2259 + const hash_buffer = await crypto.subtle.digest("SHA-256", text_encoder.encode(data)); 2260 + return base64_encode(hash_buffer); 2261 + } 2262 + function base64_encode(bytes) { 2263 + if (globalThis.Buffer) { 2264 + return globalThis.Buffer.from(bytes).toString("base64"); 2265 + } 2266 + let binary = ""; 2267 + for (let i = 0; i < bytes.length; i++) { 2268 + binary += String.fromCharCode(bytes[i]); 2269 + } 2270 + return btoa(binary); 2271 + } 2272 + class Renderer { 2273 + /** 2274 + * The contents of the renderer. 2275 + * @type {RendererItem[]} 2276 + */ 2277 + #out = []; 2278 + /** 2279 + * Any `onDestroy` callbacks registered during execution of this renderer. 2280 + * @type {(() => void)[] | undefined} 2281 + */ 2282 + #on_destroy = void 0; 2283 + /** 2284 + * Whether this renderer is a component body. 2285 + * @type {boolean} 2286 + */ 2287 + #is_component_body = false; 2288 + /** 2289 + * If set, this renderer is an error boundary. When async collection 2290 + * of the children fails, the failed snippet is rendered instead. 2291 + * @type {{ 2292 + * failed: (renderer: Renderer, error: unknown, reset: () => void) => void; 2293 + * transformError: (error: unknown) => unknown; 2294 + * context: SSRContext | null; 2295 + * } | null} 2296 + */ 2297 + #boundary = null; 2298 + /** 2299 + * The type of string content that this renderer is accumulating. 2300 + * @type {RendererType} 2301 + */ 2302 + type; 2303 + /** @type {Renderer | undefined} */ 2304 + #parent; 2305 + /** 2306 + * Asynchronous work associated with this renderer 2307 + * @type {Promise<void> | undefined} 2308 + */ 2309 + promise = void 0; 2310 + /** 2311 + * State which is associated with the content tree as a whole. 2312 + * It will be re-exposed, uncopied, on all children. 2313 + * @type {SSRState} 2314 + * @readonly 2315 + */ 2316 + global; 2317 + /** 2318 + * State that is local to the branch it is declared in. 2319 + * It will be shallow-copied to all children. 2320 + * 2321 + * @type {{ select_value: string | undefined }} 2322 + */ 2323 + local; 2324 + /** 2325 + * @param {SSRState} global 2326 + * @param {Renderer | undefined} [parent] 2327 + */ 2328 + constructor(global, parent) { 2329 + this.#parent = parent; 2330 + this.global = global; 2331 + this.local = parent ? { ...parent.local } : { select_value: void 0 }; 2332 + this.type = parent ? parent.type : "body"; 2333 + } 2334 + /** 2335 + * @param {(renderer: Renderer) => void} fn 2336 + */ 2337 + head(fn) { 2338 + const head2 = new Renderer(this.global, this); 2339 + head2.type = "head"; 2340 + this.#out.push(head2); 2341 + head2.child(fn); 2342 + } 2343 + /** 2344 + * @param {Array<Promise<void>>} blockers 2345 + * @param {(renderer: Renderer) => void} fn 2346 + */ 2347 + async_block(blockers, fn) { 2348 + this.#out.push(BLOCK_OPEN); 2349 + this.async(blockers, fn); 2350 + this.#out.push(BLOCK_CLOSE); 2351 + } 2352 + /** 2353 + * @param {Array<Promise<void>>} blockers 2354 + * @param {(renderer: Renderer) => void} fn 2355 + */ 2356 + async(blockers, fn) { 2357 + let callback = fn; 2358 + if (blockers.length > 0) { 2359 + const context = ssr_context; 2360 + callback = (renderer) => { 2361 + return Promise.all(blockers).then(() => { 2362 + const previous_context = ssr_context; 2363 + try { 2364 + set_ssr_context(context); 2365 + return fn(renderer); 2366 + } finally { 2367 + set_ssr_context(previous_context); 2368 + } 2369 + }); 2370 + }; 2371 + } 2372 + this.child(callback); 2373 + } 2374 + /** 2375 + * @param {Array<() => void>} thunks 2376 + */ 2377 + run(thunks) { 2378 + const context = ssr_context; 2379 + let promise = Promise.resolve(thunks[0]()); 2380 + const promises = [promise]; 2381 + for (const fn of thunks.slice(1)) { 2382 + promise = promise.then(() => { 2383 + const previous_context = ssr_context; 2384 + set_ssr_context(context); 2385 + try { 2386 + return fn(); 2387 + } finally { 2388 + set_ssr_context(previous_context); 2389 + } 2390 + }); 2391 + promises.push(promise); 2392 + } 2393 + promise.catch(noop); 2394 + this.promise = promise; 2395 + return promises; 2396 + } 2397 + /** 2398 + * @param {(renderer: Renderer) => MaybePromise<void>} fn 2399 + */ 2400 + child_block(fn) { 2401 + this.#out.push(BLOCK_OPEN); 2402 + this.child(fn); 2403 + this.#out.push(BLOCK_CLOSE); 2404 + } 2405 + /** 2406 + * Create a child renderer. The child renderer inherits the state from the parent, 2407 + * but has its own content. 2408 + * @param {(renderer: Renderer) => MaybePromise<void>} fn 2409 + */ 2410 + child(fn) { 2411 + const child = new Renderer(this.global, this); 2412 + this.#out.push(child); 2413 + const parent = ssr_context; 2414 + set_ssr_context({ 2415 + ...ssr_context, 2416 + p: parent, 2417 + c: null, 2418 + r: child 2419 + }); 2420 + const result = fn(child); 2421 + set_ssr_context(parent); 2422 + if (result instanceof Promise) { 2423 + result.catch(noop); 2424 + result.finally(() => set_ssr_context(null)).catch(noop); 2425 + if (child.global.mode === "sync") { 2426 + await_invalid(); 2427 + } 2428 + child.promise = result; 2429 + } 2430 + return child; 2431 + } 2432 + /** 2433 + * Render children inside an error boundary. If the children throw and the API-level 2434 + * `transformError` transform handles the error (doesn't re-throw), the `failed` snippet is 2435 + * rendered instead. Otherwise the error propagates. 2436 + * 2437 + * @param {{ failed?: (renderer: Renderer, error: unknown, reset: () => void) => void }} props 2438 + * @param {(renderer: Renderer) => MaybePromise<void>} children_fn 2439 + */ 2440 + boundary(props, children_fn) { 2441 + const child = new Renderer(this.global, this); 2442 + this.#out.push(child); 2443 + const parent_context = ssr_context; 2444 + if (props.failed) { 2445 + child.#boundary = { 2446 + failed: props.failed, 2447 + transformError: this.global.transformError, 2448 + context: parent_context 2449 + }; 2450 + } 2451 + set_ssr_context({ 2452 + ...ssr_context, 2453 + p: parent_context, 2454 + c: null, 2455 + r: child 2456 + }); 2457 + try { 2458 + const result = children_fn(child); 2459 + set_ssr_context(parent_context); 2460 + if (result instanceof Promise) { 2461 + if (child.global.mode === "sync") { 2462 + await_invalid(); 2463 + } 2464 + result.catch(noop); 2465 + child.promise = result; 2466 + } 2467 + } catch (error) { 2468 + set_ssr_context(parent_context); 2469 + const failed_snippet = props.failed; 2470 + if (!failed_snippet) throw error; 2471 + const result = this.global.transformError(error); 2472 + child.#out.length = 0; 2473 + child.#boundary = null; 2474 + if (result instanceof Promise) { 2475 + if (this.global.mode === "sync") { 2476 + await_invalid(); 2477 + } 2478 + child.promise = /** @type {Promise<unknown>} */ 2479 + result.then((transformed) => { 2480 + set_ssr_context(parent_context); 2481 + child.#out.push(Renderer.#serialize_failed_boundary(transformed)); 2482 + failed_snippet(child, transformed, noop); 2483 + child.#out.push(BLOCK_CLOSE); 2484 + }); 2485 + child.promise.catch(noop); 2486 + } else { 2487 + child.#out.push(Renderer.#serialize_failed_boundary(result)); 2488 + failed_snippet(child, result, noop); 2489 + child.#out.push(BLOCK_CLOSE); 2490 + } 2491 + } 2492 + } 2493 + /** 2494 + * Create a component renderer. The component renderer inherits the state from the parent, 2495 + * but has its own content. It is treated as an ordering boundary for ondestroy callbacks. 2496 + * @param {(renderer: Renderer) => MaybePromise<void>} fn 2497 + * @param {Function} [component_fn] 2498 + * @returns {void} 2499 + */ 2500 + component(fn, component_fn) { 2501 + push(); 2502 + const child = this.child(fn); 2503 + child.#is_component_body = true; 2504 + pop(); 2505 + } 2506 + /** 2507 + * @param {Record<string, any>} attrs 2508 + * @param {(renderer: Renderer) => void} fn 2509 + * @param {string | undefined} [css_hash] 2510 + * @param {Record<string, boolean> | undefined} [classes] 2511 + * @param {Record<string, string> | undefined} [styles] 2512 + * @param {number | undefined} [flags] 2513 + * @param {boolean | undefined} [is_rich] 2514 + * @returns {void} 2515 + */ 2516 + select(attrs, fn, css_hash, classes, styles, flags, is_rich) { 2517 + const { value, ...select_attrs } = attrs; 2518 + this.push(`<select${attributes(select_attrs, css_hash, classes, styles, flags)}>`); 2519 + this.child((renderer) => { 2520 + renderer.local.select_value = value; 2521 + fn(renderer); 2522 + }); 2523 + this.push(`${is_rich ? "<!>" : ""}</select>`); 2524 + } 2525 + /** 2526 + * @param {Record<string, any>} attrs 2527 + * @param {string | number | boolean | ((renderer: Renderer) => void)} body 2528 + * @param {string | undefined} [css_hash] 2529 + * @param {Record<string, boolean> | undefined} [classes] 2530 + * @param {Record<string, string> | undefined} [styles] 2531 + * @param {number | undefined} [flags] 2532 + * @param {boolean | undefined} [is_rich] 2533 + */ 2534 + option(attrs, body, css_hash, classes, styles, flags, is_rich) { 2535 + this.#out.push(`<option${attributes(attrs, css_hash, classes, styles, flags)}`); 2536 + const close = (renderer, value, { head: head2, body: body2 }) => { 2537 + if (has_own_property.call(attrs, "value")) { 2538 + value = attrs.value; 2539 + } 2540 + if (value === this.local.select_value) { 2541 + renderer.#out.push(' selected=""'); 2542 + } 2543 + renderer.#out.push(`>${body2}${is_rich ? "<!>" : ""}</option>`); 2544 + if (head2) { 2545 + renderer.head((child) => child.push(head2)); 2546 + } 2547 + }; 2548 + if (typeof body === "function") { 2549 + this.child((renderer) => { 2550 + const r = new Renderer(this.global, this); 2551 + body(r); 2552 + if (this.global.mode === "async") { 2553 + return r.#collect_content_async().then((content) => { 2554 + close(renderer, content.body.replaceAll("<!---->", ""), content); 2555 + }); 2556 + } else { 2557 + const content = r.#collect_content(); 2558 + close(renderer, content.body.replaceAll("<!---->", ""), content); 2559 + } 2560 + }); 2561 + } else { 2562 + close(this, body, { body: escape_html(body) }); 2563 + } 2564 + } 2565 + /** 2566 + * @param {(renderer: Renderer) => void} fn 2567 + */ 2568 + title(fn) { 2569 + const path = this.get_path(); 2570 + const close = (head2) => { 2571 + this.global.set_title(head2, path); 2572 + }; 2573 + this.child((renderer) => { 2574 + const r = new Renderer(renderer.global, renderer); 2575 + fn(r); 2576 + if (renderer.global.mode === "async") { 2577 + return r.#collect_content_async().then((content) => { 2578 + close(content.head); 2579 + }); 2580 + } else { 2581 + const content = r.#collect_content(); 2582 + close(content.head); 2583 + } 2584 + }); 2585 + } 2586 + /** 2587 + * @param {string | (() => Promise<string>)} content 2588 + */ 2589 + push(content) { 2590 + if (typeof content === "function") { 2591 + this.child(async (renderer) => renderer.push(await content())); 2592 + } else { 2593 + this.#out.push(content); 2594 + } 2595 + } 2596 + /** 2597 + * @param {() => void} fn 2598 + */ 2599 + on_destroy(fn) { 2600 + (this.#on_destroy ??= []).push(fn); 2601 + } 2602 + /** 2603 + * @returns {number[]} 2604 + */ 2605 + get_path() { 2606 + return this.#parent ? [...this.#parent.get_path(), this.#parent.#out.indexOf(this)] : []; 2607 + } 2608 + /** 2609 + * @deprecated this is needed for legacy component bindings 2610 + */ 2611 + copy() { 2612 + const copy = new Renderer(this.global, this.#parent); 2613 + copy.#out = this.#out.map((item) => item instanceof Renderer ? item.copy() : item); 2614 + copy.promise = this.promise; 2615 + return copy; 2616 + } 2617 + /** 2618 + * @param {Renderer} other 2619 + * @deprecated this is needed for legacy component bindings 2620 + */ 2621 + subsume(other) { 2622 + if (this.global.mode !== other.global.mode) { 2623 + throw new Error( 2624 + "invariant: A renderer cannot switch modes. If you're seeing this, there's a compiler bug. File an issue!" 2625 + ); 2626 + } 2627 + this.local = other.local; 2628 + this.#out = other.#out.map((item, i) => { 2629 + const current = this.#out[i]; 2630 + if (current instanceof Renderer && item instanceof Renderer) { 2631 + current.subsume(item); 2632 + return current; 2633 + } 2634 + return item; 2635 + }); 2636 + this.promise = other.promise; 2637 + this.type = other.type; 2638 + } 2639 + get length() { 2640 + return this.#out.length; 2641 + } 2642 + /** 2643 + * Creates the hydration comment that marks the start of a failed boundary. 2644 + * The error is JSON-serialized and embedded inside an HTML comment for the client 2645 + * to parse during hydration. The JSON is escaped to prevent `-->` or `<!--` sequences 2646 + * from breaking out of the comment (XSS). Uses unicode escapes which `JSON.parse()` 2647 + * handles transparently. 2648 + * @param {unknown} error 2649 + * @returns {string} 2650 + */ 2651 + static #serialize_failed_boundary(error) { 2652 + var json = JSON.stringify(error); 2653 + var escaped = json.replace(/>/g, "\\u003e").replace(/</g, "\\u003c"); 2654 + return `<!--${HYDRATION_START_FAILED}${escaped}-->`; 2655 + } 2656 + /** 2657 + * Only available on the server and when compiling with the `server` option. 2658 + * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. 2659 + * @template {Record<string, any>} Props 2660 + * @param {Component<Props>} component 2661 + * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} [options] 2662 + * @returns {RenderOutput} 2663 + */ 2664 + static render(component, options = {}) { 2665 + let sync; 2666 + const result = ( 2667 + /** @type {RenderOutput} */ 2668 + {} 2669 + ); 2670 + Object.defineProperties(result, { 2671 + html: { 2672 + get: () => { 2673 + return (sync ??= Renderer.#render(component, options)).body; 2674 + } 2675 + }, 2676 + head: { 2677 + get: () => { 2678 + return (sync ??= Renderer.#render(component, options)).head; 2679 + } 2680 + }, 2681 + body: { 2682 + get: () => { 2683 + return (sync ??= Renderer.#render(component, options)).body; 2684 + } 2685 + }, 2686 + hashes: { 2687 + value: { 2688 + script: "" 2689 + } 2690 + }, 2691 + then: { 2692 + value: ( 2693 + /** 2694 + * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. 2695 + * 2696 + * @template TResult1 2697 + * @template [TResult2=never] 2698 + * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled 2699 + * @param { (reason: unknown) => TResult2 } onrejected 2700 + */ 2701 + (onfulfilled, onrejected) => { 2702 + { 2703 + const result2 = sync ??= Renderer.#render(component, options); 2704 + const user_result = onfulfilled({ 2705 + head: result2.head, 2706 + body: result2.body, 2707 + html: result2.body, 2708 + hashes: { script: [] } 2709 + }); 2710 + return Promise.resolve(user_result); 2711 + } 2712 + } 2713 + ) 2714 + } 2715 + }); 2716 + return result; 2717 + } 2718 + /** 2719 + * Collect all of the `onDestroy` callbacks registered during rendering. In an async context, this is only safe to call 2720 + * after awaiting `collect_async`. 2721 + * 2722 + * Child renderers are "porous" and don't affect execution order, but component body renderers 2723 + * create ordering boundaries. Within a renderer, callbacks run in order until hitting a component boundary. 2724 + * @returns {Iterable<() => void>} 2725 + */ 2726 + *#collect_on_destroy() { 2727 + for (const component of this.#traverse_components()) { 2728 + yield* component.#collect_ondestroy(); 2729 + } 2730 + } 2731 + /** 2732 + * Performs a depth-first search of renderers, yielding the deepest components first, then additional components as we backtrack up the tree. 2733 + * @returns {Iterable<Renderer>} 2734 + */ 2735 + *#traverse_components() { 2736 + for (const child of this.#out) { 2737 + if (typeof child !== "string") { 2738 + yield* child.#traverse_components(); 2739 + } 2740 + } 2741 + if (this.#is_component_body) { 2742 + yield this; 2743 + } 2744 + } 2745 + /** 2746 + * @returns {Iterable<() => void>} 2747 + */ 2748 + *#collect_ondestroy() { 2749 + if (this.#on_destroy) { 2750 + for (const fn of this.#on_destroy) { 2751 + yield fn; 2752 + } 2753 + } 2754 + for (const child of this.#out) { 2755 + if (child instanceof Renderer && !child.#is_component_body) { 2756 + yield* child.#collect_ondestroy(); 2757 + } 2758 + } 2759 + } 2760 + /** 2761 + * Render a component. Throws if any of the children are performing asynchronous work. 2762 + * 2763 + * @template {Record<string, any>} Props 2764 + * @param {Component<Props>} component 2765 + * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string }} options 2766 + * @returns {AccumulatedContent} 2767 + */ 2768 + static #render(component, options) { 2769 + var previous_context = ssr_context; 2770 + try { 2771 + const renderer = Renderer.#open_render("sync", component, options); 2772 + const content = renderer.#collect_content(); 2773 + return Renderer.#close_render(content, renderer); 2774 + } finally { 2775 + abort(); 2776 + set_ssr_context(previous_context); 2777 + } 2778 + } 2779 + /** 2780 + * Render a component. 2781 + * 2782 + * @template {Record<string, any>} Props 2783 + * @param {Component<Props>} component 2784 + * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} options 2785 + * @returns {Promise<AccumulatedContent & { hashes: { script: Sha256Source[] } }>} 2786 + */ 2787 + static async #render_async(component, options) { 2788 + const previous_context = ssr_context; 2789 + try { 2790 + const renderer = Renderer.#open_render("async", component, options); 2791 + const content = await renderer.#collect_content_async(); 2792 + const hydratables = await renderer.#collect_hydratables(); 2793 + if (hydratables !== null) { 2794 + content.head = hydratables + content.head; 2795 + } 2796 + return Renderer.#close_render(content, renderer); 2797 + } finally { 2798 + set_ssr_context(previous_context); 2799 + abort(); 2800 + } 2801 + } 2802 + /** 2803 + * Collect all of the code from the `out` array and return it as a string, or a promise resolving to a string. 2804 + * @param {AccumulatedContent} content 2805 + * @returns {AccumulatedContent} 2806 + */ 2807 + #collect_content(content = { head: "", body: "" }) { 2808 + for (const item of this.#out) { 2809 + if (typeof item === "string") { 2810 + content[this.type] += item; 2811 + } else if (item instanceof Renderer) { 2812 + item.#collect_content(content); 2813 + } 2814 + } 2815 + return content; 2816 + } 2817 + /** 2818 + * Collect all of the code from the `out` array and return it as a string. 2819 + * @param {AccumulatedContent} content 2820 + * @returns {Promise<AccumulatedContent>} 2821 + */ 2822 + async #collect_content_async(content = { head: "", body: "" }) { 2823 + await this.promise; 2824 + for (const item of this.#out) { 2825 + if (typeof item === "string") { 2826 + content[this.type] += item; 2827 + } else if (item instanceof Renderer) { 2828 + if (item.#boundary) { 2829 + const boundary_content = { head: "", body: "" }; 2830 + try { 2831 + await item.#collect_content_async(boundary_content); 2832 + content.head += boundary_content.head; 2833 + content.body += boundary_content.body; 2834 + } catch (error) { 2835 + const { context, failed, transformError } = item.#boundary; 2836 + set_ssr_context(context); 2837 + let transformed = await transformError(error); 2838 + const failed_renderer = new Renderer(item.global, item); 2839 + failed_renderer.type = item.type; 2840 + failed_renderer.#out.push(Renderer.#serialize_failed_boundary(transformed)); 2841 + failed(failed_renderer, transformed, noop); 2842 + failed_renderer.#out.push(BLOCK_CLOSE); 2843 + await failed_renderer.#collect_content_async(content); 2844 + } 2845 + } else { 2846 + await item.#collect_content_async(content); 2847 + } 2848 + } 2849 + } 2850 + return content; 2851 + } 2852 + async #collect_hydratables() { 2853 + const ctx = get_render_context().hydratable; 2854 + for (const [_, key] of ctx.unresolved_promises) { 2855 + unresolved_hydratable(key, ctx.lookup.get(key)?.stack ?? "<missing stack trace>"); 2856 + } 2857 + for (const comparison of ctx.comparisons) { 2858 + await comparison; 2859 + } 2860 + return await this.#hydratable_block(ctx); 2861 + } 2862 + /** 2863 + * @template {Record<string, any>} Props 2864 + * @param {'sync' | 'async'} mode 2865 + * @param {import('svelte').Component<Props>} component 2866 + * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp; transformError?: (error: unknown) => unknown }} options 2867 + * @returns {Renderer} 2868 + */ 2869 + static #open_render(mode, component, options) { 2870 + var previous_context = ssr_context; 2871 + try { 2872 + const renderer = new Renderer( 2873 + new SSRState( 2874 + mode, 2875 + options.idPrefix ? options.idPrefix + "-" : "", 2876 + options.csp, 2877 + options.transformError 2878 + ) 2879 + ); 2880 + const context = { p: null, c: options.context ?? null, r: renderer }; 2881 + set_ssr_context(context); 2882 + renderer.push(BLOCK_OPEN); 2883 + component(renderer, options.props ?? {}); 2884 + renderer.push(BLOCK_CLOSE); 2885 + return renderer; 2886 + } finally { 2887 + set_ssr_context(previous_context); 2888 + } 2889 + } 2890 + /** 2891 + * @param {AccumulatedContent} content 2892 + * @param {Renderer} renderer 2893 + * @returns {AccumulatedContent & { hashes: { script: Sha256Source[] } }} 2894 + */ 2895 + static #close_render(content, renderer) { 2896 + for (const cleanup of renderer.#collect_on_destroy()) { 2897 + cleanup(); 2898 + } 2899 + let head2 = content.head + renderer.global.get_title(); 2900 + let body = content.body; 2901 + for (const { hash, code } of renderer.global.css) { 2902 + head2 += `<style id="${hash}">${code}</style>`; 2903 + } 2904 + return { 2905 + head: head2, 2906 + body, 2907 + hashes: { 2908 + script: renderer.global.csp.script_hashes 2909 + } 2910 + }; 2911 + } 2912 + /** 2913 + * @param {HydratableContext} ctx 2914 + */ 2915 + async #hydratable_block(ctx) { 2916 + if (ctx.lookup.size === 0) { 2917 + return null; 2918 + } 2919 + let entries = []; 2920 + let has_promises = false; 2921 + for (const [k, v] of ctx.lookup) { 2922 + if (v.promises) { 2923 + has_promises = true; 2924 + for (const p of v.promises) await p; 2925 + } 2926 + entries.push(`[${devalue.uneval(k)},${v.serialized}]`); 2927 + } 2928 + let prelude = `const h = (window.__svelte ??= {}).h ??= new Map();`; 2929 + if (has_promises) { 2930 + prelude = `const r = (v) => Promise.resolve(v); 2931 + ${prelude}`; 2932 + } 2933 + const body = ` 2934 + { 2935 + ${prelude} 2936 + 2937 + for (const [k, v] of [ 2938 + ${entries.join(",\n ")} 2939 + ]) { 2940 + h.set(k, v); 2941 + } 2942 + } 2943 + `; 2944 + let csp_attr = ""; 2945 + if (this.global.csp.nonce) { 2946 + csp_attr = ` nonce="${this.global.csp.nonce}"`; 2947 + } else if (this.global.csp.hash) { 2948 + const hash = await sha256(body); 2949 + this.global.csp.script_hashes.push(`sha256-${hash}`); 2950 + } 2951 + return ` 2952 + <script${csp_attr}>${body}<\/script>`; 2953 + } 2954 + } 2955 + class SSRState { 2956 + /** @readonly @type {Csp & { script_hashes: Sha256Source[] }} */ 2957 + csp; 2958 + /** @readonly @type {'sync' | 'async'} */ 2959 + mode; 2960 + /** @readonly @type {() => string} */ 2961 + uid; 2962 + /** @readonly @type {Set<{ hash: string; code: string }>} */ 2963 + css = /* @__PURE__ */ new Set(); 2964 + /** 2965 + * `transformError` passed to `render`. Called when an error boundary catches an error. 2966 + * Throws by default if unset in `render`. 2967 + * @type {(error: unknown) => unknown} 2968 + */ 2969 + transformError; 2970 + /** @type {{ path: number[], value: string }} */ 2971 + #title = { path: [], value: "" }; 2972 + /** 2973 + * @param {'sync' | 'async'} mode 2974 + * @param {string} id_prefix 2975 + * @param {Csp} csp 2976 + * @param {((error: unknown) => unknown) | undefined} [transformError] 2977 + */ 2978 + constructor(mode, id_prefix = "", csp = { hash: false }, transformError) { 2979 + this.mode = mode; 2980 + this.csp = { ...csp, script_hashes: [] }; 2981 + this.transformError = transformError ?? ((error) => { 2982 + throw error; 2983 + }); 2984 + let uid2 = 1; 2985 + this.uid = () => `${id_prefix}s${uid2++}`; 2986 + } 2987 + get_title() { 2988 + return this.#title.value; 2989 + } 2990 + /** 2991 + * Performs a depth-first (lexicographic) comparison using the path. Rejects sets 2992 + * from earlier than or equal to the current value. 2993 + * @param {string} value 2994 + * @param {number[]} path 2995 + */ 2996 + set_title(value, path) { 2997 + const current = this.#title.path; 2998 + let i = 0; 2999 + let l = Math.min(path.length, current.length); 3000 + while (i < l && path[i] === current[i]) i += 1; 3001 + if (path[i] === void 0) return; 3002 + if (current[i] === void 0 || path[i] > current[i]) { 3003 + this.#title.path = path; 3004 + this.#title.value = value; 3005 + } 3006 + } 3007 + } 3008 + const INVALID_ATTR_NAME_CHAR_REGEX = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u; 3009 + function render(component, options = {}) { 3010 + if (options.csp?.hash && options.csp.nonce) { 3011 + invalid_csp(); 3012 + } 3013 + return Renderer.render( 3014 + /** @type {Component<Props>} */ 3015 + component, 3016 + options 3017 + ); 3018 + } 3019 + function head(hash, renderer, fn) { 3020 + renderer.head((renderer2) => { 3021 + renderer2.push(`<!--${hash}-->`); 3022 + renderer2.child(fn); 3023 + renderer2.push(EMPTY_COMMENT); 3024 + }); 3025 + } 3026 + function attributes(attrs, css_hash, classes, styles, flags = 0) { 3027 + if (styles) { 3028 + attrs.style = to_style(attrs.style, styles); 3029 + } 3030 + if (attrs.class) { 3031 + attrs.class = clsx(attrs.class); 3032 + } 3033 + if (css_hash || classes) { 3034 + attrs.class = to_class(attrs.class, css_hash, classes); 3035 + } 3036 + let attr_str = ""; 3037 + let name; 3038 + const is_html = (flags & ELEMENT_IS_NAMESPACED) === 0; 3039 + const lowercase = (flags & ELEMENT_PRESERVE_ATTRIBUTE_CASE) === 0; 3040 + const is_input = (flags & ELEMENT_IS_INPUT) !== 0; 3041 + for (name of Object.keys(attrs)) { 3042 + if (typeof attrs[name] === "function") continue; 3043 + if (name[0] === "$" && name[1] === "$") continue; 3044 + if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue; 3045 + var value = attrs[name]; 3046 + var lower = name.toLowerCase(); 3047 + if (lowercase) name = lower; 3048 + if (lower.length > 2 && lower.startsWith("on")) continue; 3049 + if (is_input) { 3050 + if (name === "defaultvalue" || name === "defaultchecked") { 3051 + name = name === "defaultvalue" ? "value" : "checked"; 3052 + if (attrs[name]) continue; 3053 + } 3054 + } 3055 + attr_str += attr(name, value, is_html && is_boolean_attribute(name)); 3056 + } 3057 + return attr_str; 3058 + } 3059 + function stringify(value) { 3060 + return typeof value === "string" ? value : value == null ? "" : value + ""; 3061 + } 3062 + function attr_class(value, hash, directives) { 3063 + var result = to_class(value, hash, directives); 3064 + return result ? ` class="${escape_html(result, true)}"` : ""; 3065 + } 3066 + function attr_style(value, directives) { 3067 + var result = to_style(value, directives); 3068 + return result ? ` style="${escape_html(result, true)}"` : ""; 3069 + } 3070 + function store_get(store_values, store_name, store) { 3071 + if (store_name in store_values && store_values[store_name][0] === store) { 3072 + return store_values[store_name][2]; 3073 + } 3074 + store_values[store_name]?.[1](); 3075 + store_values[store_name] = [store, null, void 0]; 3076 + const unsub = subscribe_to_store( 3077 + store, 3078 + /** @param {any} v */ 3079 + (v) => store_values[store_name][2] = v 3080 + ); 3081 + store_values[store_name][1] = unsub; 3082 + return store_values[store_name][2]; 3083 + } 3084 + function unsubscribe_stores(store_values) { 3085 + for (const store_name of Object.keys(store_values)) { 3086 + store_values[store_name][1](); 3087 + } 3088 + } 3089 + function ensure_array_like(array_like_or_iterator) { 3090 + if (array_like_or_iterator) { 3091 + return array_like_or_iterator.length !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator); 3092 + } 3093 + return []; 3094 + } 3095 + function once(get_value) { 3096 + let value = ( 3097 + /** @type {V} */ 3098 + UNINITIALIZED 3099 + ); 3100 + return () => { 3101 + if (value === UNINITIALIZED) { 3102 + value = get_value(); 3103 + } 3104 + return value; 3105 + }; 3106 + } 3107 + function derived(fn) { 3108 + const get_value = ssr_context === null ? fn : once(fn); 3109 + let updated_value; 3110 + return function(new_value) { 3111 + if (arguments.length === 0) { 3112 + return updated_value ?? get_value(); 3113 + } 3114 + updated_value = new_value; 3115 + return updated_value; 3116 + }; 3117 + } 3118 + export { 3119 + hydration_failed as $, 3120 + block as A, 3121 + BOUNDARY_EFFECT as B, 3122 + COMMENT_NODE as C, 3123 + branch as D, 3124 + create_text as E, 3125 + pause_effect as F, 3126 + current_batch as G, 3127 + HYDRATION_ERROR as H, 3128 + move_effect as I, 3129 + defer_effect as J, 3130 + set_active_effect as K, 3131 + set_active_reaction as L, 3132 + set_component_context as M, 3133 + Batch as N, 3134 + handle_error as O, 3135 + active_reaction as P, 3136 + component_context as Q, 3137 + internal_set as R, 3138 + destroy_effect as S, 3139 + invoke_error_boundary as T, 3140 + svelte_boundary_reset_onerror as U, 3141 + HYDRATION_START_FAILED as V, 3142 + EFFECT_TRANSPARENT as W, 3143 + EFFECT_PRESERVED as X, 3144 + define_property as Y, 3145 + init_operations as Z, 3146 + get_first_child as _, 3147 + ssr_context as a, 3148 + clear_text_content as a0, 3149 + component_root as a1, 3150 + array_from as a2, 3151 + is_passive_event as a3, 3152 + push$1 as a4, 3153 + pop$1 as a5, 3154 + set as a6, 3155 + LEGACY_PROPS as a7, 3156 + flushSync as a8, 3157 + mutable_source as a9, 3158 + render as aa, 3159 + setContext as ab, 3160 + attr_style as b, 3161 + attr as c, 3162 + stringify as d, 3163 + escape_html as e, 3164 + attr_class as f, 3165 + getContext as g, 3166 + head as h, 3167 + ensure_array_like as i, 3168 + derived as j, 3169 + store_get as k, 3170 + HYDRATION_END as l, 3171 + HYDRATION_START as m, 3172 + noop as n, 3173 + HYDRATION_START_ELSE as o, 3174 + get_next_sibling as p, 3175 + effect_tracking as q, 3176 + get as r, 3177 + safe_not_equal as s, 3178 + render_effect as t, 3179 + unsubscribe_stores as u, 3180 + source as v, 3181 + untrack as w, 3182 + increment as x, 3183 + queue_micro_task as y, 3184 + active_effect as z 3185 + };
+2 -2
.svelte-kit/output/server/chunks/internal.js
··· 30 30 service_worker_options: void 0, 31 31 server_error_boundaries: false, 32 32 templates: { 33 - app: ({ head, body, assets, nonce, env }) => '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <link rel="icon" href="/frogcursor.png" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n <title>VODS VODS VODS</title>\n ' + head + '\n </head>\n <body data-sveltekit-prerender="auto">\n ' + body + "\n </body>\n</html>\nbody>\n</html>\n", 33 + app: ({ head, body, assets, nonce, env }) => '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <link rel="icon" href="/frogicon.png" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n <title>vod frog</title>\n ' + head + '\n </head>\n <body>\n <div style="display: contents">' + body + "</div>\n </body>\n</html>\n", 34 34 error: ({ status, message }) => '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>' + message + `</title> 35 35 36 36 <style> ··· 102 102 <div class="error"> 103 103 <span class="status">` + status + '</span>\n <div class="message">\n <h1>' + message + "</h1>\n </div>\n </div>\n </body>\n</html>\n" 104 104 }, 105 - version_hash: "1uytokf" 105 + version_hash: "1gh8pzr" 106 106 }; 107 107 async function get_hooks() { 108 108 let handle;
+8 -1889
.svelte-kit/output/server/chunks/root.js
··· 1 - import { H as HYDRATION_ERROR, C as COMMENT_NODE, b as HYDRATION_END, c as HYDRATION_START, d as HYDRATION_START_ELSE, r as run_all, B as BOUNDARY_EFFECT, R as REACTION_RAN, E as ERROR_VALUE, f as EFFECT, i as CONNECTED, j as CLEAN, M as MAYBE_DIRTY, D as DIRTY, k as DERIVED, W as WAS_MARKED, I as INERT, l as BLOCK_EFFECT, U as UNINITIALIZED, m as DESTROYED, o as EAGER_EFFECT, A as ASYNC, p as deferred, q as RENDER_EFFECT, t as MANAGED_EFFECT, u as ROOT_EFFECT, v as BRANCH_EFFECT, w as includes, x as HYDRATION_START_FAILED, y as EFFECT_TRANSPARENT, z as EFFECT_PRESERVED, S as STALE_REACTION, n as noop, F as STATE_SYMBOL, G as object_prototype, J as array_prototype, K as get_descriptor, L as get_prototype_of, N as is_array, O as is_extensible, P as HEAD_EFFECT, Q as DESTROYING, T as USER_EFFECT, V as REACTION_IS_UPDATING, X as index_of, Y as define_property, Z as array_from, _ as is_passive_event, $ as LEGACY_PROPS, a0 as render, a1 as setContext, a2 as derived } from "./index.js"; 2 - import { B as BROWSER } from "./false.js"; 3 - function equals(value) { 4 - return value === this.v; 5 - } 6 - function safe_not_equal(a, b) { 7 - return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function"; 8 - } 9 - function safe_equals(value) { 10 - return !safe_not_equal(value, this.v); 11 - } 12 - function effect_update_depth_exceeded() { 13 - { 14 - throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); 15 - } 16 - } 17 - function hydration_failed() { 18 - { 19 - throw new Error(`https://svelte.dev/e/hydration_failed`); 20 - } 21 - } 22 - function state_descriptors_fixed() { 23 - { 24 - throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); 25 - } 26 - } 27 - function state_prototype_fixed() { 28 - { 29 - throw new Error(`https://svelte.dev/e/state_prototype_fixed`); 30 - } 31 - } 32 - function state_unsafe_mutation() { 33 - { 34 - throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); 35 - } 36 - } 37 - function svelte_boundary_reset_onerror() { 38 - { 39 - throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`); 40 - } 41 - } 1 + import { H as HYDRATION_ERROR, C as COMMENT_NODE, l as HYDRATION_END, m as HYDRATION_START, o as HYDRATION_START_ELSE, p as get_next_sibling, q as effect_tracking, r as get, t as render_effect, v as source, w as untrack, x as increment, y as queue_micro_task, z as active_effect, B as BOUNDARY_EFFECT, A as block, D as branch, E as create_text, F as pause_effect, G as current_batch, I as move_effect, J as defer_effect, K as set_active_effect, L as set_active_reaction, M as set_component_context, N as Batch, O as handle_error, P as active_reaction, Q as component_context, R as internal_set, S as destroy_effect, T as invoke_error_boundary, U as svelte_boundary_reset_onerror, V as HYDRATION_START_FAILED, W as EFFECT_TRANSPARENT, X as EFFECT_PRESERVED, Y as define_property, Z as init_operations, _ as get_first_child, $ as hydration_failed, a0 as clear_text_content, a1 as component_root, a2 as array_from, a3 as is_passive_event, a4 as push, a5 as pop, a6 as set, a7 as LEGACY_PROPS, a8 as flushSync, a9 as mutable_source, aa as render, ab as setContext, j as derived } from "./index2.js"; 42 2 function hydration_mismatch(location) { 43 3 { 44 4 console.warn(`https://svelte.dev/e/hydration_mismatch`); ··· 62 22 return hydrate_node = node; 63 23 } 64 24 function hydrate_next() { 65 - return set_hydrate_node(/* @__PURE__ */ get_next_sibling(hydrate_node)); 25 + return set_hydrate_node(get_next_sibling(hydrate_node)); 66 26 } 67 27 function next(count = 1) { 68 28 if (hydrating) { ··· 70 30 var node = hydrate_node; 71 31 while (i--) { 72 32 node = /** @type {TemplateNode} */ 73 - /* @__PURE__ */ get_next_sibling(node); 33 + get_next_sibling(node); 74 34 } 75 35 hydrate_node = node; 76 36 } ··· 94 54 } 95 55 var next2 = ( 96 56 /** @type {TemplateNode} */ 97 - /* @__PURE__ */ get_next_sibling(node) 57 + get_next_sibling(node) 98 58 ); 99 59 if (remove) node.remove(); 100 60 node = next2; 101 61 } 102 62 } 103 - let tracing_mode_flag = false; 104 - let component_context = null; 105 - function set_component_context(context) { 106 - component_context = context; 107 - } 108 - function push(props, runes = false, fn) { 109 - component_context = { 110 - p: component_context, 111 - i: false, 112 - c: null, 113 - e: null, 114 - s: props, 115 - x: null, 116 - r: ( 117 - /** @type {Effect} */ 118 - active_effect 119 - ), 120 - l: null 121 - }; 122 - } 123 - function pop(component) { 124 - var context = ( 125 - /** @type {ComponentContext} */ 126 - component_context 127 - ); 128 - var effects = context.e; 129 - if (effects !== null) { 130 - context.e = null; 131 - for (var fn of effects) { 132 - create_user_effect(fn); 133 - } 134 - } 135 - context.i = true; 136 - component_context = context.p; 137 - return ( 138 - /** @type {T} */ 139 - {} 140 - ); 141 - } 142 - function is_runes() { 143 - return true; 144 - } 145 - let micro_tasks = []; 146 - function run_micro_tasks() { 147 - var tasks = micro_tasks; 148 - micro_tasks = []; 149 - run_all(tasks); 150 - } 151 - function queue_micro_task(fn) { 152 - if (micro_tasks.length === 0 && !is_flushing_sync) { 153 - var tasks = micro_tasks; 154 - queueMicrotask(() => { 155 - if (tasks === micro_tasks) run_micro_tasks(); 156 - }); 157 - } 158 - micro_tasks.push(fn); 159 - } 160 - function flush_tasks() { 161 - while (micro_tasks.length > 0) { 162 - run_micro_tasks(); 163 - } 164 - } 165 - function handle_error(error) { 166 - var effect = active_effect; 167 - if (effect === null) { 168 - active_reaction.f |= ERROR_VALUE; 169 - return error; 170 - } 171 - if ((effect.f & REACTION_RAN) === 0 && (effect.f & EFFECT) === 0) { 172 - throw error; 173 - } 174 - invoke_error_boundary(error, effect); 175 - } 176 - function invoke_error_boundary(error, effect) { 177 - while (effect !== null) { 178 - if ((effect.f & BOUNDARY_EFFECT) !== 0) { 179 - if ((effect.f & REACTION_RAN) === 0) { 180 - throw error; 181 - } 182 - try { 183 - effect.b.error(error); 184 - return; 185 - } catch (e) { 186 - error = e; 187 - } 188 - } 189 - effect = effect.parent; 190 - } 191 - throw error; 192 - } 193 - const STATUS_MASK = -7169; 194 - function set_signal_status(signal, status) { 195 - signal.f = signal.f & STATUS_MASK | status; 196 - } 197 - function update_derived_status(derived2) { 198 - if ((derived2.f & CONNECTED) !== 0 || derived2.deps === null) { 199 - set_signal_status(derived2, CLEAN); 200 - } else { 201 - set_signal_status(derived2, MAYBE_DIRTY); 202 - } 203 - } 204 - function clear_marked(deps) { 205 - if (deps === null) return; 206 - for (const dep of deps) { 207 - if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) { 208 - continue; 209 - } 210 - dep.f ^= WAS_MARKED; 211 - clear_marked( 212 - /** @type {Derived} */ 213 - dep.deps 214 - ); 215 - } 216 - } 217 - function defer_effect(effect, dirty_effects, maybe_dirty_effects) { 218 - if ((effect.f & DIRTY) !== 0) { 219 - dirty_effects.add(effect); 220 - } else if ((effect.f & MAYBE_DIRTY) !== 0) { 221 - maybe_dirty_effects.add(effect); 222 - } 223 - clear_marked(effect.deps); 224 - set_signal_status(effect, CLEAN); 225 - } 226 - const batches = /* @__PURE__ */ new Set(); 227 - let current_batch = null; 228 - let batch_values = null; 229 - let last_scheduled_effect = null; 230 - let is_flushing_sync = false; 231 - let is_processing = false; 232 - let collected_effects = null; 233 - let legacy_updates = null; 234 - var flush_count = 0; 235 - let uid = 1; 236 - class Batch { 237 - id = uid++; 238 - /** 239 - * The current values of any signals that are updated in this batch. 240 - * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment) 241 - * They keys of this map are identical to `this.#previous` 242 - * @type {Map<Value, [any, boolean]>} 243 - */ 244 - current = /* @__PURE__ */ new Map(); 245 - /** 246 - * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place. 247 - * They keys of this map are identical to `this.#current` 248 - * @type {Map<Value, any>} 249 - */ 250 - previous = /* @__PURE__ */ new Map(); 251 - /** 252 - * When the batch is committed (and the DOM is updated), we need to remove old branches 253 - * and append new ones by calling the functions added inside (if/each/key/etc) blocks 254 - * @type {Set<(batch: Batch) => void>} 255 - */ 256 - #commit_callbacks = /* @__PURE__ */ new Set(); 257 - /** 258 - * If a fork is discarded, we need to destroy any effects that are no longer needed 259 - * @type {Set<(batch: Batch) => void>} 260 - */ 261 - #discard_callbacks = /* @__PURE__ */ new Set(); 262 - /** 263 - * Async effects that are currently in flight 264 - * @type {Map<Effect, number>} 265 - */ 266 - #pending = /* @__PURE__ */ new Map(); 267 - /** 268 - * Async effects that are currently in flight, _not_ inside a pending boundary 269 - * @type {Map<Effect, number>} 270 - */ 271 - #blocking_pending = /* @__PURE__ */ new Map(); 272 - /** 273 - * A deferred that resolves when the batch is committed, used with `settled()` 274 - * TODO replace with Promise.withResolvers once supported widely enough 275 - * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null} 276 - */ 277 - #deferred = null; 278 - /** 279 - * The root effects that need to be flushed 280 - * @type {Effect[]} 281 - */ 282 - #roots = []; 283 - /** 284 - * Effects created while this batch was active. 285 - * @type {Effect[]} 286 - */ 287 - #new_effects = []; 288 - /** 289 - * Deferred effects (which run after async work has completed) that are DIRTY 290 - * @type {Set<Effect>} 291 - */ 292 - #dirty_effects = /* @__PURE__ */ new Set(); 293 - /** 294 - * Deferred effects that are MAYBE_DIRTY 295 - * @type {Set<Effect>} 296 - */ 297 - #maybe_dirty_effects = /* @__PURE__ */ new Set(); 298 - /** 299 - * A map of branches that still exist, but will be destroyed when this batch 300 - * is committed — we skip over these during `process`. 301 - * The value contains child effects that were dirty/maybe_dirty before being reset, 302 - * so they can be rescheduled if the branch survives. 303 - * @type {Map<Effect, { d: Effect[], m: Effect[] }>} 304 - */ 305 - #skipped_branches = /* @__PURE__ */ new Map(); 306 - is_fork = false; 307 - #decrement_queued = false; 308 - /** @type {Set<Batch>} */ 309 - #blockers = /* @__PURE__ */ new Set(); 310 - #is_deferred() { 311 - return this.is_fork || this.#blocking_pending.size > 0; 312 - } 313 - #is_blocked() { 314 - for (const batch of this.#blockers) { 315 - for (const effect of batch.#blocking_pending.keys()) { 316 - var skipped = false; 317 - var e = effect; 318 - while (e.parent !== null) { 319 - if (this.#skipped_branches.has(e)) { 320 - skipped = true; 321 - break; 322 - } 323 - e = e.parent; 324 - } 325 - if (!skipped) { 326 - return true; 327 - } 328 - } 329 - } 330 - return false; 331 - } 332 - /** 333 - * Add an effect to the #skipped_branches map and reset its children 334 - * @param {Effect} effect 335 - */ 336 - skip_effect(effect) { 337 - if (!this.#skipped_branches.has(effect)) { 338 - this.#skipped_branches.set(effect, { d: [], m: [] }); 339 - } 340 - } 341 - /** 342 - * Remove an effect from the #skipped_branches map and reschedule 343 - * any tracked dirty/maybe_dirty child effects 344 - * @param {Effect} effect 345 - */ 346 - unskip_effect(effect) { 347 - var tracked = this.#skipped_branches.get(effect); 348 - if (tracked) { 349 - this.#skipped_branches.delete(effect); 350 - for (var e of tracked.d) { 351 - set_signal_status(e, DIRTY); 352 - this.schedule(e); 353 - } 354 - for (e of tracked.m) { 355 - set_signal_status(e, MAYBE_DIRTY); 356 - this.schedule(e); 357 - } 358 - } 359 - } 360 - #process() { 361 - if (flush_count++ > 1e3) { 362 - batches.delete(this); 363 - infinite_loop_guard(); 364 - } 365 - if (!this.#is_deferred()) { 366 - for (const e of this.#dirty_effects) { 367 - this.#maybe_dirty_effects.delete(e); 368 - set_signal_status(e, DIRTY); 369 - this.schedule(e); 370 - } 371 - for (const e of this.#maybe_dirty_effects) { 372 - set_signal_status(e, MAYBE_DIRTY); 373 - this.schedule(e); 374 - } 375 - } 376 - const roots = this.#roots; 377 - this.#roots = []; 378 - this.apply(); 379 - var effects = collected_effects = []; 380 - var render_effects = []; 381 - var updates = legacy_updates = []; 382 - for (const root2 of roots) { 383 - try { 384 - this.#traverse(root2, effects, render_effects); 385 - } catch (e) { 386 - reset_all(root2); 387 - throw e; 388 - } 389 - } 390 - current_batch = null; 391 - if (updates.length > 0) { 392 - var batch = Batch.ensure(); 393 - for (const e of updates) { 394 - batch.schedule(e); 395 - } 396 - } 397 - collected_effects = null; 398 - legacy_updates = null; 399 - if (this.#is_deferred() || this.#is_blocked()) { 400 - this.#defer_effects(render_effects); 401 - this.#defer_effects(effects); 402 - for (const [e, t] of this.#skipped_branches) { 403 - reset_branch(e, t); 404 - } 405 - } else { 406 - if (this.#pending.size === 0) { 407 - batches.delete(this); 408 - } 409 - this.#dirty_effects.clear(); 410 - this.#maybe_dirty_effects.clear(); 411 - for (const fn of this.#commit_callbacks) fn(this); 412 - this.#commit_callbacks.clear(); 413 - flush_queued_effects(render_effects); 414 - flush_queued_effects(effects); 415 - this.#deferred?.resolve(); 416 - } 417 - var next_batch = ( 418 - /** @type {Batch | null} */ 419 - /** @type {unknown} */ 420 - current_batch 421 - ); 422 - if (this.#roots.length > 0) { 423 - const batch2 = next_batch ??= this; 424 - batch2.#roots.push(...this.#roots.filter((r) => !batch2.#roots.includes(r))); 425 - } 426 - if (next_batch !== null) { 427 - batches.add(next_batch); 428 - next_batch.#process(); 429 - } 430 - if (!batches.has(this)) { 431 - this.#commit(); 432 - } 433 - } 434 - /** 435 - * Traverse the effect tree, executing effects or stashing 436 - * them for later execution as appropriate 437 - * @param {Effect} root 438 - * @param {Effect[]} effects 439 - * @param {Effect[]} render_effects 440 - */ 441 - #traverse(root2, effects, render_effects) { 442 - root2.f ^= CLEAN; 443 - var effect = root2.first; 444 - while (effect !== null) { 445 - var flags2 = effect.f; 446 - var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0; 447 - var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0; 448 - var skip = is_skippable_branch || (flags2 & INERT) !== 0 || this.#skipped_branches.has(effect); 449 - if (!skip && effect.fn !== null) { 450 - if (is_branch) { 451 - effect.f ^= CLEAN; 452 - } else if ((flags2 & EFFECT) !== 0) { 453 - effects.push(effect); 454 - } else if (is_dirty(effect)) { 455 - if ((flags2 & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect); 456 - update_effect(effect); 457 - } 458 - var child = effect.first; 459 - if (child !== null) { 460 - effect = child; 461 - continue; 462 - } 463 - } 464 - while (effect !== null) { 465 - var next2 = effect.next; 466 - if (next2 !== null) { 467 - effect = next2; 468 - break; 469 - } 470 - effect = effect.parent; 471 - } 472 - } 473 - } 474 - /** 475 - * @param {Effect[]} effects 476 - */ 477 - #defer_effects(effects) { 478 - for (var i = 0; i < effects.length; i += 1) { 479 - defer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects); 480 - } 481 - } 482 - /** 483 - * Associate a change to a given source with the current 484 - * batch, noting its previous and current values 485 - * @param {Value} source 486 - * @param {any} old_value 487 - * @param {boolean} [is_derived] 488 - */ 489 - capture(source2, old_value, is_derived = false) { 490 - if (old_value !== UNINITIALIZED && !this.previous.has(source2)) { 491 - this.previous.set(source2, old_value); 492 - } 493 - if ((source2.f & ERROR_VALUE) === 0) { 494 - this.current.set(source2, [source2.v, is_derived]); 495 - batch_values?.set(source2, source2.v); 496 - } 497 - } 498 - activate() { 499 - current_batch = this; 500 - } 501 - deactivate() { 502 - current_batch = null; 503 - batch_values = null; 504 - } 505 - flush() { 506 - try { 507 - is_processing = true; 508 - current_batch = this; 509 - this.#process(); 510 - } finally { 511 - flush_count = 0; 512 - last_scheduled_effect = null; 513 - collected_effects = null; 514 - legacy_updates = null; 515 - is_processing = false; 516 - current_batch = null; 517 - batch_values = null; 518 - old_values.clear(); 519 - } 520 - } 521 - discard() { 522 - for (const fn of this.#discard_callbacks) fn(this); 523 - this.#discard_callbacks.clear(); 524 - batches.delete(this); 525 - } 526 - /** 527 - * @param {Effect} effect 528 - */ 529 - register_created_effect(effect) { 530 - this.#new_effects.push(effect); 531 - } 532 - #commit() { 533 - for (const batch of batches) { 534 - var is_earlier = batch.id < this.id; 535 - var sources = []; 536 - for (const [source3, [value, is_derived]] of this.current) { 537 - if (batch.current.has(source3)) { 538 - var batch_value = ( 539 - /** @type {[any, boolean]} */ 540 - batch.current.get(source3)[0] 541 - ); 542 - if (is_earlier && value !== batch_value) { 543 - batch.current.set(source3, [value, is_derived]); 544 - } else { 545 - continue; 546 - } 547 - } 548 - sources.push(source3); 549 - } 550 - var others = [...batch.current.keys()].filter((s) => !this.current.has(s)); 551 - if (others.length === 0) { 552 - if (is_earlier) { 553 - batch.discard(); 554 - } 555 - } else if (sources.length > 0) { 556 - batch.activate(); 557 - var marked = /* @__PURE__ */ new Set(); 558 - var checked = /* @__PURE__ */ new Map(); 559 - for (var source2 of sources) { 560 - mark_effects(source2, others, marked, checked); 561 - } 562 - checked = /* @__PURE__ */ new Map(); 563 - var current_unequal = [...batch.current.keys()].filter( 564 - (c) => this.current.has(c) ? ( 565 - /** @type {[any, boolean]} */ 566 - this.current.get(c)[0] !== c 567 - ) : true 568 - ); 569 - for (const effect of this.#new_effects) { 570 - if ((effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 && depends_on(effect, current_unequal, checked)) { 571 - if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) { 572 - set_signal_status(effect, DIRTY); 573 - batch.schedule(effect); 574 - } else { 575 - batch.#dirty_effects.add(effect); 576 - } 577 - } 578 - } 579 - if (batch.#roots.length > 0) { 580 - batch.apply(); 581 - for (var root2 of batch.#roots) { 582 - batch.#traverse(root2, [], []); 583 - } 584 - batch.#roots = []; 585 - } 586 - batch.deactivate(); 587 - } 588 - } 589 - for (const batch of batches) { 590 - if (batch.#blockers.has(this)) { 591 - batch.#blockers.delete(this); 592 - if (batch.#blockers.size === 0 && !batch.#is_deferred()) { 593 - batch.activate(); 594 - batch.#process(); 595 - } 596 - } 597 - } 598 - } 599 - /** 600 - * @param {boolean} blocking 601 - * @param {Effect} effect 602 - */ 603 - increment(blocking, effect) { 604 - let pending_count = this.#pending.get(effect) ?? 0; 605 - this.#pending.set(effect, pending_count + 1); 606 - if (blocking) { 607 - let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0; 608 - this.#blocking_pending.set(effect, blocking_pending_count + 1); 609 - } 610 - } 611 - /** 612 - * @param {boolean} blocking 613 - * @param {Effect} effect 614 - * @param {boolean} skip - whether to skip updates (because this is triggered by a stale reaction) 615 - */ 616 - decrement(blocking, effect, skip) { 617 - let pending_count = this.#pending.get(effect) ?? 0; 618 - if (pending_count === 1) { 619 - this.#pending.delete(effect); 620 - } else { 621 - this.#pending.set(effect, pending_count - 1); 622 - } 623 - if (blocking) { 624 - let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0; 625 - if (blocking_pending_count === 1) { 626 - this.#blocking_pending.delete(effect); 627 - } else { 628 - this.#blocking_pending.set(effect, blocking_pending_count - 1); 629 - } 630 - } 631 - if (this.#decrement_queued || skip) return; 632 - this.#decrement_queued = true; 633 - queue_micro_task(() => { 634 - this.#decrement_queued = false; 635 - this.flush(); 636 - }); 637 - } 638 - /** 639 - * @param {Set<Effect>} dirty_effects 640 - * @param {Set<Effect>} maybe_dirty_effects 641 - */ 642 - transfer_effects(dirty_effects, maybe_dirty_effects) { 643 - for (const e of dirty_effects) { 644 - this.#dirty_effects.add(e); 645 - } 646 - for (const e of maybe_dirty_effects) { 647 - this.#maybe_dirty_effects.add(e); 648 - } 649 - dirty_effects.clear(); 650 - maybe_dirty_effects.clear(); 651 - } 652 - /** @param {(batch: Batch) => void} fn */ 653 - oncommit(fn) { 654 - this.#commit_callbacks.add(fn); 655 - } 656 - /** @param {(batch: Batch) => void} fn */ 657 - ondiscard(fn) { 658 - this.#discard_callbacks.add(fn); 659 - } 660 - settled() { 661 - return (this.#deferred ??= deferred()).promise; 662 - } 663 - static ensure() { 664 - if (current_batch === null) { 665 - const batch = current_batch = new Batch(); 666 - if (!is_processing) { 667 - batches.add(current_batch); 668 - if (!is_flushing_sync) { 669 - queue_micro_task(() => { 670 - if (current_batch !== batch) { 671 - return; 672 - } 673 - batch.flush(); 674 - }); 675 - } 676 - } 677 - } 678 - return current_batch; 679 - } 680 - apply() { 681 - { 682 - batch_values = null; 683 - return; 684 - } 685 - } 686 - /** 687 - * 688 - * @param {Effect} effect 689 - */ 690 - schedule(effect) { 691 - last_scheduled_effect = effect; 692 - if (effect.b?.is_pending && (effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 && (effect.f & REACTION_RAN) === 0) { 693 - effect.b.defer_effect(effect); 694 - return; 695 - } 696 - var e = effect; 697 - while (e.parent !== null) { 698 - e = e.parent; 699 - var flags2 = e.f; 700 - if (collected_effects !== null && e === active_effect) { 701 - if ((active_reaction === null || (active_reaction.f & DERIVED) === 0) && true) { 702 - return; 703 - } 704 - } 705 - if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { 706 - if ((flags2 & CLEAN) === 0) { 707 - return; 708 - } 709 - e.f ^= CLEAN; 710 - } 711 - } 712 - this.#roots.push(e); 713 - } 714 - } 715 - function flushSync(fn) { 716 - var was_flushing_sync = is_flushing_sync; 717 - is_flushing_sync = true; 718 - try { 719 - var result; 720 - if (fn) ; 721 - while (true) { 722 - flush_tasks(); 723 - if (current_batch === null) { 724 - return ( 725 - /** @type {T} */ 726 - result 727 - ); 728 - } 729 - current_batch.flush(); 730 - } 731 - } finally { 732 - is_flushing_sync = was_flushing_sync; 733 - } 734 - } 735 - function infinite_loop_guard() { 736 - try { 737 - effect_update_depth_exceeded(); 738 - } catch (error) { 739 - invoke_error_boundary(error, last_scheduled_effect); 740 - } 741 - } 742 - let eager_block_effects = null; 743 - function flush_queued_effects(effects) { 744 - var length = effects.length; 745 - if (length === 0) return; 746 - var i = 0; 747 - while (i < length) { 748 - var effect = effects[i++]; 749 - if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) { 750 - eager_block_effects = /* @__PURE__ */ new Set(); 751 - update_effect(effect); 752 - if (effect.deps === null && effect.first === null && effect.nodes === null && effect.teardown === null && effect.ac === null) { 753 - unlink_effect(effect); 754 - } 755 - if (eager_block_effects?.size > 0) { 756 - old_values.clear(); 757 - for (const e of eager_block_effects) { 758 - if ((e.f & (DESTROYED | INERT)) !== 0) continue; 759 - const ordered_effects = [e]; 760 - let ancestor = e.parent; 761 - while (ancestor !== null) { 762 - if (eager_block_effects.has(ancestor)) { 763 - eager_block_effects.delete(ancestor); 764 - ordered_effects.push(ancestor); 765 - } 766 - ancestor = ancestor.parent; 767 - } 768 - for (let j = ordered_effects.length - 1; j >= 0; j--) { 769 - const e2 = ordered_effects[j]; 770 - if ((e2.f & (DESTROYED | INERT)) !== 0) continue; 771 - update_effect(e2); 772 - } 773 - } 774 - eager_block_effects.clear(); 775 - } 776 - } 777 - } 778 - eager_block_effects = null; 779 - } 780 - function mark_effects(value, sources, marked, checked) { 781 - if (marked.has(value)) return; 782 - marked.add(value); 783 - if (value.reactions !== null) { 784 - for (const reaction of value.reactions) { 785 - const flags2 = reaction.f; 786 - if ((flags2 & DERIVED) !== 0) { 787 - mark_effects( 788 - /** @type {Derived} */ 789 - reaction, 790 - sources, 791 - marked, 792 - checked 793 - ); 794 - } else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && depends_on(reaction, sources, checked)) { 795 - set_signal_status(reaction, DIRTY); 796 - schedule_effect( 797 - /** @type {Effect} */ 798 - reaction 799 - ); 800 - } 801 - } 802 - } 803 - } 804 - function depends_on(reaction, sources, checked) { 805 - const depends = checked.get(reaction); 806 - if (depends !== void 0) return depends; 807 - if (reaction.deps !== null) { 808 - for (const dep of reaction.deps) { 809 - if (includes.call(sources, dep)) { 810 - return true; 811 - } 812 - if ((dep.f & DERIVED) !== 0 && depends_on( 813 - /** @type {Derived} */ 814 - dep, 815 - sources, 816 - checked 817 - )) { 818 - checked.set( 819 - /** @type {Derived} */ 820 - dep, 821 - true 822 - ); 823 - return true; 824 - } 825 - } 826 - } 827 - checked.set(reaction, false); 828 - return false; 829 - } 830 - function schedule_effect(effect) { 831 - current_batch.schedule(effect); 832 - } 833 - function reset_branch(effect, tracked) { 834 - if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) { 835 - return; 836 - } 837 - if ((effect.f & DIRTY) !== 0) { 838 - tracked.d.push(effect); 839 - } else if ((effect.f & MAYBE_DIRTY) !== 0) { 840 - tracked.m.push(effect); 841 - } 842 - set_signal_status(effect, CLEAN); 843 - var e = effect.first; 844 - while (e !== null) { 845 - reset_branch(e, tracked); 846 - e = e.next; 847 - } 848 - } 849 - function reset_all(effect) { 850 - set_signal_status(effect, CLEAN); 851 - var e = effect.first; 852 - while (e !== null) { 853 - reset_all(e); 854 - e = e.next; 855 - } 856 - } 857 63 function createSubscriber(start) { 858 64 let subscribers = 0; 859 65 let version = source(0); ··· 1259 465 }); 1260 466 } 1261 467 } 1262 - function destroy_derived_effects(derived2) { 1263 - var effects = derived2.effects; 1264 - if (effects !== null) { 1265 - derived2.effects = null; 1266 - for (var i = 0; i < effects.length; i += 1) { 1267 - destroy_effect( 1268 - /** @type {Effect} */ 1269 - effects[i] 1270 - ); 1271 - } 1272 - } 1273 - } 1274 - function get_derived_parent_effect(derived2) { 1275 - var parent = derived2.parent; 1276 - while (parent !== null) { 1277 - if ((parent.f & DERIVED) === 0) { 1278 - return (parent.f & DESTROYED) === 0 ? ( 1279 - /** @type {Effect} */ 1280 - parent 1281 - ) : null; 1282 - } 1283 - parent = parent.parent; 1284 - } 1285 - return null; 1286 - } 1287 - function execute_derived(derived2) { 1288 - var value; 1289 - var prev_active_effect = active_effect; 1290 - set_active_effect(get_derived_parent_effect(derived2)); 1291 - { 1292 - try { 1293 - derived2.f &= ~WAS_MARKED; 1294 - destroy_derived_effects(derived2); 1295 - value = update_reaction(derived2); 1296 - } finally { 1297 - set_active_effect(prev_active_effect); 1298 - } 1299 - } 1300 - return value; 1301 - } 1302 - function update_derived(derived2) { 1303 - var old_value = derived2.v; 1304 - var value = execute_derived(derived2); 1305 - if (!derived2.equals(value)) { 1306 - derived2.wv = increment_write_version(); 1307 - if (!current_batch?.is_fork || derived2.deps === null) { 1308 - derived2.v = value; 1309 - current_batch?.capture(derived2, old_value, true); 1310 - if (derived2.deps === null) { 1311 - set_signal_status(derived2, CLEAN); 1312 - return; 1313 - } 1314 - } 1315 - } 1316 - if (is_destroying_effect) { 1317 - return; 1318 - } 1319 - if (batch_values !== null) { 1320 - if (effect_tracking() || current_batch?.is_fork) { 1321 - batch_values.set(derived2, value); 1322 - } 1323 - } else { 1324 - update_derived_status(derived2); 1325 - } 1326 - } 1327 - function freeze_derived_effects(derived2) { 1328 - if (derived2.effects === null) return; 1329 - for (const e of derived2.effects) { 1330 - if (e.teardown || e.ac) { 1331 - e.teardown?.(); 1332 - e.ac?.abort(STALE_REACTION); 1333 - e.teardown = noop; 1334 - e.ac = null; 1335 - remove_reactions(e, 0); 1336 - destroy_effect_children(e); 1337 - } 1338 - } 1339 - } 1340 - function unfreeze_derived_effects(derived2) { 1341 - if (derived2.effects === null) return; 1342 - for (const e of derived2.effects) { 1343 - if (e.teardown) { 1344 - update_effect(e); 1345 - } 1346 - } 1347 - } 1348 - let eager_effects = /* @__PURE__ */ new Set(); 1349 - const old_values = /* @__PURE__ */ new Map(); 1350 - let eager_effects_deferred = false; 1351 - function source(v, stack) { 1352 - var signal = { 1353 - f: 0, 1354 - // TODO ideally we could skip this altogether, but it causes type errors 1355 - v, 1356 - reactions: null, 1357 - equals, 1358 - rv: 0, 1359 - wv: 0 1360 - }; 1361 - return signal; 1362 - } 1363 - // @__NO_SIDE_EFFECTS__ 1364 - function state(v, stack) { 1365 - const s = source(v); 1366 - push_reaction_value(s); 1367 - return s; 1368 - } 1369 - // @__NO_SIDE_EFFECTS__ 1370 - function mutable_source(initial_value, immutable = false, trackable = true) { 1371 - const s = source(initial_value); 1372 - if (!immutable) { 1373 - s.equals = safe_equals; 1374 - } 1375 - return s; 1376 - } 1377 - function set(source2, value, should_proxy = false) { 1378 - if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check 1379 - // to ensure we error if state is set inside an inspect effect 1380 - (!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !includes.call(current_sources, source2))) { 1381 - state_unsafe_mutation(); 1382 - } 1383 - let new_value = should_proxy ? proxy(value) : value; 1384 - return internal_set(source2, new_value, legacy_updates); 1385 - } 1386 - function internal_set(source2, value, updated_during_traversal = null) { 1387 - if (!source2.equals(value)) { 1388 - var old_value = source2.v; 1389 - if (is_destroying_effect) { 1390 - old_values.set(source2, value); 1391 - } else { 1392 - old_values.set(source2, old_value); 1393 - } 1394 - source2.v = value; 1395 - var batch = Batch.ensure(); 1396 - batch.capture(source2, old_value); 1397 - if ((source2.f & DERIVED) !== 0) { 1398 - const derived2 = ( 1399 - /** @type {Derived} */ 1400 - source2 1401 - ); 1402 - if ((source2.f & DIRTY) !== 0) { 1403 - execute_derived(derived2); 1404 - } 1405 - if (batch_values === null) { 1406 - update_derived_status(derived2); 1407 - } 1408 - } 1409 - source2.wv = increment_write_version(); 1410 - mark_reactions(source2, DIRTY, updated_during_traversal); 1411 - if (active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) { 1412 - if (untracked_writes === null) { 1413 - set_untracked_writes([source2]); 1414 - } else { 1415 - untracked_writes.push(source2); 1416 - } 1417 - } 1418 - if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) { 1419 - flush_eager_effects(); 1420 - } 1421 - } 1422 - return value; 1423 - } 1424 - function flush_eager_effects() { 1425 - eager_effects_deferred = false; 1426 - for (const effect of eager_effects) { 1427 - if ((effect.f & CLEAN) !== 0) { 1428 - set_signal_status(effect, MAYBE_DIRTY); 1429 - } 1430 - if (is_dirty(effect)) { 1431 - update_effect(effect); 1432 - } 1433 - } 1434 - eager_effects.clear(); 1435 - } 1436 - function increment(source2) { 1437 - set(source2, source2.v + 1); 1438 - } 1439 - function mark_reactions(signal, status, updated_during_traversal) { 1440 - var reactions = signal.reactions; 1441 - if (reactions === null) return; 1442 - var length = reactions.length; 1443 - for (var i = 0; i < length; i++) { 1444 - var reaction = reactions[i]; 1445 - var flags2 = reaction.f; 1446 - var not_dirty = (flags2 & DIRTY) === 0; 1447 - if (not_dirty) { 1448 - set_signal_status(reaction, status); 1449 - } 1450 - if ((flags2 & DERIVED) !== 0) { 1451 - var derived2 = ( 1452 - /** @type {Derived} */ 1453 - reaction 1454 - ); 1455 - batch_values?.delete(derived2); 1456 - if ((flags2 & WAS_MARKED) === 0) { 1457 - if (flags2 & CONNECTED) { 1458 - reaction.f |= WAS_MARKED; 1459 - } 1460 - mark_reactions(derived2, MAYBE_DIRTY, updated_during_traversal); 1461 - } 1462 - } else if (not_dirty) { 1463 - var effect = ( 1464 - /** @type {Effect} */ 1465 - reaction 1466 - ); 1467 - if ((flags2 & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) { 1468 - eager_block_effects.add(effect); 1469 - } 1470 - if (updated_during_traversal !== null) { 1471 - updated_during_traversal.push(effect); 1472 - } else { 1473 - schedule_effect(effect); 1474 - } 1475 - } 1476 - } 1477 - } 1478 - function proxy(value) { 1479 - if (typeof value !== "object" || value === null || STATE_SYMBOL in value) { 1480 - return value; 1481 - } 1482 - const prototype = get_prototype_of(value); 1483 - if (prototype !== object_prototype && prototype !== array_prototype) { 1484 - return value; 1485 - } 1486 - var sources = /* @__PURE__ */ new Map(); 1487 - var is_proxied_array = is_array(value); 1488 - var version = /* @__PURE__ */ state(0); 1489 - var parent_version = update_version; 1490 - var with_parent = (fn) => { 1491 - if (update_version === parent_version) { 1492 - return fn(); 1493 - } 1494 - var reaction = active_reaction; 1495 - var version2 = update_version; 1496 - set_active_reaction(null); 1497 - set_update_version(parent_version); 1498 - var result = fn(); 1499 - set_active_reaction(reaction); 1500 - set_update_version(version2); 1501 - return result; 1502 - }; 1503 - if (is_proxied_array) { 1504 - sources.set("length", /* @__PURE__ */ state( 1505 - /** @type {any[]} */ 1506 - value.length 1507 - )); 1508 - } 1509 - return new Proxy( 1510 - /** @type {any} */ 1511 - value, 1512 - { 1513 - defineProperty(_, prop, descriptor) { 1514 - if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) { 1515 - state_descriptors_fixed(); 1516 - } 1517 - var s = sources.get(prop); 1518 - if (s === void 0) { 1519 - with_parent(() => { 1520 - var s2 = /* @__PURE__ */ state(descriptor.value); 1521 - sources.set(prop, s2); 1522 - return s2; 1523 - }); 1524 - } else { 1525 - set(s, descriptor.value, true); 1526 - } 1527 - return true; 1528 - }, 1529 - deleteProperty(target, prop) { 1530 - var s = sources.get(prop); 1531 - if (s === void 0) { 1532 - if (prop in target) { 1533 - const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); 1534 - sources.set(prop, s2); 1535 - increment(version); 1536 - } 1537 - } else { 1538 - set(s, UNINITIALIZED); 1539 - increment(version); 1540 - } 1541 - return true; 1542 - }, 1543 - get(target, prop, receiver) { 1544 - if (prop === STATE_SYMBOL) { 1545 - return value; 1546 - } 1547 - var s = sources.get(prop); 1548 - var exists = prop in target; 1549 - if (s === void 0 && (!exists || get_descriptor(target, prop)?.writable)) { 1550 - s = with_parent(() => { 1551 - var p = proxy(exists ? target[prop] : UNINITIALIZED); 1552 - var s2 = /* @__PURE__ */ state(p); 1553 - return s2; 1554 - }); 1555 - sources.set(prop, s); 1556 - } 1557 - if (s !== void 0) { 1558 - var v = get(s); 1559 - return v === UNINITIALIZED ? void 0 : v; 1560 - } 1561 - return Reflect.get(target, prop, receiver); 1562 - }, 1563 - getOwnPropertyDescriptor(target, prop) { 1564 - var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); 1565 - if (descriptor && "value" in descriptor) { 1566 - var s = sources.get(prop); 1567 - if (s) descriptor.value = get(s); 1568 - } else if (descriptor === void 0) { 1569 - var source2 = sources.get(prop); 1570 - var value2 = source2?.v; 1571 - if (source2 !== void 0 && value2 !== UNINITIALIZED) { 1572 - return { 1573 - enumerable: true, 1574 - configurable: true, 1575 - value: value2, 1576 - writable: true 1577 - }; 1578 - } 1579 - } 1580 - return descriptor; 1581 - }, 1582 - has(target, prop) { 1583 - if (prop === STATE_SYMBOL) { 1584 - return true; 1585 - } 1586 - var s = sources.get(prop); 1587 - var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop); 1588 - if (s !== void 0 || active_effect !== null && (!has || get_descriptor(target, prop)?.writable)) { 1589 - if (s === void 0) { 1590 - s = with_parent(() => { 1591 - var p = has ? proxy(target[prop]) : UNINITIALIZED; 1592 - var s2 = /* @__PURE__ */ state(p); 1593 - return s2; 1594 - }); 1595 - sources.set(prop, s); 1596 - } 1597 - var value2 = get(s); 1598 - if (value2 === UNINITIALIZED) { 1599 - return false; 1600 - } 1601 - } 1602 - return has; 1603 - }, 1604 - set(target, prop, value2, receiver) { 1605 - var s = sources.get(prop); 1606 - var has = prop in target; 1607 - if (is_proxied_array && prop === "length") { 1608 - for (var i = value2; i < /** @type {Source<number>} */ 1609 - s.v; i += 1) { 1610 - var other_s = sources.get(i + ""); 1611 - if (other_s !== void 0) { 1612 - set(other_s, UNINITIALIZED); 1613 - } else if (i in target) { 1614 - other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); 1615 - sources.set(i + "", other_s); 1616 - } 1617 - } 1618 - } 1619 - if (s === void 0) { 1620 - if (!has || get_descriptor(target, prop)?.writable) { 1621 - s = with_parent(() => /* @__PURE__ */ state(void 0)); 1622 - set(s, proxy(value2)); 1623 - sources.set(prop, s); 1624 - } 1625 - } else { 1626 - has = s.v !== UNINITIALIZED; 1627 - var p = with_parent(() => proxy(value2)); 1628 - set(s, p); 1629 - } 1630 - var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); 1631 - if (descriptor?.set) { 1632 - descriptor.set.call(receiver, value2); 1633 - } 1634 - if (!has) { 1635 - if (is_proxied_array && typeof prop === "string") { 1636 - var ls = ( 1637 - /** @type {Source<number>} */ 1638 - sources.get("length") 1639 - ); 1640 - var n = Number(prop); 1641 - if (Number.isInteger(n) && n >= ls.v) { 1642 - set(ls, n + 1); 1643 - } 1644 - } 1645 - increment(version); 1646 - } 1647 - return true; 1648 - }, 1649 - ownKeys(target) { 1650 - get(version); 1651 - var own_keys = Reflect.ownKeys(target).filter((key2) => { 1652 - var source3 = sources.get(key2); 1653 - return source3 === void 0 || source3.v !== UNINITIALIZED; 1654 - }); 1655 - for (var [key, source2] of sources) { 1656 - if (source2.v !== UNINITIALIZED && !(key in target)) { 1657 - own_keys.push(key); 1658 - } 1659 - } 1660 - return own_keys; 1661 - }, 1662 - setPrototypeOf() { 1663 - state_prototype_fixed(); 1664 - } 1665 - } 1666 - ); 1667 - } 1668 - var $window; 1669 - var first_child_getter; 1670 - var next_sibling_getter; 1671 - function init_operations() { 1672 - if ($window !== void 0) { 1673 - return; 1674 - } 1675 - $window = window; 1676 - var element_prototype = Element.prototype; 1677 - var node_prototype = Node.prototype; 1678 - var text_prototype = Text.prototype; 1679 - first_child_getter = get_descriptor(node_prototype, "firstChild").get; 1680 - next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get; 1681 - if (is_extensible(element_prototype)) { 1682 - element_prototype.__click = void 0; 1683 - element_prototype.__className = void 0; 1684 - element_prototype.__attributes = null; 1685 - element_prototype.__style = void 0; 1686 - element_prototype.__e = void 0; 1687 - } 1688 - if (is_extensible(text_prototype)) { 1689 - text_prototype.__t = void 0; 1690 - } 1691 - } 1692 - function create_text(value = "") { 1693 - return document.createTextNode(value); 1694 - } 1695 - // @__NO_SIDE_EFFECTS__ 1696 - function get_first_child(node) { 1697 - return ( 1698 - /** @type {TemplateNode | null} */ 1699 - first_child_getter.call(node) 1700 - ); 1701 - } 1702 - // @__NO_SIDE_EFFECTS__ 1703 - function get_next_sibling(node) { 1704 - return ( 1705 - /** @type {TemplateNode | null} */ 1706 - next_sibling_getter.call(node) 1707 - ); 1708 - } 1709 - function clear_text_content(node) { 1710 - node.textContent = ""; 1711 - } 1712 - function without_reactive_context(fn) { 1713 - var previous_reaction = active_reaction; 1714 - var previous_effect = active_effect; 1715 - set_active_reaction(null); 1716 - set_active_effect(null); 1717 - try { 1718 - return fn(); 1719 - } finally { 1720 - set_active_reaction(previous_reaction); 1721 - set_active_effect(previous_effect); 1722 - } 1723 - } 1724 - function push_effect(effect, parent_effect) { 1725 - var parent_last = parent_effect.last; 1726 - if (parent_last === null) { 1727 - parent_effect.last = parent_effect.first = effect; 1728 - } else { 1729 - parent_last.next = effect; 1730 - effect.prev = parent_last; 1731 - parent_effect.last = effect; 1732 - } 1733 - } 1734 - function create_effect(type, fn) { 1735 - var parent = active_effect; 1736 - if (parent !== null && (parent.f & INERT) !== 0) { 1737 - type |= INERT; 1738 - } 1739 - var effect = { 1740 - ctx: component_context, 1741 - deps: null, 1742 - nodes: null, 1743 - f: type | DIRTY | CONNECTED, 1744 - first: null, 1745 - fn, 1746 - last: null, 1747 - next: null, 1748 - parent, 1749 - b: parent && parent.b, 1750 - prev: null, 1751 - teardown: null, 1752 - wv: 0, 1753 - ac: null 1754 - }; 1755 - current_batch?.register_created_effect(effect); 1756 - var e = effect; 1757 - if ((type & EFFECT) !== 0) { 1758 - if (collected_effects !== null) { 1759 - collected_effects.push(effect); 1760 - } else { 1761 - Batch.ensure().schedule(effect); 1762 - } 1763 - } else if (fn !== null) { 1764 - try { 1765 - update_effect(effect); 1766 - } catch (e2) { 1767 - destroy_effect(effect); 1768 - throw e2; 1769 - } 1770 - if (e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child 1771 - (e.f & EFFECT_PRESERVED) === 0) { 1772 - e = e.first; 1773 - if ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) { 1774 - e.f |= EFFECT_TRANSPARENT; 1775 - } 1776 - } 1777 - } 1778 - if (e !== null) { 1779 - e.parent = parent; 1780 - if (parent !== null) { 1781 - push_effect(e, parent); 1782 - } 1783 - if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) { 1784 - var derived2 = ( 1785 - /** @type {Derived} */ 1786 - active_reaction 1787 - ); 1788 - (derived2.effects ??= []).push(e); 1789 - } 1790 - } 1791 - return effect; 1792 - } 1793 - function effect_tracking() { 1794 - return active_reaction !== null && !untracking; 1795 - } 1796 - function create_user_effect(fn) { 1797 - return create_effect(EFFECT | USER_EFFECT, fn); 1798 - } 1799 - function component_root(fn) { 1800 - Batch.ensure(); 1801 - const effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn); 1802 - return (options = {}) => { 1803 - return new Promise((fulfil) => { 1804 - if (options.outro) { 1805 - pause_effect(effect, () => { 1806 - destroy_effect(effect); 1807 - fulfil(void 0); 1808 - }); 1809 - } else { 1810 - destroy_effect(effect); 1811 - fulfil(void 0); 1812 - } 1813 - }); 1814 - }; 1815 - } 1816 - function render_effect(fn, flags2 = 0) { 1817 - return create_effect(RENDER_EFFECT | flags2, fn); 1818 - } 1819 - function block(fn, flags2 = 0) { 1820 - var effect = create_effect(BLOCK_EFFECT | flags2, fn); 1821 - return effect; 1822 - } 1823 - function branch(fn) { 1824 - return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn); 1825 - } 1826 - function execute_effect_teardown(effect) { 1827 - var teardown = effect.teardown; 1828 - if (teardown !== null) { 1829 - const previously_destroying_effect = is_destroying_effect; 1830 - const previous_reaction = active_reaction; 1831 - set_is_destroying_effect(true); 1832 - set_active_reaction(null); 1833 - try { 1834 - teardown.call(null); 1835 - } finally { 1836 - set_is_destroying_effect(previously_destroying_effect); 1837 - set_active_reaction(previous_reaction); 1838 - } 1839 - } 1840 - } 1841 - function destroy_effect_children(signal, remove_dom = false) { 1842 - var effect = signal.first; 1843 - signal.first = signal.last = null; 1844 - while (effect !== null) { 1845 - const controller = effect.ac; 1846 - if (controller !== null) { 1847 - without_reactive_context(() => { 1848 - controller.abort(STALE_REACTION); 1849 - }); 1850 - } 1851 - var next2 = effect.next; 1852 - if ((effect.f & ROOT_EFFECT) !== 0) { 1853 - effect.parent = null; 1854 - } else { 1855 - destroy_effect(effect, remove_dom); 1856 - } 1857 - effect = next2; 1858 - } 1859 - } 1860 - function destroy_block_effect_children(signal) { 1861 - var effect = signal.first; 1862 - while (effect !== null) { 1863 - var next2 = effect.next; 1864 - if ((effect.f & BRANCH_EFFECT) === 0) { 1865 - destroy_effect(effect); 1866 - } 1867 - effect = next2; 1868 - } 1869 - } 1870 - function destroy_effect(effect, remove_dom = true) { 1871 - var removed = false; 1872 - if ((remove_dom || (effect.f & HEAD_EFFECT) !== 0) && effect.nodes !== null && effect.nodes.end !== null) { 1873 - remove_effect_dom( 1874 - effect.nodes.start, 1875 - /** @type {TemplateNode} */ 1876 - effect.nodes.end 1877 - ); 1878 - removed = true; 1879 - } 1880 - set_signal_status(effect, DESTROYING); 1881 - destroy_effect_children(effect, remove_dom && !removed); 1882 - remove_reactions(effect, 0); 1883 - var transitions = effect.nodes && effect.nodes.t; 1884 - if (transitions !== null) { 1885 - for (const transition of transitions) { 1886 - transition.stop(); 1887 - } 1888 - } 1889 - execute_effect_teardown(effect); 1890 - effect.f ^= DESTROYING; 1891 - effect.f |= DESTROYED; 1892 - var parent = effect.parent; 1893 - if (parent !== null && parent.first !== null) { 1894 - unlink_effect(effect); 1895 - } 1896 - effect.next = effect.prev = effect.teardown = effect.ctx = effect.deps = effect.fn = effect.nodes = effect.ac = effect.b = null; 1897 - } 1898 - function remove_effect_dom(node, end) { 1899 - while (node !== null) { 1900 - var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); 1901 - node.remove(); 1902 - node = next2; 1903 - } 1904 - } 1905 - function unlink_effect(effect) { 1906 - var parent = effect.parent; 1907 - var prev = effect.prev; 1908 - var next2 = effect.next; 1909 - if (prev !== null) prev.next = next2; 1910 - if (next2 !== null) next2.prev = prev; 1911 - if (parent !== null) { 1912 - if (parent.first === effect) parent.first = next2; 1913 - if (parent.last === effect) parent.last = prev; 1914 - } 1915 - } 1916 - function pause_effect(effect, callback, destroy = true) { 1917 - var transitions = []; 1918 - pause_children(effect, transitions, true); 1919 - var fn = () => { 1920 - if (destroy) destroy_effect(effect); 1921 - if (callback) callback(); 1922 - }; 1923 - var remaining = transitions.length; 1924 - if (remaining > 0) { 1925 - var check = () => --remaining || fn(); 1926 - for (var transition of transitions) { 1927 - transition.out(check); 1928 - } 1929 - } else { 1930 - fn(); 1931 - } 1932 - } 1933 - function pause_children(effect, transitions, local) { 1934 - if ((effect.f & INERT) !== 0) return; 1935 - effect.f ^= INERT; 1936 - var t = effect.nodes && effect.nodes.t; 1937 - if (t !== null) { 1938 - for (const transition of t) { 1939 - if (transition.is_global || local) { 1940 - transitions.push(transition); 1941 - } 1942 - } 1943 - } 1944 - var child = effect.first; 1945 - while (child !== null) { 1946 - var sibling = child.next; 1947 - var transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent, 1948 - // it means the parent block effect was pruned. In that case, 1949 - // transparency information was transferred to the branch effect. 1950 - (child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0; 1951 - pause_children(child, transitions, transparent ? local : false); 1952 - child = sibling; 1953 - } 1954 - } 1955 - function move_effect(effect, fragment) { 1956 - if (!effect.nodes) return; 1957 - var node = effect.nodes.start; 1958 - var end = effect.nodes.end; 1959 - while (node !== null) { 1960 - var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); 1961 - fragment.append(node); 1962 - node = next2; 1963 - } 1964 - } 1965 - let is_updating_effect = false; 1966 - let is_destroying_effect = false; 1967 - function set_is_destroying_effect(value) { 1968 - is_destroying_effect = value; 1969 - } 1970 - let active_reaction = null; 1971 - let untracking = false; 1972 - function set_active_reaction(reaction) { 1973 - active_reaction = reaction; 1974 - } 1975 - let active_effect = null; 1976 - function set_active_effect(effect) { 1977 - active_effect = effect; 1978 - } 1979 - let current_sources = null; 1980 - function push_reaction_value(value) { 1981 - if (active_reaction !== null && true) { 1982 - if (current_sources === null) { 1983 - current_sources = [value]; 1984 - } else { 1985 - current_sources.push(value); 1986 - } 1987 - } 1988 - } 1989 - let new_deps = null; 1990 - let skipped_deps = 0; 1991 - let untracked_writes = null; 1992 - function set_untracked_writes(value) { 1993 - untracked_writes = value; 1994 - } 1995 - let write_version = 1; 1996 - let read_version = 0; 1997 - let update_version = read_version; 1998 - function set_update_version(value) { 1999 - update_version = value; 2000 - } 2001 - function increment_write_version() { 2002 - return ++write_version; 2003 - } 2004 - function is_dirty(reaction) { 2005 - var flags2 = reaction.f; 2006 - if ((flags2 & DIRTY) !== 0) { 2007 - return true; 2008 - } 2009 - if (flags2 & DERIVED) { 2010 - reaction.f &= ~WAS_MARKED; 2011 - } 2012 - if ((flags2 & MAYBE_DIRTY) !== 0) { 2013 - var dependencies = ( 2014 - /** @type {Value[]} */ 2015 - reaction.deps 2016 - ); 2017 - var length = dependencies.length; 2018 - for (var i = 0; i < length; i++) { 2019 - var dependency = dependencies[i]; 2020 - if (is_dirty( 2021 - /** @type {Derived} */ 2022 - dependency 2023 - )) { 2024 - update_derived( 2025 - /** @type {Derived} */ 2026 - dependency 2027 - ); 2028 - } 2029 - if (dependency.wv > reaction.wv) { 2030 - return true; 2031 - } 2032 - } 2033 - if ((flags2 & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that 2034 - // traversal of the graph in the other batches still happens 2035 - batch_values === null) { 2036 - set_signal_status(reaction, CLEAN); 2037 - } 2038 - } 2039 - return false; 2040 - } 2041 - function schedule_possible_effect_self_invalidation(signal, effect, root2 = true) { 2042 - var reactions = signal.reactions; 2043 - if (reactions === null) return; 2044 - if (current_sources !== null && includes.call(current_sources, signal)) { 2045 - return; 2046 - } 2047 - for (var i = 0; i < reactions.length; i++) { 2048 - var reaction = reactions[i]; 2049 - if ((reaction.f & DERIVED) !== 0) { 2050 - schedule_possible_effect_self_invalidation( 2051 - /** @type {Derived} */ 2052 - reaction, 2053 - effect, 2054 - false 2055 - ); 2056 - } else if (effect === reaction) { 2057 - if (root2) { 2058 - set_signal_status(reaction, DIRTY); 2059 - } else if ((reaction.f & CLEAN) !== 0) { 2060 - set_signal_status(reaction, MAYBE_DIRTY); 2061 - } 2062 - schedule_effect( 2063 - /** @type {Effect} */ 2064 - reaction 2065 - ); 2066 - } 2067 - } 2068 - } 2069 - function update_reaction(reaction) { 2070 - var previous_deps = new_deps; 2071 - var previous_skipped_deps = skipped_deps; 2072 - var previous_untracked_writes = untracked_writes; 2073 - var previous_reaction = active_reaction; 2074 - var previous_sources = current_sources; 2075 - var previous_component_context = component_context; 2076 - var previous_untracking = untracking; 2077 - var previous_update_version = update_version; 2078 - var flags2 = reaction.f; 2079 - new_deps = /** @type {null | Value[]} */ 2080 - null; 2081 - skipped_deps = 0; 2082 - untracked_writes = null; 2083 - active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; 2084 - current_sources = null; 2085 - set_component_context(reaction.ctx); 2086 - untracking = false; 2087 - update_version = ++read_version; 2088 - if (reaction.ac !== null) { 2089 - without_reactive_context(() => { 2090 - reaction.ac.abort(STALE_REACTION); 2091 - }); 2092 - reaction.ac = null; 2093 - } 2094 - try { 2095 - reaction.f |= REACTION_IS_UPDATING; 2096 - var fn = ( 2097 - /** @type {Function} */ 2098 - reaction.fn 2099 - ); 2100 - var result = fn(); 2101 - reaction.f |= REACTION_RAN; 2102 - var deps = reaction.deps; 2103 - var is_fork = current_batch?.is_fork; 2104 - if (new_deps !== null) { 2105 - var i; 2106 - if (!is_fork) { 2107 - remove_reactions(reaction, skipped_deps); 2108 - } 2109 - if (deps !== null && skipped_deps > 0) { 2110 - deps.length = skipped_deps + new_deps.length; 2111 - for (i = 0; i < new_deps.length; i++) { 2112 - deps[skipped_deps + i] = new_deps[i]; 2113 - } 2114 - } else { 2115 - reaction.deps = deps = new_deps; 2116 - } 2117 - if (effect_tracking() && (reaction.f & CONNECTED) !== 0) { 2118 - for (i = skipped_deps; i < deps.length; i++) { 2119 - (deps[i].reactions ??= []).push(reaction); 2120 - } 2121 - } 2122 - } else if (!is_fork && deps !== null && skipped_deps < deps.length) { 2123 - remove_reactions(reaction, skipped_deps); 2124 - deps.length = skipped_deps; 2125 - } 2126 - if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) { 2127 - for (i = 0; i < /** @type {Source[]} */ 2128 - untracked_writes.length; i++) { 2129 - schedule_possible_effect_self_invalidation( 2130 - untracked_writes[i], 2131 - /** @type {Effect} */ 2132 - reaction 2133 - ); 2134 - } 2135 - } 2136 - if (previous_reaction !== null && previous_reaction !== reaction) { 2137 - read_version++; 2138 - if (previous_reaction.deps !== null) { 2139 - for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) { 2140 - previous_reaction.deps[i2].rv = read_version; 2141 - } 2142 - } 2143 - if (previous_deps !== null) { 2144 - for (const dep of previous_deps) { 2145 - dep.rv = read_version; 2146 - } 2147 - } 2148 - if (untracked_writes !== null) { 2149 - if (previous_untracked_writes === null) { 2150 - previous_untracked_writes = untracked_writes; 2151 - } else { 2152 - previous_untracked_writes.push(.../** @type {Source[]} */ 2153 - untracked_writes); 2154 - } 2155 - } 2156 - } 2157 - if ((reaction.f & ERROR_VALUE) !== 0) { 2158 - reaction.f ^= ERROR_VALUE; 2159 - } 2160 - return result; 2161 - } catch (error) { 2162 - return handle_error(error); 2163 - } finally { 2164 - reaction.f ^= REACTION_IS_UPDATING; 2165 - new_deps = previous_deps; 2166 - skipped_deps = previous_skipped_deps; 2167 - untracked_writes = previous_untracked_writes; 2168 - active_reaction = previous_reaction; 2169 - current_sources = previous_sources; 2170 - set_component_context(previous_component_context); 2171 - untracking = previous_untracking; 2172 - update_version = previous_update_version; 2173 - } 2174 - } 2175 - function remove_reaction(signal, dependency) { 2176 - let reactions = dependency.reactions; 2177 - if (reactions !== null) { 2178 - var index = index_of.call(reactions, signal); 2179 - if (index !== -1) { 2180 - var new_length = reactions.length - 1; 2181 - if (new_length === 0) { 2182 - reactions = dependency.reactions = null; 2183 - } else { 2184 - reactions[index] = reactions[new_length]; 2185 - reactions.pop(); 2186 - } 2187 - } 2188 - } 2189 - if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear 2190 - // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` 2191 - // allows us to skip the expensive work of disconnecting and immediately reconnecting it 2192 - (new_deps === null || !includes.call(new_deps, dependency))) { 2193 - var derived2 = ( 2194 - /** @type {Derived} */ 2195 - dependency 2196 - ); 2197 - if ((derived2.f & CONNECTED) !== 0) { 2198 - derived2.f ^= CONNECTED; 2199 - derived2.f &= ~WAS_MARKED; 2200 - } 2201 - update_derived_status(derived2); 2202 - freeze_derived_effects(derived2); 2203 - remove_reactions(derived2, 0); 2204 - } 2205 - } 2206 - function remove_reactions(signal, start_index) { 2207 - var dependencies = signal.deps; 2208 - if (dependencies === null) return; 2209 - for (var i = start_index; i < dependencies.length; i++) { 2210 - remove_reaction(signal, dependencies[i]); 2211 - } 2212 - } 2213 - function update_effect(effect) { 2214 - var flags2 = effect.f; 2215 - if ((flags2 & DESTROYED) !== 0) { 2216 - return; 2217 - } 2218 - set_signal_status(effect, CLEAN); 2219 - var previous_effect = active_effect; 2220 - var was_updating_effect = is_updating_effect; 2221 - active_effect = effect; 2222 - is_updating_effect = true; 2223 - try { 2224 - if ((flags2 & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) { 2225 - destroy_block_effect_children(effect); 2226 - } else { 2227 - destroy_effect_children(effect); 2228 - } 2229 - execute_effect_teardown(effect); 2230 - var teardown = update_reaction(effect); 2231 - effect.teardown = typeof teardown === "function" ? teardown : null; 2232 - effect.wv = write_version; 2233 - var dep; 2234 - if (BROWSER && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) ; 2235 - } finally { 2236 - is_updating_effect = was_updating_effect; 2237 - active_effect = previous_effect; 2238 - } 2239 - } 2240 - function get(signal) { 2241 - var flags2 = signal.f; 2242 - var is_derived = (flags2 & DERIVED) !== 0; 2243 - if (active_reaction !== null && !untracking) { 2244 - var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0; 2245 - if (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) { 2246 - var deps = active_reaction.deps; 2247 - if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) { 2248 - if (signal.rv < read_version) { 2249 - signal.rv = read_version; 2250 - if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { 2251 - skipped_deps++; 2252 - } else if (new_deps === null) { 2253 - new_deps = [signal]; 2254 - } else { 2255 - new_deps.push(signal); 2256 - } 2257 - } 2258 - } else { 2259 - (active_reaction.deps ??= []).push(signal); 2260 - var reactions = signal.reactions; 2261 - if (reactions === null) { 2262 - signal.reactions = [active_reaction]; 2263 - } else if (!includes.call(reactions, active_reaction)) { 2264 - reactions.push(active_reaction); 2265 - } 2266 - } 2267 - } 2268 - } 2269 - if (is_destroying_effect && old_values.has(signal)) { 2270 - return old_values.get(signal); 2271 - } 2272 - if (is_derived) { 2273 - var derived2 = ( 2274 - /** @type {Derived} */ 2275 - signal 2276 - ); 2277 - if (is_destroying_effect) { 2278 - var value = derived2.v; 2279 - if ((derived2.f & CLEAN) === 0 && derived2.reactions !== null || depends_on_old_values(derived2)) { 2280 - value = execute_derived(derived2); 2281 - } 2282 - old_values.set(derived2, value); 2283 - return value; 2284 - } 2285 - var should_connect = (derived2.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0); 2286 - var is_new = (derived2.f & REACTION_RAN) === 0; 2287 - if (is_dirty(derived2)) { 2288 - if (should_connect) { 2289 - derived2.f |= CONNECTED; 2290 - } 2291 - update_derived(derived2); 2292 - } 2293 - if (should_connect && !is_new) { 2294 - unfreeze_derived_effects(derived2); 2295 - reconnect(derived2); 2296 - } 2297 - } 2298 - if (batch_values?.has(signal)) { 2299 - return batch_values.get(signal); 2300 - } 2301 - if ((signal.f & ERROR_VALUE) !== 0) { 2302 - throw signal.v; 2303 - } 2304 - return signal.v; 2305 - } 2306 - function reconnect(derived2) { 2307 - derived2.f |= CONNECTED; 2308 - if (derived2.deps === null) return; 2309 - for (const dep of derived2.deps) { 2310 - (dep.reactions ??= []).push(derived2); 2311 - if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) { 2312 - unfreeze_derived_effects( 2313 - /** @type {Derived} */ 2314 - dep 2315 - ); 2316 - reconnect( 2317 - /** @type {Derived} */ 2318 - dep 2319 - ); 2320 - } 2321 - } 2322 - } 2323 - function depends_on_old_values(derived2) { 2324 - if (derived2.v === UNINITIALIZED) return true; 2325 - if (derived2.deps === null) return false; 2326 - for (const dep of derived2.deps) { 2327 - if (old_values.has(dep)) { 2328 - return true; 2329 - } 2330 - if ((dep.f & DERIVED) !== 0 && depends_on_old_values( 2331 - /** @type {Derived} */ 2332 - dep 2333 - )) { 2334 - return true; 2335 - } 2336 - } 2337 - return false; 2338 - } 2339 - function untrack(fn) { 2340 - var previous_untracking = untracking; 2341 - try { 2342 - untracking = true; 2343 - return fn(); 2344 - } finally { 2345 - untracking = previous_untracking; 2346 - } 2347 - } 2348 468 const event_symbol = /* @__PURE__ */ Symbol("events"); 2349 469 const all_registered_events = /* @__PURE__ */ new Set(); 2350 470 const root_event_handles = /* @__PURE__ */ new Set(); ··· 2452 572 const was_hydrating = hydrating; 2453 573 const previous_hydrate_node = hydrate_node; 2454 574 try { 2455 - var anchor = /* @__PURE__ */ get_first_child(target); 575 + var anchor = get_first_child(target); 2456 576 while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ 2457 577 anchor.data !== HYDRATION_START)) { 2458 - anchor = /* @__PURE__ */ get_next_sibling(anchor); 578 + anchor = get_next_sibling(anchor); 2459 579 } 2460 580 if (!anchor) { 2461 581 throw HYDRATION_ERROR; ··· 2622 742 constructor(options) { 2623 743 var sources = /* @__PURE__ */ new Map(); 2624 744 var add_source = (key, value) => { 2625 - var s = /* @__PURE__ */ mutable_source(value, false, false); 745 + var s = mutable_source(value, false, false); 2626 746 sources.set(key, s); 2627 747 return s; 2628 748 }; ··· 2810 930 } 2811 931 const root = asClassComponent(Root); 2812 932 export { 2813 - root as r, 2814 - safe_not_equal as s 933 + root as r 2815 934 };
+19
.svelte-kit/output/server/chunks/state.svelte.js
··· 1 + import "clsx"; 2 + import { n as noop } from "./index2.js"; 3 + import "./exports.js"; 4 + import "@sveltejs/kit/internal/server"; 5 + import "./root.js"; 6 + const is_legacy = noop.toString().includes("$$") || /function \w+\(\) \{\}/.test(noop.toString()); 7 + const placeholder_url = "a:"; 8 + if (is_legacy) { 9 + ({ 10 + data: {}, 11 + form: null, 12 + error: null, 13 + params: {}, 14 + route: { id: null }, 15 + state: {}, 16 + status: -1, 17 + url: new URL(placeholder_url) 18 + }); 19 + }
+6 -18
.svelte-kit/output/server/entries/fallbacks/error.svelte.js
··· 1 - import { n as noop, g as getContext, e as escape_html } from "../../chunks/index.js"; 1 + import { g as getContext, e as escape_html } from "../../chunks/index2.js"; 2 2 import "clsx"; 3 - import { w as writable } from "../../chunks/exports.js"; 4 - import "@sveltejs/kit/internal/server"; 5 - import "../../chunks/root.js"; 3 + import "../../chunks/state.svelte.js"; 6 4 import "@sveltejs/kit/internal"; 5 + import "../../chunks/exports.js"; 7 6 import "../../chunks/utils.js"; 7 + import { w as writable } from "../../chunks/index.js"; 8 + import "@sveltejs/kit/internal/server"; 9 + import "../../chunks/root.js"; 8 10 function create_updated_store() { 9 11 const { set, subscribe } = writable(false); 10 12 { ··· 14 16 check: async () => false 15 17 }; 16 18 } 17 - } 18 - const is_legacy = noop.toString().includes("$$") || /function \w+\(\) \{\}/.test(noop.toString()); 19 - const placeholder_url = "a:"; 20 - if (is_legacy) { 21 - ({ 22 - data: {}, 23 - form: null, 24 - error: null, 25 - params: {}, 26 - route: { id: null }, 27 - state: {}, 28 - status: -1, 29 - url: new URL(placeholder_url) 30 - }); 31 19 } 32 20 const stores = { 33 21 updated: /* @__PURE__ */ create_updated_store()
+5 -16
.svelte-kit/output/server/entries/pages/_layout.svelte.js
··· 1 - import { a as attr_class, s as stringify, h as head } from "../../chunks/index.js"; 1 + import { h as head } from "../../chunks/index2.js"; 2 2 import "clsx"; 3 3 function MeshBackground($$renderer) { 4 4 $$renderer.push(`<div class="mesh-bg svelte-17k46oa"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" preserveAspectRatio="none" class="mesh-svg svelte-17k46oa"><defs><radialGradient id="g1" cx="50%" cy="40%" r="70%"><stop offset="0%" stop-color="#39FF44"></stop><stop offset="60%" stop-color="#2BBF33"></stop><stop offset="100%" stop-color="#1A8C22"></stop></radialGradient><radialGradient id="g2" cx="90%" cy="5%" r="45%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.9"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.4"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g3" cx="5%" cy="95%" r="40%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.7"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g4" cx="15%" cy="10%" r="50%"><stop offset="0%" stop-color="#5FFF66" stop-opacity="0.6"></stop><stop offset="100%" stop-color="#39FF44" stop-opacity="0"></stop></radialGradient><radialGradient id="g5" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#4AFF54" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#2BBF33" stop-opacity="0"></stop></radialGradient></defs><rect width="1000" height="1000" fill="url(#g1)"></rect><rect width="1000" height="1000" fill="url(#g2)"></rect><rect width="1000" height="1000" fill="url(#g3)"></rect><rect width="1000" height="1000" fill="url(#g4)"></rect><rect width="1000" height="1000" fill="url(#g5)"></rect></svg></div>`); 5 5 } 6 - function PlantOverlay($$renderer, $$props) { 7 - let { side } = $$props; 8 - $$renderer.push(`<div${attr_class(`plant-overlay ${stringify(side)}`, "svelte-11afcec")}><svg viewBox="0 0 160 900" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" class="svelte-11afcec">`); 9 - if (side === "left") { 10 - $$renderer.push("<!--[0-->"); 11 - $$renderer.push(`<path d="M 50 900 Q 55 780 42 660 Q 35 540 48 420 Q 55 300 40 180 Q 30 80 50 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="42" cy="140" rx="40" ry="14" fill="#0A182B" transform="rotate(-35 42 140)"></ellipse><ellipse cx="48" cy="290" rx="44" ry="15" fill="#0A182B" transform="rotate(25 48 290)"></ellipse><ellipse cx="38" cy="440" rx="38" ry="13" fill="#0A182B" transform="rotate(-30 38 440)"></ellipse><ellipse cx="52" cy="570" rx="42" ry="14" fill="#0A182B" transform="rotate(20 52 570)"></ellipse><ellipse cx="44" cy="710" rx="40" ry="14" fill="#0A182B" transform="rotate(-22 44 710)"></ellipse><ellipse cx="48" cy="830" rx="36" ry="12" fill="#0A182B" transform="rotate(18 48 830)"></ellipse><ellipse cx="55" cy="210" rx="28" ry="10" fill="#0A182B" transform="rotate(40 55 210)"></ellipse><ellipse cx="50" cy="370" rx="24" ry="9" fill="#0A182B" transform="rotate(35 50 370)"></ellipse><ellipse cx="45" cy="510" rx="30" ry="11" fill="#0A182B" transform="rotate(-28 45 510)"></ellipse><ellipse cx="52" cy="650" rx="26" ry="9" fill="#0A182B" transform="rotate(30 52 650)"></ellipse><ellipse cx="40" cy="780" rx="22" ry="8" fill="#0A182B" transform="rotate(-25 40 780)"></ellipse>`); 12 - } else { 13 - $$renderer.push("<!--[-1-->"); 14 - $$renderer.push(`<path d="M 110 900 Q 105 780 118 660 Q 125 540 112 420 Q 105 300 120 180 Q 130 80 110 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="118" cy="170" rx="40" ry="14" fill="#0A182B" transform="rotate(35 118 170)"></ellipse><ellipse cx="112" cy="320" rx="44" ry="15" fill="#0A182B" transform="rotate(-25 112 320)"></ellipse><ellipse cx="122" cy="470" rx="38" ry="13" fill="#0A182B" transform="rotate(30 122 470)"></ellipse><ellipse cx="108" cy="610" rx="42" ry="14" fill="#0A182B" transform="rotate(-20 108 610)"></ellipse><ellipse cx="116" cy="750" rx="40" ry="14" fill="#0A182B" transform="rotate(22 116 750)"></ellipse><ellipse cx="112" cy="860" rx="36" ry="12" fill="#0A182B" transform="rotate(-18 112 860)"></ellipse><ellipse cx="105" cy="240" rx="28" ry="10" fill="#0A182B" transform="rotate(-40 105 240)"></ellipse><ellipse cx="110" cy="400" rx="24" ry="9" fill="#0A182B" transform="rotate(-35 110 400)"></ellipse><ellipse cx="115" cy="540" rx="30" ry="11" fill="#0A182B" transform="rotate(28 115 540)"></ellipse><ellipse cx="108" cy="680" rx="26" ry="9" fill="#0A182B" transform="rotate(-30 108 680)"></ellipse>`); 15 - } 16 - $$renderer.push(`<!--]--></svg></div>`); 6 + function PlantOverlay($$renderer) { 7 + $$renderer.push(`<div class="plant-overlay svelte-11afcec"><img src="/leaves.png" alt="" class="leaves svelte-11afcec"/></div>`); 17 8 } 18 9 function _layout($$renderer, $$props) { 19 10 let { children } = $$props; 20 11 head("12qhfyh", $$renderer, ($$renderer2) => { 21 - $$renderer2.push(`<link rel="icon" href="/frogcursor.png"/> `); 12 + $$renderer2.push(`<link rel="icon" href="/frogicon.png"/> <link rel="preconnect" href="https://fonts.googleapis.com"/> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"/> <link href="https://fonts.googleapis.com/css2?family=Shrikhand&amp;family=Nunito:wght@400;700&amp;display=swap" rel="stylesheet"/> `); 22 13 $$renderer2.push(`<style> 23 14 /* Cursor must be in global head style to override everything */ 24 15 *, *::before, *::after { ··· 31 22 }); 32 23 MeshBackground($$renderer); 33 24 $$renderer.push(`<!----> `); 34 - PlantOverlay($$renderer, { side: "left" }); 35 - $$renderer.push(`<!----> `); 36 - PlantOverlay($$renderer, { side: "right" }); 25 + PlantOverlay($$renderer); 37 26 $$renderer.push(`<!----> `); 38 27 children($$renderer); 39 28 $$renderer.push(`<!---->`);
+129 -55
.svelte-kit/output/server/entries/pages/_page.svelte.js
··· 1 - import { a3 as ssr_context, a4 as attr_style, a5 as attr, s as stringify, e as escape_html, a as attr_class, h as head, a6 as ensure_array_like } from "../../chunks/index.js"; 1 + import { a as ssr_context, b as attr_style, c as attr, d as stringify, f as attr_class, e as escape_html, h as head, i as ensure_array_like } from "../../chunks/index2.js"; 2 2 import "hls.js"; 3 + import { F as FrogHeader } from "../../chunks/FrogHeader.js"; 3 4 import "clsx"; 4 5 function onDestroy(fn) { 5 6 /** @type {SSRContext} */ 6 7 ssr_context.r.on_destroy(fn); 8 + } 9 + const PLAYBACK_BASE = "https://vod-beta.stream.place/xrpc/place.stream.playback.getVideoPlaylist"; 10 + function getPlaylistUrl(uri) { 11 + return `${PLAYBACK_BASE}?uri=${encodeURIComponent(uri)}`; 7 12 } 8 13 function formatDuration(nanos) { 9 14 const totalSeconds = Math.floor(nanos / 1e9); ··· 38 43 const r2 = seededRandom(seed, 1); 39 44 const r3 = seededRandom(seed, 2); 40 45 return { 41 - rotation: (r1 - 0.5) * 4, 42 - // -2 to +2 degrees 46 + rotation: (r1 - 0.5) * 6, 47 + // -3 to +3 degrees 43 48 translateX: (r2 - 0.5) * 12, 44 49 // -6 to +6 px 45 - translateY: (r3 - 0.5) * 8 46 - // -4 to +4 px 50 + translateY: (r3 - 0.5) * 60 51 + // -30 to +30 px 47 52 }; 48 53 } 49 54 function WavyBorder($$renderer, $$props) { ··· 53 58 fill = "#39FF44", 54 59 strokeColor = "#0A182B", 55 60 strokeWidth = 3, 56 - padding = 16, 61 + padding = "16px", 57 62 children 58 63 } = $$props; 59 - const svgPath = generateBlobPath(seed); 60 - const filterId = `turb-${seed.replace(/[^a-zA-Z0-9]/g, "").slice(0, 12)}`; 61 - const turbSeed = Math.floor(seededRandom(seed, 99) * 999); 62 - function generateBlobPath(s) { 63 - const margin = 6; 64 - const amp = 5; 65 - const segs = 10; 66 - const pts = []; 64 + const paddingValue = typeof padding === "number" ? `${padding}px` : padding; 65 + const { pts, svgPath } = generateWavyShape(seed); 66 + const clipPolygon = `polygon(${pts.map(([x, y]) => `${x.toFixed(2)}% ${y.toFixed(2)}%`).join(", ")})`; 67 + function generateWavyShape(s) { 68 + const margin = 1; 69 + const amp = 2.5; 70 + const segs = 16; 71 + const edgeParams = [0, 1, 2, 3].map((e) => ({ 72 + phase1: seededRandom(s, e * 10 + 1) * Math.PI * 2, 73 + phase2: seededRandom(s, e * 10 + 2) * Math.PI * 2, 74 + freq1: 1.5 + seededRandom(s, e * 10 + 3) * 1.5, 75 + freq2: 3 + seededRandom(s, e * 10 + 4) * 2, 76 + ampScale: 0.7 + seededRandom(s, e * 10 + 5) * 0.6 77 + })); 78 + function wobble(edgeIdx, t) { 79 + const p = edgeParams[edgeIdx]; 80 + const w1 = Math.sin(t * p.freq1 * Math.PI * 2 + p.phase1) * amp * 0.7; 81 + const w2 = Math.sin(t * p.freq2 * Math.PI * 2 + p.phase2) * amp * 0.3; 82 + return (w1 + w2) * p.ampScale; 83 + } 84 + const points = []; 67 85 for (let i = 0; i <= segs; i++) { 68 86 const t = i / segs; 69 - const r = seededRandom(s, i); 70 - pts.push([ 71 - margin + t * (100 - 2 * margin), 72 - margin + (r - 0.5) * amp * 2 73 - ]); 87 + points.push([margin + t * (100 - 2 * margin), margin + wobble(0, t)]); 74 88 } 75 89 for (let i = 1; i <= segs; i++) { 76 90 const t = i / segs; 77 - const r = seededRandom(s, segs + i + 50); 78 - pts.push([ 79 - 100 - margin + (r - 0.5) * amp * 2, 80 - margin + t * (100 - 2 * margin) 81 - ]); 91 + points.push([100 - margin + wobble(1, t), margin + t * (100 - 2 * margin)]); 82 92 } 83 93 for (let i = 1; i <= segs; i++) { 84 94 const t = i / segs; 85 - const r = seededRandom(s, segs * 2 + i + 100); 86 - pts.push([ 95 + points.push([ 87 96 100 - margin - t * (100 - 2 * margin), 88 - 100 - margin + (r - 0.5) * amp * 2 97 + 100 - margin + wobble(2, t) 89 98 ]); 90 99 } 91 100 for (let i = 1; i < segs; i++) { 92 101 const t = i / segs; 93 - const r = seededRandom(s, segs * 3 + i + 150); 94 - pts.push([ 95 - margin + (r - 0.5) * amp * 2, 96 - 100 - margin - t * (100 - 2 * margin) 97 - ]); 102 + points.push([margin + wobble(3, t), 100 - margin - t * (100 - 2 * margin)]); 98 103 } 99 - if (pts.length < 3) return ""; 100 - let d = `M ${pts[0][0]} ${pts[0][1]}`; 101 - for (let i = 0; i < pts.length; i++) { 102 - const p0 = pts[(i - 1 + pts.length) % pts.length]; 103 - const p1 = pts[i]; 104 - const p2 = pts[(i + 1) % pts.length]; 105 - const p3 = pts[(i + 2) % pts.length]; 106 - const tension = 0.35; 104 + let d = `M ${points[0][0].toFixed(1)} ${points[0][1].toFixed(1)}`; 105 + for (let i = 0; i < points.length; i++) { 106 + const p0 = points[(i - 1 + points.length) % points.length]; 107 + const p1 = points[i]; 108 + const p2 = points[(i + 1) % points.length]; 109 + const p3 = points[(i + 2) % points.length]; 110 + const tension = 0.3; 107 111 const cp1x = p1[0] + (p2[0] - p0[0]) * tension; 108 112 const cp1y = p1[1] + (p2[1] - p0[1]) * tension; 109 113 const cp2x = p2[0] - (p3[0] - p1[0]) * tension; ··· 111 115 d += ` C ${cp1x.toFixed(1)} ${cp1y.toFixed(1)}, ${cp2x.toFixed(1)} ${cp2y.toFixed(1)}, ${p2[0].toFixed(1)} ${p2[1].toFixed(1)}`; 112 116 } 113 117 d += " Z"; 114 - return d; 118 + const sampledPts = []; 119 + const totalPts = points.length; 120 + const samplesPerSegment = 10; 121 + for (let i = 0; i < totalPts; i++) { 122 + const p0 = points[(i - 1 + totalPts) % totalPts]; 123 + const p1 = points[i]; 124 + const p2 = points[(i + 1) % totalPts]; 125 + const p3 = points[(i + 2) % totalPts]; 126 + const tension = 0.3; 127 + const cp1x = p1[0] + (p2[0] - p0[0]) * tension; 128 + const cp1y = p1[1] + (p2[1] - p0[1]) * tension; 129 + const cp2x = p2[0] - (p3[0] - p1[0]) * tension; 130 + const cp2y = p2[1] - (p3[1] - p1[1]) * tension; 131 + for (let j = 0; j < samplesPerSegment; j++) { 132 + const t = j / samplesPerSegment; 133 + const mt = 1 - t; 134 + const x = mt * mt * mt * p1[0] + 3 * mt * mt * t * cp1x + 3 * mt * t * t * cp2x + t * t * t * p2[0]; 135 + const y = mt * mt * mt * p1[1] + 3 * mt * mt * t * cp1y + 3 * mt * t * t * cp2y + t * t * t * p2[1]; 136 + sampledPts.push([x, y]); 137 + } 138 + } 139 + return { pts: sampledPts, svgPath: d }; 115 140 } 116 - $$renderer2.push(`<div class="wavy-container svelte-7frlgw"${attr_style(`--padding: ${stringify(padding)}px;`)}><svg class="wavy-svg svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg"><defs><filter${attr("id", filterId)} x="-5%" y="-5%" width="110%" height="110%"><feTurbulence type="turbulence" baseFrequency="0.03" numOctaves="4"${attr("seed", turbSeed)} result="turb"></feTurbulence><feDisplacementMap in="SourceGraphic" in2="turb" scale="3" xChannelSelector="R" yChannelSelector="G"></feDisplacementMap></filter></defs><path${attr("d", svgPath)}${attr("fill", fill)}${attr("stroke", strokeColor)}${attr("stroke-width", strokeWidth)} stroke-linejoin="round"${attr("filter", `url(#${stringify(filterId)})`)}></path></svg> <div class="wavy-content svelte-7frlgw">`); 141 + $$renderer2.push(`<div class="wavy-container svelte-7frlgw"${attr_style(`--padding: ${stringify(paddingValue)};`)}><div class="wavy-clipped svelte-7frlgw"${attr_style(`clip-path: ${stringify(clipPolygon)};`)}><div class="wavy-fill svelte-7frlgw"${attr_style(`background: ${stringify(fill)};`)}></div> <div class="wavy-content svelte-7frlgw">`); 117 142 children($$renderer2); 118 - $$renderer2.push(`<!----></div></div>`); 143 + $$renderer2.push(`<!----></div></div> <svg class="wavy-stroke svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" overflow="visible"><path${attr("d", svgPath)} fill="none"${attr("stroke", strokeColor)}${attr("stroke-width", strokeWidth)} stroke-linejoin="round" stroke-linecap="round"></path></svg></div>`); 144 + }); 145 + } 146 + function VideoPlayer($$renderer, $$props) { 147 + $$renderer.component(($$renderer2) => { 148 + let currentTime = 0; 149 + let duration = 0; 150 + let scrubProgress = 0; 151 + let frogFlipped = false; 152 + let showControls = true; 153 + WavyBorder($$renderer2, { 154 + seed: "player-main", 155 + padding: 4, 156 + children: ($$renderer3) => { 157 + $$renderer3.push(`<div class="player-wrapper svelte-zbxgh1" role="region"><video playsinline="" class="svelte-zbxgh1"><track kind="captions"/></video> <div${attr_class("controls svelte-zbxgh1", void 0, { "visible": showControls })}><div class="scrub-bar svelte-zbxgh1" role="slider"${attr("aria-valuenow", currentTime)}${attr("aria-valuemin", 0)}${attr("aria-valuemax", duration)}${attr("tabindex", 0)}><div${attr_class("scrub-frog svelte-zbxgh1", void 0, { "flipped": frogFlipped })}${attr_style(`left: ${stringify(scrubProgress * 100)}%;`)}><img${attr("src", "/froggiestand.png")} alt="scrub" class="frog-sprite svelte-zbxgh1" draggable="false"/></div></div></div> <button${attr_class("fullscreen-btn svelte-zbxgh1", void 0, { "visible": showControls })}${attr("title", "Fullscreen")}><img src="/frogeye.png" alt="fullscreen" class="frogeye svelte-zbxgh1"/></button> `); 158 + { 159 + $$renderer3.push("<!--[-1-->"); 160 + } 161 + $$renderer3.push(`<!--]--></div>`); 162 + } 163 + }); 119 164 }); 120 165 } 121 166 function VideoCard($$renderer, $$props) { ··· 134 179 seed: rkey, 135 180 fill: "#39FF44", 136 181 strokeColor: "#0A182B", 137 - strokeWidth: 3.5, 138 - padding: 20, 182 + strokeWidth: 2.2, 183 + padding: "clamp(24px, 4vw, 36px)", 139 184 children: ($$renderer3) => { 140 185 $$renderer3.push(`<span class="duration-badge svelte-1nxalmg">${escape_html(formatDuration(video.value.duration))}</span> <div class="thumb-wrapper svelte-1nxalmg">`); 141 186 WavyBorder($$renderer3, { 142 187 seed: rkey + "-thumb", 143 188 fill: "#3992FF", 144 189 strokeColor: "#0A182B", 145 - strokeWidth: 2, 190 + strokeWidth: 1.5, 146 191 padding: 0, 147 192 children: ($$renderer4) => { 148 193 $$renderer4.push(`<div class="thumbnail svelte-1nxalmg" role="img">`); ··· 157 202 { 158 203 $$renderer4.push("<!--[-1-->"); 159 204 } 205 + $$renderer4.push(`<!--]--> `); 206 + { 207 + $$renderer4.push("<!--[-1-->"); 208 + } 160 209 $$renderer4.push(`<!--]--> <div class="thumb-shadow svelte-1nxalmg"></div></div>`); 161 210 }, 162 211 $$slots: { default: true } ··· 166 215 }); 167 216 $$renderer2.push(`<!----></button>`); 168 217 }); 169 - } 170 - function FrogHeader($$renderer) { 171 - $$renderer.push(`<header class="frog-header svelte-1kxia9k"><div class="title-row svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1> <img src="/frogcursor.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k">@goose.art using @stream.place</p></div></header>`); 172 218 } 173 219 function _page($$renderer, $$props) { 174 220 $$renderer.component(($$renderer2) => { 175 221 let videos = []; 176 222 let loading = false; 223 + let selectedVideo = null; 224 + let pageIndex = 0; 225 + function closePlayer() { 226 + selectedVideo = null; 227 + const url = new URL(window.location.href); 228 + url.searchParams.delete("v"); 229 + window.history.pushState({}, "", url.toString()); 230 + } 177 231 head("1uha8ag", $$renderer2, ($$renderer3) => { 178 232 $$renderer3.title(($$renderer4) => { 179 - $$renderer4.push(`<title>vod frog 🐸</title>`); 233 + $$renderer4.push(`<title>vod frog</title>`); 180 234 }); 181 235 }); 182 236 $$renderer2.push(`<div class="app svelte-1uha8ag">`); 183 - FrogHeader($$renderer2); 237 + FrogHeader($$renderer2, { onHomeClick: closePlayer }); 184 238 $$renderer2.push(`<!----> `); 185 - { 239 + if (selectedVideo) { 240 + $$renderer2.push("<!--[0-->"); 241 + $$renderer2.push(`<section class="player-section svelte-1uha8ag">`); 242 + VideoPlayer($$renderer2, { src: getPlaylistUrl(selectedVideo.uri) }); 243 + $$renderer2.push(`<!----> <div class="player-info svelte-1uha8ag">`); 244 + WavyBorder($$renderer2, { 245 + seed: "player-info", 246 + fill: "#39FF44", 247 + strokeColor: "#0A182B", 248 + strokeWidth: 1.8, 249 + padding: 48, 250 + children: ($$renderer3) => { 251 + $$renderer3.push(`<h2 class="player-title svelte-1uha8ag">${escape_html(selectedVideo.value.title)}</h2> <p class="player-meta svelte-1uha8ag"><span class="creator-tag svelte-1uha8ag">${escape_html(selectedVideo.value.creator)}</span> <span class="dot svelte-1uha8ag">·</span> ${escape_html(formatDate(selectedVideo.value.createdAt))} <span class="dot svelte-1uha8ag">·</span> ${escape_html(formatDuration(selectedVideo.value.duration))}</p>`); 252 + } 253 + }); 254 + $$renderer2.push(`<!----></div></section>`); 255 + } else { 186 256 $$renderer2.push("<!--[-1-->"); 187 257 } 188 258 $$renderer2.push(`<!--]--> `); ··· 195 265 let video = each_array[$$index]; 196 266 VideoCard($$renderer2, { video }); 197 267 } 198 - $$renderer2.push(`<!--]--></section> `); 268 + $$renderer2.push(`<!--]--></section> <div class="pagination svelte-1uha8ag">`); 269 + { 270 + $$renderer2.push("<!--[-1-->"); 271 + } 272 + $$renderer2.push(`<!--]--> <span class="page-num svelte-1uha8ag">page ${escape_html(pageIndex + 1)}</span> `); 199 273 { 200 274 $$renderer2.push("<!--[0-->"); 201 - $$renderer2.push(`<div class="load-more svelte-1uha8ag"><button${attr("disabled", loading, true)} class="svelte-1uha8ag">${escape_html("load more 🐸")}</button></div>`); 275 + $$renderer2.push(`<button class="page-btn svelte-1uha8ag"${attr("disabled", loading, true)}>next →</button>`); 202 276 } 203 - $$renderer2.push(`<!--]--></div>`); 277 + $$renderer2.push(`<!--]--></div></div>`); 204 278 }); 205 279 } 206 280 export {
+53
.svelte-kit/output/server/entries/pages/profile/_handle_/_page.svelte.js
··· 1 + import { g as getContext, h as head, e as escape_html, u as unsubscribe_stores, j as derived, k as store_get } from "../../../../chunks/index2.js"; 2 + import "clsx"; 3 + import "@sveltejs/kit/internal"; 4 + import "../../../../chunks/exports.js"; 5 + import "../../../../chunks/utils.js"; 6 + import "@sveltejs/kit/internal/server"; 7 + import "../../../../chunks/root.js"; 8 + import "../../../../chunks/state.svelte.js"; 9 + import { F as FrogHeader } from "../../../../chunks/FrogHeader.js"; 10 + const getStores = () => { 11 + const stores$1 = getContext("__svelte__"); 12 + return { 13 + /** @type {typeof page} */ 14 + page: { 15 + subscribe: stores$1.page.subscribe 16 + }, 17 + /** @type {typeof navigating} */ 18 + navigating: { 19 + subscribe: stores$1.navigating.subscribe 20 + }, 21 + /** @type {typeof updated} */ 22 + updated: stores$1.updated 23 + }; 24 + }; 25 + const page = { 26 + subscribe(fn) { 27 + const store = getStores().page; 28 + return store.subscribe(fn); 29 + } 30 + }; 31 + function _page($$renderer, $$props) { 32 + $$renderer.component(($$renderer2) => { 33 + var $$store_subs; 34 + let handle = derived(() => store_get($$store_subs ??= {}, "$page", page).params.handle); 35 + head("oxml5t", $$renderer2, ($$renderer3) => { 36 + $$renderer3.title(($$renderer4) => { 37 + $$renderer4.push(`<title>${escape_html(handle())} — vod frog 🐸</title>`); 38 + }); 39 + }); 40 + $$renderer2.push(`<div class="profile-page svelte-oxml5t">`); 41 + FrogHeader($$renderer2, {}); 42 + $$renderer2.push(`<!----> `); 43 + { 44 + $$renderer2.push("<!--[0-->"); 45 + $$renderer2.push(`<div class="loading svelte-oxml5t"><img src="/froggiejump.png" alt="loading" class="loading-frog svelte-oxml5t"/> <p class="loading-text svelte-oxml5t">hopping over to fetch profile...</p></div>`); 46 + } 47 + $$renderer2.push(`<!--]--> <div class="back-link svelte-oxml5t"><a href="/" class="svelte-oxml5t">← back to vods</a></div></div>`); 48 + if ($$store_subs) unsubscribe_stores($$store_subs); 49 + }); 50 + } 51 + export { 52 + _page as default 53 + };
+6
.svelte-kit/output/server/entries/pages/profile/_handle_/_page.ts.js
··· 1 + const prerender = false; 2 + const ssr = false; 3 + export { 4 + prerender, 5 + ssr 6 + };
+2 -1
.svelte-kit/output/server/index.js
··· 5 5 import { a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js"; 6 6 import { E as ENDPOINT_METHODS, P as PAGE_METHODS, n as negotiate, m as method_not_allowed, h as handle_error_and_jsonify, g as get_status, i as is_form_content_type, a as normalize_error, b as get_global_name, s as serialize_uses, c as clarify_devalue_error, d as get_node_type, e as escape_html, S as SVELTE_KIT_ASSETS, f as create_remote_key, j as static_error_page, r as redirect_response, p as parse_remote_arg, k as stringify, l as deserialize_binary_form, o as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, q as handle_fatal_error, M as MUTATIVE_METHODS, t as format_server_error } from "./chunks/shared.js"; 7 7 import * as devalue from "devalue"; 8 - import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, w as writable, r as readable, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, f as resolve, g as decode_pathname, h as validate_server_exports } from "./chunks/exports.js"; 8 + import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, r as resolve, f as decode_pathname, g as validate_server_exports } from "./chunks/exports.js"; 9 9 import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js"; 10 + import { w as writable, r as readable } from "./chunks/index.js"; 10 11 import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js"; 11 12 import { parse, serialize } from "cookie"; 12 13 import * as set_cookie_parser from "set-cookie-parser";
+11 -3
.svelte-kit/output/server/manifest-full.js
··· 7 7 return { 8 8 appDir: "_app", 9 9 appPath: "_app", 10 - assets: new Set(["favicon.png","favicon.svg","frogcursor-small.png","frogcursor.png","robots.txt"]), 10 + assets: new Set(["favicon.png","favicon.svg","frogcursor-small.png","frogcursor.png","frogeye.png","froggie.png","froggiejump.png","froggiestand.png","frogicon.png","leaves.png","robots.txt"]), 11 11 mimeTypes: {".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain"}, 12 12 _: { 13 - client: {start:"_app/immutable/entry/start.YsP-T6iU.js",app:"_app/immutable/entry/app.BiVWJwsp.js",imports:["_app/immutable/entry/start.YsP-T6iU.js","_app/immutable/chunks/D9RahMPT.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/B43_79mg.js","_app/immutable/entry/app.BiVWJwsp.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/BcVkVDn_.js","_app/immutable/chunks/mmStoiki.js","_app/immutable/chunks/B43_79mg.js","_app/immutable/chunks/C_B-Ij-b.js","_app/immutable/chunks/C6hdjiAW.js"],stylesheets:[],fonts:[],uses_env_dynamic_public:false}, 13 + client: {start:"_app/immutable/entry/start.BUzUbSG3.js",app:"_app/immutable/entry/app.CwuxgLSd.js",imports:["_app/immutable/entry/start.BUzUbSG3.js","_app/immutable/chunks/C0nNmPgn.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/entry/app.CwuxgLSd.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/BsDbD4Ku.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/chunks/XE2G8ySY.js","_app/immutable/chunks/CFYBLbZM.js","_app/immutable/chunks/Dr80VTgO.js"],stylesheets:[],fonts:[],uses_env_dynamic_public:false}, 14 14 nodes: [ 15 15 __memo(() => import('./nodes/0.js')), 16 16 __memo(() => import('./nodes/1.js')), 17 - __memo(() => import('./nodes/2.js')) 17 + __memo(() => import('./nodes/2.js')), 18 + __memo(() => import('./nodes/3.js')) 18 19 ], 19 20 remotes: { 20 21 ··· 25 26 pattern: /^\/$/, 26 27 params: [], 27 28 page: { layouts: [0,], errors: [1,], leaf: 2 }, 29 + endpoint: null 30 + }, 31 + { 32 + id: "/profile/[handle]", 33 + pattern: /^\/profile\/([^/]+?)\/?$/, 34 + params: [{"name":"handle","optional":false,"rest":false,"chained":false}], 35 + page: { layouts: [0,], errors: [1,], leaf: 3 }, 28 36 endpoint: null 29 37 } 30 38 ],
+11 -4
.svelte-kit/output/server/manifest.js
··· 7 7 return { 8 8 appDir: "_app", 9 9 appPath: "_app", 10 - assets: new Set(["favicon.png","favicon.svg","frogcursor-small.png","frogcursor.png","robots.txt"]), 10 + assets: new Set(["favicon.png","favicon.svg","frogcursor-small.png","frogcursor.png","frogeye.png","froggie.png","froggiejump.png","froggiestand.png","frogicon.png","leaves.png","robots.txt"]), 11 11 mimeTypes: {".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain"}, 12 12 _: { 13 - client: {start:"_app/immutable/entry/start.YsP-T6iU.js",app:"_app/immutable/entry/app.BiVWJwsp.js",imports:["_app/immutable/entry/start.YsP-T6iU.js","_app/immutable/chunks/D9RahMPT.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/B43_79mg.js","_app/immutable/entry/app.BiVWJwsp.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/BcVkVDn_.js","_app/immutable/chunks/mmStoiki.js","_app/immutable/chunks/B43_79mg.js","_app/immutable/chunks/C_B-Ij-b.js","_app/immutable/chunks/C6hdjiAW.js"],stylesheets:[],fonts:[],uses_env_dynamic_public:false}, 13 + client: {start:"_app/immutable/entry/start.BUzUbSG3.js",app:"_app/immutable/entry/app.CwuxgLSd.js",imports:["_app/immutable/entry/start.BUzUbSG3.js","_app/immutable/chunks/C0nNmPgn.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/entry/app.CwuxgLSd.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/BsDbD4Ku.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/chunks/XE2G8ySY.js","_app/immutable/chunks/CFYBLbZM.js","_app/immutable/chunks/Dr80VTgO.js"],stylesheets:[],fonts:[],uses_env_dynamic_public:false}, 14 14 nodes: [ 15 15 __memo(() => import('./nodes/0.js')), 16 - __memo(() => import('./nodes/1.js')) 16 + __memo(() => import('./nodes/1.js')), 17 + __memo(() => import('./nodes/3.js')) 17 18 ], 18 19 remotes: { 19 20 20 21 }, 21 22 routes: [ 22 - 23 + { 24 + id: "/profile/[handle]", 25 + pattern: /^\/profile\/([^/]+?)\/?$/, 26 + params: [{"name":"handle","optional":false,"rest":false,"chained":false}], 27 + page: { layouts: [0,], errors: [1,], leaf: 2 }, 28 + endpoint: null 29 + } 23 30 ], 24 31 prerendered_routes: new Set(["/"]), 25 32 matchers: async () => {
+2 -2
.svelte-kit/output/server/nodes/0.js
··· 8 8 "ssr": false 9 9 }; 10 10 export const universal_id = "src/routes/+layout.ts"; 11 - export const imports = ["_app/immutable/nodes/0.D6CLfhqK.js","_app/immutable/chunks/mmStoiki.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/8u-mThFx.js","_app/immutable/chunks/C_B-Ij-b.js","_app/immutable/chunks/DsupRLPE.js"]; 12 - export const stylesheets = ["_app/immutable/assets/0.CyGpFWYY.css"]; 11 + export const imports = ["_app/immutable/nodes/0.Cq8Xsn4J.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/DmyE0d-6.js","_app/immutable/chunks/CFYBLbZM.js","_app/immutable/chunks/B46dcLgj.js"]; 12 + export const stylesheets = ["_app/immutable/assets/0.DIlgUleF.css"]; 13 13 export const fonts = [];
+1 -1
.svelte-kit/output/server/nodes/1.js
··· 3 3 export const index = 1; 4 4 let component_cache; 5 5 export const component = async () => component_cache ??= (await import('../entries/fallbacks/error.svelte.js')).default; 6 - export const imports = ["_app/immutable/nodes/1.xyjmz21p.js","_app/immutable/chunks/mmStoiki.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/DsupRLPE.js","_app/immutable/chunks/BcVkVDn_.js","_app/immutable/chunks/D9RahMPT.js","_app/immutable/chunks/B43_79mg.js"]; 6 + export const imports = ["_app/immutable/nodes/1.BfJAtU5y.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/B46dcLgj.js","_app/immutable/chunks/BsDbD4Ku.js","_app/immutable/chunks/C0nNmPgn.js","_app/immutable/chunks/DxGD2b0U.js"]; 7 7 export const stylesheets = []; 8 8 export const fonts = [];
+2 -2
.svelte-kit/output/server/nodes/2.js
··· 3 3 export const index = 2; 4 4 let component_cache; 5 5 export const component = async () => component_cache ??= (await import('../entries/pages/_page.svelte.js')).default; 6 - export const imports = ["_app/immutable/nodes/2.D4xyri_M.js","_app/immutable/chunks/mmStoiki.js","_app/immutable/chunks/w0kPbzMq.js","_app/immutable/chunks/B43_79mg.js","_app/immutable/chunks/BcVkVDn_.js","_app/immutable/chunks/C_B-Ij-b.js","_app/immutable/chunks/8u-mThFx.js","_app/immutable/chunks/C6hdjiAW.js","_app/immutable/chunks/DsupRLPE.js"]; 7 - export const stylesheets = ["_app/immutable/assets/2.BKmFmlcI.css"]; 6 + export const imports = ["_app/immutable/nodes/2.DCJPxWEg.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/chunks/BsDbD4Ku.js","_app/immutable/chunks/XE2G8ySY.js","_app/immutable/chunks/CFYBLbZM.js","_app/immutable/chunks/DmyE0d-6.js","_app/immutable/chunks/D_t83wNY.js","_app/immutable/chunks/Dr80VTgO.js"]; 7 + export const stylesheets = ["_app/immutable/assets/FrogHeader.8kzFzgPu.css","_app/immutable/assets/2.CHt1yucP.css"]; 8 8 export const fonts = [];
+13
.svelte-kit/output/server/nodes/3.js
··· 1 + 2 + 3 + export const index = 3; 4 + let component_cache; 5 + export const component = async () => component_cache ??= (await import('../entries/pages/profile/_handle_/_page.svelte.js')).default; 6 + export const universal = { 7 + "prerender": false, 8 + "ssr": false 9 + }; 10 + export const universal_id = "src/routes/profile/[handle]/+page.ts"; 11 + export const imports = ["_app/immutable/nodes/3.CW9t1woG.js","_app/immutable/chunks/DGbOEUpF.js","_app/immutable/chunks/CkzjbUDB.js","_app/immutable/chunks/DxGD2b0U.js","_app/immutable/chunks/BsDbD4Ku.js","_app/immutable/chunks/XE2G8ySY.js","_app/immutable/chunks/CFYBLbZM.js","_app/immutable/chunks/DmyE0d-6.js","_app/immutable/chunks/D_t83wNY.js","_app/immutable/chunks/C0nNmPgn.js"]; 12 + export const stylesheets = ["_app/immutable/assets/FrogHeader.8kzFzgPu.css","_app/immutable/assets/3.CjGf6tQE.css"]; 13 + export const fonts = [];
+4
.svelte-kit/types/route_meta_data.json
··· 2 2 "/": [ 3 3 "src/routes/+layout.ts", 4 4 "src/routes/+layout.ts" 5 + ], 6 + "/profile/[handle]": [ 7 + "src/routes/profile/[handle]/+page.ts", 8 + "src/routes/+layout.ts" 5 9 ] 6 10 }
+2 -2
.svelte-kit/types/src/routes/$types.d.ts
··· 11 11 type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never; 12 12 export type Snapshot<T = any> = Kit.Snapshot<T>; 13 13 type PageParentData = EnsureDefined<LayoutData>; 14 - type LayoutRouteId = RouteId | "/" | null 15 - type LayoutParams = RouteParams & { } 14 + type LayoutRouteId = RouteId | "/" | "/profile/[handle]" | null 15 + type LayoutParams = RouteParams & { handle?: string } 16 16 type LayoutParentData = EnsureDefined<{}>; 17 17 18 18 export type PageServerData = null;
+20
.svelte-kit/types/src/routes/profile/[handle]/$types.d.ts
··· 1 + import type * as Kit from '@sveltejs/kit'; 2 + 3 + type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; 4 + type MatcherParam<M> = M extends (param : string) => param is (infer U extends string) ? U : string; 5 + type RouteParams = { handle: string }; 6 + type RouteId = '/profile/[handle]'; 7 + type MaybeWithVoid<T> = {} extends T ? T | void : T; 8 + export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T]; 9 + type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>> 10 + type EnsureDefined<T> = T extends null | undefined ? {} : T; 11 + type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never; 12 + export type Snapshot<T = any> = Kit.Snapshot<T>; 13 + type PageParentData = EnsureDefined<import('../../$types.js').LayoutData>; 14 + 15 + export type EntryGenerator = () => Promise<Array<RouteParams>> | Array<RouteParams>; 16 + export type PageServerData = null; 17 + export type PageLoad<OutputData extends OutputDataShape<PageParentData> = OutputDataShape<PageParentData>> = Kit.Load<RouteParams, PageServerData, PageParentData, OutputData, RouteId>; 18 + export type PageLoadEvent = Parameters<PageLoad>[0]; 19 + export type PageData = Expand<Omit<PageParentData, keyof PageParentData & EnsureDefined<PageServerData>> & OptionalUnion<EnsureDefined<PageParentData & EnsureDefined<PageServerData>>>>; 20 + export type PageProps = { params: RouteParams; data: PageData }
-1
build/_app/immutable/assets/0.CyGpFWYY.css
··· 1 - .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-1;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;top:0;bottom:0;width:100px;z-index:100;pointer-events:none;opacity:.85}.plant-overlay.left.svelte-11afcec{left:10px}.plant-overlay.right.svelte-11afcec{right:10px}.plant-overlay.svelte-11afcec svg:where(.svelte-11afcec){width:100%;height:100%}@media(max-width:900px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
+1
build/_app/immutable/assets/0.DIlgUleF.css
··· 1 + .mesh-bg.svelte-17k46oa{position:fixed;inset:0;z-index:-2;overflow:hidden}.mesh-svg.svelte-17k46oa{width:100%;height:100%}.plant-overlay.svelte-11afcec{position:fixed;inset:0;z-index:-1;pointer-events:none;overflow:hidden;mix-blend-mode:multiply}.leaves.svelte-11afcec{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}@media(max-width:768px){.plant-overlay.svelte-11afcec{display:none}}html,body{margin:0;padding:0;min-height:100vh;overflow-x:hidden}body{font-family:Nunito,Fang,system-ui,-apple-system,BlinkMacSystemFont,sans-serif}*{box-sizing:border-box}::selection{background:#ff399280;color:#ffdeed}::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#1a8c22}::-webkit-scrollbar-thumb{background:#0a182b;border-radius:5px}::-webkit-scrollbar-thumb:hover{background:#ff3992}
-1
build/_app/immutable/assets/2.BKmFmlcI.css
··· 1 - .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-svg.svelte-7frlgw{position:absolute;inset:-8px;width:calc(100% + 16px);height:calc(100% + 16px);z-index:0;pointer-events:none}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.player-wrapper.svelte-zbxgh1{position:relative;width:100%;background:#0a182b;overflow:hidden}video.svelte-zbxgh1{width:100%;display:block;max-height:70vh}.error-overlay.svelte-zbxgh1{position:absolute;bottom:0;left:0;right:0;background:#ff3992d9;color:#ffdeed;padding:8px 12px;font-family:Fang,system-ui,sans-serif;font-size:.8rem}.card.svelte-1nxalmg{all:unset;cursor:url(../../../frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Fang,system-ui,sans-serif;font-size:1rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:6px}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.thumb-img.hidden.svelte-1nxalmg{opacity:0}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:8px 2px 0}.title.svelte-1nxalmg{margin:0;font-family:Fang,system-ui,sans-serif;font-size:.9rem;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.frog-header.svelte-1kxia9k{padding:30px 20px 10px;position:relative}.title-row.svelte-1kxia9k{display:flex;align-items:flex-end;gap:10px}.logo-text.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px}.header-frog.svelte-1kxia9k{width:clamp(60px,10vw,120px);height:auto;transform:rotate(-10deg);filter:drop-shadow(2px 3px 4px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px}.subtitle.svelte-1kxia9k{font-family:PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 100px 60px}.player-section.svelte-1uha8ag{margin-bottom:30px;padding:0 10px}.player-info.svelte-1uha8ag{display:flex;justify-content:space-between;align-items:flex-start;padding:14px 4px;gap:16px}.player-title.svelte-1uha8ag{margin:0;font-family:Fang,system-ui,sans-serif;font-size:1.2rem;color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.close-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:2px solid #39FF44;border-radius:50%;width:36px;height:36px;font-size:1rem;cursor:pointer;flex-shrink:0;font-family:Fang,system-ui,sans-serif;transition:background .15s,color .15s}.close-btn.svelte-1uha8ag:hover{background:#ff3992;border-color:#ff3992;color:#ffdeed}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:30px;padding:20px 10px}.load-more.svelte-1uha8ag{text-align:center;padding:30px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag){background:#0a182b;color:#39ff44;border:3px solid #0A182B;padding:12px 36px;border-radius:40px;font-family:PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.load-more.svelte-1uha8ag button:where(.svelte-1uha8ag):disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Fang,system-ui,sans-serif;border:2px solid #FF3992}@media(max-width:768px){.app.svelte-1uha8ag{padding:0 16px 40px}.grid.svelte-1uha8ag{grid-template-columns:1fr;gap:24px;padding:10px 0}}
+1
build/_app/immutable/assets/2.CHt1yucP.css
··· 1 + .player-wrapper.svelte-zbxgh1{position:relative;width:100%;background:#0a182b;overflow:hidden}.player-wrapper.svelte-zbxgh1:fullscreen{display:flex;align-items:center;justify-content:center}.player-wrapper.svelte-zbxgh1:fullscreen video:where(.svelte-zbxgh1){max-height:100vh;max-width:100vw;object-fit:contain}video.svelte-zbxgh1{width:100%;display:block;max-height:70vh;cursor:pointer}.controls.svelte-zbxgh1{position:absolute;bottom:5%;left:10%;right:15%;opacity:0;transition:opacity .25s ease;pointer-events:none}.controls.visible.svelte-zbxgh1{opacity:1;pointer-events:auto}.scrub-bar.svelte-zbxgh1{position:relative;height:48px;cursor:pointer}.scrub-frog.svelte-zbxgh1{position:absolute;bottom:0;transform:translate(-50%);cursor:grab;transition:left .05s linear;z-index:2;padding:6px}.scrub-frog.svelte-zbxgh1:active{cursor:grabbing}.scrub-frog.flipped.svelte-zbxgh1{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-zbxgh1{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.5));pointer-events:none}.fullscreen-btn.svelte-zbxgh1{all:unset;position:absolute;bottom:5%;right:8%;cursor:pointer;opacity:0;transition:opacity .25s ease,transform .2s ease;z-index:5}.fullscreen-btn.visible.svelte-zbxgh1{opacity:1}.fullscreen-btn.svelte-zbxgh1:hover{transform:scale(1.15)}.frogeye.svelte-zbxgh1{width:44px;height:44px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4))}.error-overlay.svelte-zbxgh1{position:absolute;bottom:15%;left:10%;right:10%;background:#ff3992d9;color:#ffdeed;padding:8px 12px;border-radius:6px;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem}.card.svelte-1nxalmg{all:unset;cursor:url(../../../frogcursor-small.png) 12 12,pointer;display:flex;flex-direction:column;transition:transform .2s ease;position:relative}.card.svelte-1nxalmg:hover{transform:scale(1.03)!important}.duration-badge.svelte-1nxalmg{display:block;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#ff3992;font-weight:700;letter-spacing:.5px;margin-bottom:8px;text-align:right}.thumb-wrapper.svelte-1nxalmg{margin:0}.thumbnail.svelte-1nxalmg{position:relative;width:100%;aspect-ratio:16 / 9;background:linear-gradient(135deg,#3992ff,#1e4e8c);display:flex;align-items:center;justify-content:center;overflow:hidden}.thumb-img.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .15s}.scrub-canvas.svelte-1nxalmg{position:absolute;inset:0;width:100%;height:100%;opacity:0;pointer-events:none}.scrub-canvas.visible.svelte-1nxalmg{opacity:1}.scrub-frog.svelte-1nxalmg{position:absolute;bottom:0%;z-index:4;pointer-events:none;transform:translate(-50%);transition:left .05s linear}.scrub-frog.flipped.svelte-1nxalmg{transform:translate(-50%) scaleX(-1)}.frog-sprite.svelte-1nxalmg{width:48px;height:auto;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4));image-rendering:auto}.thumb-shadow.svelte-1nxalmg{position:absolute;inset:0;box-shadow:inset 0 3px 16px #0a182b80;pointer-events:none}.loading-spinner.svelte-1nxalmg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:3}.spinner.svelte-1nxalmg{width:28px;height:28px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:svelte-1nxalmg-spin .8s linear infinite}@keyframes svelte-1nxalmg-spin{to{transform:rotate(360deg)}}.scrub-bar.svelte-1nxalmg{position:absolute;bottom:0;left:0;right:0;height:3px;background:#fff3;z-index:2}.scrub-bar-fill.svelte-1nxalmg{height:100%;background:#ff3992;transition:width .05s linear}.info.svelte-1nxalmg{padding:14px 10px 8px}.title.svelte-1nxalmg{margin:0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.9rem;font-weight:700;color:#0a182b;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.creator.svelte-1nxalmg{margin:4px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.8rem;color:#0a182b;opacity:.8;text-decoration:underline;text-decoration-color:#ff3992}.date.svelte-1nxalmg{margin:2px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#ff3992;font-style:italic}.app.svelte-1uha8ag{max-width:1300px;margin:0 auto;padding:0 clamp(24px,7vw,120px) 60px}.player-section.svelte-1uha8ag{margin-bottom:40px;margin-top:20px;padding:0 10px}.player-info.svelte-1uha8ag{padding:20px 4px}.player-title.svelte-1uha8ag{margin:0;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.4rem,3vw,2rem);color:#0a182b}.player-meta.svelte-1uha8ag{margin:6px 0 0;font-family:Nunito,Fang,system-ui,sans-serif;color:#0a182b;opacity:.7;font-size:.85rem}.creator-tag.svelte-1uha8ag{color:#3992ff;text-decoration:underline}.dot.svelte-1uha8ag{margin:0 4px;color:#0a182b;opacity:.4}.grid.svelte-1uha8ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(300px,100%),1fr));gap:clamp(32px,5vw,50px);padding:20px clamp(16px,3vw,24px)}.pagination.svelte-1uha8ag{display:flex;justify-content:center;align-items:center;gap:20px;padding:30px}.page-btn.svelte-1uha8ag{background:#0a182b;color:#39ff44;border:3px solid #0a182b;padding:12px 32px;border-radius:40px;font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;cursor:pointer;transition:all .2s ease;letter-spacing:.5px}.page-btn.svelte-1uha8ag:hover{background:#39ff44;color:#0a182b;border-color:#0a182b}.page-btn.svelte-1uha8ag:disabled{background:#1a8c22;color:#0a182b;border-color:#1a8c22;cursor:wait;opacity:.6}.page-num.svelte-1uha8ag{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b}.error.svelte-1uha8ag{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:0 10px 20px;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #ff3992}
+1
build/_app/immutable/assets/3.CjGf6tQE.css
··· 1 + .profile-page.svelte-oxml5t{max-width:800px;margin:0 auto;padding:0 clamp(24px,7vw,80px) 60px}.loading.svelte-oxml5t{text-align:center;padding:60px 20px}.loading-frog.svelte-oxml5t{width:64px;height:auto;animation:svelte-oxml5t-hop .6s ease-in-out infinite alternate}@keyframes svelte-oxml5t-hop{0%{transform:translateY(0)}to{transform:translateY(-12px)}}.loading-text.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.2rem;color:#0a182b;margin-top:12px}.error.svelte-oxml5t{background:#ff399226;color:#ff3992;padding:12px 16px;border-radius:8px;margin:20px 0;font-family:Nunito,Fang,system-ui,sans-serif;border:2px solid #FF3992}.profile-layout.svelte-oxml5t{display:flex;flex-direction:column;gap:24px}.banner-img.svelte-oxml5t{width:100%;display:block;aspect-ratio:3 / 1;object-fit:cover}.profile-card-area.svelte-oxml5t{margin-top:-20px}.profile-card.svelte-oxml5t{display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px}.avatar-wrapper.svelte-oxml5t{width:clamp(80px,15vw,120px);margin-bottom:8px}.avatar.svelte-oxml5t{width:100%;display:block;aspect-ratio:1;object-fit:cover;border-radius:0}.display-name.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(1.8rem,4vw,2.8rem);color:#0a182b;margin:0;line-height:1.1}.handle.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:1rem;color:#0a182b;opacity:.7;margin:0}.description.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.95rem;color:#0a182b;margin:8px 0;max-width:500px;line-height:1.5}.stats.svelte-oxml5t{display:flex;gap:clamp(16px,4vw,32px);margin:12px 0}.stat.svelte-oxml5t{display:flex;flex-direction:column;align-items:center}.stat-num.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.4rem;color:#0a182b;font-weight:700}.stat-label.svelte-oxml5t{font-family:Nunito,Fang,system-ui,sans-serif;font-size:.75rem;color:#0a182b;opacity:.6}.profile-link.svelte-oxml5t{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;margin-top:8px;transition:color .15s}.profile-link.svelte-oxml5t:hover{color:#ff3992}.back-link.svelte-oxml5t{text-align:center;padding:30px}.back-link.svelte-oxml5t a:where(.svelte-oxml5t){font-family:Shrikhand,PicNic,cursive,system-ui;font-size:1.1rem;color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.back-link.svelte-oxml5t a:where(.svelte-oxml5t):hover{color:#ff3992}
+1
build/_app/immutable/assets/FrogHeader.8kzFzgPu.css
··· 1 + .wavy-container.svelte-7frlgw{position:relative;isolation:isolate}.wavy-clipped.svelte-7frlgw{position:relative}.wavy-fill.svelte-7frlgw{position:absolute;inset:0;z-index:0}.wavy-content.svelte-7frlgw{position:relative;z-index:1;padding:var(--padding)}.wavy-stroke.svelte-7frlgw{position:absolute;inset:0;width:100%;height:100%;z-index:3;pointer-events:none;overflow:visible}.frog-header.svelte-1kxia9k{padding:30px 20px;position:relative}.title-area.svelte-1kxia9k{position:relative;display:inline-block}.logo-link.svelte-1kxia9k{text-decoration:none;color:inherit}.logo-text.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(3rem,8vw,5.5rem);color:#0a182b;margin:0;line-height:.9;font-weight:400;letter-spacing:-1px;position:relative;z-index:1}.header-frog.svelte-1kxia9k{position:absolute;right:-80px;top:-60px;width:clamp(120px,18vw,220px);height:auto;z-index:2;transform:rotate(-10deg);filter:drop-shadow(2px 4px 6px rgba(10,24,43,.3));transition:transform .3s ease}.header-frog.svelte-1kxia9k:hover{transform:rotate(5deg) scale(1.1)}.subtitle-lines.svelte-1kxia9k{margin-top:6px;position:relative;z-index:0}.subtitle-link.svelte-1kxia9k{color:#0a182b;text-decoration:underline;text-decoration-color:#ff3992;transition:color .15s}.subtitle-link.svelte-1kxia9k:hover{color:#ff3992}.subtitle.svelte-1kxia9k{font-family:Shrikhand,PicNic,cursive,system-ui;font-size:clamp(.85rem,2vw,1.15rem);color:#0a182b;margin:0;line-height:1.4;opacity:.85}@media(max-width:600px){.frog-header.svelte-1kxia9k{padding:20px 16px 8px}.header-frog.svelte-1kxia9k{right:-100px;top:-20px}}
-2
build/_app/immutable/chunks/8u-mThFx.js
··· 1 - import{g as p,E as v,c as N,$ as T,a0 as b,h as a,a1 as m,a2 as o,n as E,l as c,f as y,a3 as F}from"./w0kPbzMq.js";import{B as h}from"./C_B-Ij-b.js";function _(i,s,...e){var t=new h(i);p(()=>{const l=s()??null;t.ensure(l,l&&(n=>l(n,...e)))},v)}function O(i,s){let e=null,t=a;var l;if(a){e=y;for(var n=F(document.head);n!==null&&(n.nodeType!==m||n.data!==i);)n=o(n);if(n===null)E(!1);else{var r=o(n);n.remove(),c(r)}}a||(l=document.head.appendChild(N()));try{p(()=>s(l),T|b)}finally{t&&(E(!0),c(e))}}const d=[...` 2 - \r\f \v\uFEFF`];function w(i,s,e){var t=i==null?"":""+i;if(s&&(t=t?t+" "+s:s),e){for(var l of Object.keys(e))if(e[l])t=t?t+" "+l:l;else if(t.length)for(var n=l.length,r=0;(r=t.indexOf(l,r))>=0;){var f=r+n;(r===0||d.includes(t[r-1]))&&(f===t.length||d.includes(t[f]))?t=(r===0?"":t.substring(0,r))+t.substring(f+1):r=f}}return t===""?null:t}function R(i,s){return i==null?null:String(i)}function D(i,s,e,t,l,n){var r=i.__className;if(a||r!==e||r===void 0){var f=w(e,t,n);(!a||f!==i.getAttribute("class"))&&(f==null?i.removeAttribute("class"):i.className=f),i.__className=e}else if(n&&l!==n)for(var u in n){var g=!!n[u];(l==null||g!==!!l[u])&&i.classList.toggle(u,g)}return n}export{_ as a,O as h,D as s,R as t};
-1
build/_app/immutable/chunks/B43_79mg.js
··· 1 - import{u as l,o as t,q as u,t as o}from"./w0kPbzMq.js";function c(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function a(e){t===null&&c(),u&&t.l!==null?i(t).m.push(e):l(()=>{const n=o(e);if(typeof n=="function")return n})}function f(e){t===null&&c(),a(()=>()=>o(e))}function i(e){var n=e.l;return n.u??={a:[],b:[],m:[]}}export{f as a,a as o};
+1
build/_app/immutable/chunks/B46dcLgj.js
··· 1 + import{e}from"./CkzjbUDB.js";e();
-2
build/_app/immutable/chunks/BcVkVDn_.js
··· 1 - import{ab as Z,A as j,w as ee,ac as z,t as te,ad as Y,ae as T,f as g,h as v,x as m,af as P,g as re,i as se,ag as ie,ah as V,b as p,c as U,p as x,a as W,m as ae,ai as ne,aj as N,ak as D,al as q,am as fe,an as he,ao as J,o as X,ap as oe,d as F,l as O,aq as le,k as de,ar as S,E as ce,a0 as ue,as as _e,at as pe,au as ge,av as ve,aw as ye,ax as L,a3 as be,a1 as G,ay as me,a2 as Ee,az as M,n as R,aA as we,aB as Te,aC as Se,aD as Re,U as Ae,aE as Ne,aF as De,X as Oe}from"./w0kPbzMq.js";import{b as ke}from"./mmStoiki.js";function xe(t){let e=0,r=z(0),i;return()=>{Z()&&(j(r),ee(()=>(e===0&&(i=te(()=>t(()=>Y(r)))),e+=1,()=>{T(()=>{e-=1,e===0&&(i?.(),i=void 0,Y(r))})})))}}var Fe=ce|ue;function Le(t,e,r,i){new Me(t,e,r,i)}class Me{parent;is_pending=!1;transform_error;#t;#_=v?g:null;#i;#o;#e;#a=null;#r=null;#s=null;#n=null;#l=0;#h=0;#d=!1;#p=new Set;#g=new Set;#f=null;#b=xe(()=>(this.#f=z(this.#l),()=>{this.#f=null}));constructor(e,r,i,a){this.#t=e,this.#i=r,this.#o=s=>{var n=m;n.b=this,n.f|=P,i(s)},this.parent=m.b,this.transform_error=a??this.parent?.transform_error??(s=>s),this.#e=re(()=>{if(v){const s=this.#_;se();const n=s.data===ie;if(s.data.startsWith(V)){const f=JSON.parse(s.data.slice(V.length));this.#E(f)}else n?this.#w():this.#m()}else this.#v()},Fe),v&&(this.#t=g)}#m(){try{this.#a=p(()=>this.#o(this.#t))}catch(e){this.error(e)}}#E(e){const r=this.#i.failed;r&&(this.#s=p(()=>{r(this.#t,()=>e,()=>()=>{})}))}#w(){const e=this.#i.pending;e&&(this.is_pending=!0,this.#r=p(()=>e(this.#t)),T(()=>{var r=this.#n=document.createDocumentFragment(),i=U();r.append(i),this.#a=this.#u(()=>p(()=>this.#o(i))),this.#h===0&&(this.#t.before(r),this.#n=null,x(this.#r,()=>{this.#r=null}),this.#c(W))}))}#v(){try{if(this.is_pending=this.has_pending_snippet(),this.#h=0,this.#l=0,this.#a=p(()=>{this.#o(this.#t)}),this.#h>0){var e=this.#n=document.createDocumentFragment();ae(this.#a,e);const r=this.#i.pending;this.#r=p(()=>r(this.#t))}else this.#c(W)}catch(r){this.error(r)}}#c(e){this.is_pending=!1,e.transfer_effects(this.#p,this.#g)}defer_effect(e){ne(e,this.#p,this.#g)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#i.pending}#u(e){var r=m,i=J,a=X;N(this.#e),D(this.#e),q(this.#e.ctx);try{return fe.ensure(),e()}catch(s){return he(s),null}finally{N(r),D(i),q(a)}}#y(e,r){if(!this.has_pending_snippet()){this.parent&&this.parent.#y(e,r);return}this.#h+=e,this.#h===0&&(this.#c(r),this.#r&&x(this.#r,()=>{this.#r=null}),this.#n&&(this.#t.before(this.#n),this.#n=null))}update_pending_count(e,r){this.#y(e,r),this.#l+=e,!(!this.#f||this.#d)&&(this.#d=!0,T(()=>{this.#d=!1,this.#f&&oe(this.#f,this.#l)}))}get_effect_pending(){return this.#b(),j(this.#f)}error(e){var r=this.#i.onerror;let i=this.#i.failed;if(!r&&!i)throw e;this.#a&&(F(this.#a),this.#a=null),this.#r&&(F(this.#r),this.#r=null),this.#s&&(F(this.#s),this.#s=null),v&&(O(this.#_),le(),O(de()));var a=!1,s=!1;const n=()=>{if(a){pe();return}a=!0,s&&_e(),this.#s!==null&&x(this.#s,()=>{this.#s=null}),this.#u(()=>{this.#v()})},c=f=>{try{s=!0,r?.(f,n),s=!1}catch(h){S(h,this.#e&&this.#e.parent)}i&&(this.#s=this.#u(()=>{try{return p(()=>{var h=m;h.b=this,h.f|=P,i(this.#t,()=>f,()=>n)})}catch(h){return S(h,this.#e.parent),null}}))};T(()=>{var f;try{f=this.transform_error(e)}catch(h){S(h,this.#e&&this.#e.parent);return}f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(c,h=>S(h,this.#e&&this.#e.parent)):c(f)})}}const Ce=["touchstart","touchmove"];function Ie(t){return Ce.includes(t)}const w=Symbol("events"),K=new Set,C=new Set;function Be(t,e,r,i={}){function a(s){if(i.capture||I.call(e,s),!s.cancelBubble)return ye(()=>r?.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?T(()=>{e.addEventListener(t,a,i)}):e.addEventListener(t,a,i),a}function Ve(t,e,r,i,a){var s={capture:i,passive:a},n=Be(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&ve(()=>{e.removeEventListener(t,n,s)})}function We(t,e,r){(e[w]??={})[t]=r}function qe(t){for(var e=0;e<t.length;e++)K.add(t[e]);for(var r of C)r(t)}let $=null;function I(t){var e=this,r=e.ownerDocument,i=t.type,a=t.composedPath?.()||[],s=a[0]||t.target;$=t;var n=0,c=$===t&&t[w];if(c){var f=a.indexOf(c);if(f!==-1&&(e===document||e===window)){t[w]=e;return}var h=a.indexOf(e);if(h===-1)return;f<=h&&(n=f)}if(s=a[n]||t.target,s!==e){ge(t,"currentTarget",{configurable:!0,get(){return s||r}});var y=J,E=m;D(null),N(null);try{for(var _,l=[];s!==null;){var o=s.assignedSlot||s.parentNode||s.host||null;try{var d=s[w]?.[i];d!=null&&(!s.disabled||t.target===s)&&d.call(s,t)}catch(u){_?l.push(u):_=u}if(t.cancelBubble||o===e||o===null)break;s=o}if(_){for(let u of l)queueMicrotask(()=>{throw u});throw _}}finally{t[w]=e,delete t.currentTarget,D(y),N(E)}}}function $e(t,e){var r=e==null?"":typeof e=="object"?`${e}`:e;r!==(t.__t??=t.nodeValue)&&(t.__t=r,t.nodeValue=`${r}`)}function He(t,e){return Q(t,e)}function je(t,e){L(),e.intro=e.intro??!1;const r=e.target,i=v,a=g;try{for(var s=be(r);s&&(s.nodeType!==G||s.data!==me);)s=Ee(s);if(!s)throw M;R(!0),O(s);const n=Q(t,{...e,anchor:s});return R(!1),n}catch(n){if(n instanceof Error&&n.message.split(` 2 - `).some(c=>c.startsWith("https://svelte.dev/e/")))throw n;return n!==M&&console.warn("Failed to hydrate: ",n),e.recover===!1&&we(),L(),Te(r),R(!1),He(t,e)}finally{R(i),O(a)}}const A=new Map;function Q(t,{target:e,anchor:r,props:i={},events:a,context:s,intro:n=!0,transformError:c}){L();var f=void 0,h=Se(()=>{var y=r??e.appendChild(U());Le(y,{pending:()=>{}},l=>{Ae({});var o=X;if(s&&(o.c=s),a&&(i.$$events=a),v&&ke(l,null),f=t(l,i)||{},v&&(m.nodes.end=g,g===null||g.nodeType!==G||g.data!==Ne))throw De(),M;Oe()},c);var E=new Set,_=l=>{for(var o=0;o<l.length;o++){var d=l[o];if(!E.has(d)){E.add(d);var u=Ie(d);for(const k of[e,document]){var b=A.get(k);b===void 0&&(b=new Map,A.set(k,b));var H=b.get(d);H===void 0?(k.addEventListener(d,I,{passive:u}),b.set(d,1)):b.set(d,H+1)}}}};return _(Re(K)),C.add(_),()=>{for(var l of E)for(const u of[e,document]){var o=A.get(u),d=o.get(l);--d==0?(u.removeEventListener(l,I),o.delete(l),o.size===0&&A.delete(u)):o.set(l,d)}C.delete(_),y!==r&&y.parentNode?.removeChild(y)}});return B.set(f,h),f}let B=new WeakMap;function ze(t,e){const r=B.get(t);return r?(B.delete(t),r(e)):Promise.resolve()}export{We as a,qe as d,Ve as e,je as h,He as m,$e as s,ze as u};
+2
build/_app/immutable/chunks/BsDbD4Ku.js
··· 1 + import{al as Z,A as j,r as ee,am as z,u as te,an as Y,ao as T,k as g,j as v,b as m,ap as q,l as re,F as se,aq as ie,ar as P,h as p,g as J,p as x,i as V,m as ne,as as ae,at as N,au as D,av as W,aw as fe,ax as he,ay as G,c as K,az as oe,f as k,t as F,aa as le,I as de,aA as S,E as ce,n as ue,aB as _e,aC as pe,w as ge,aD as ve,x as ye,aE as I,v as be,C as U,aF as me,o as Ee,aG as L,q as R,aH as we,aI as Te,aJ as Se,aK as Re,a1 as Ae,aL as Ne,aM as De,a4 as Fe}from"./CkzjbUDB.js";import{b as Oe}from"./DGbOEUpF.js";function xe(t){let e=0,r=z(0),i;return()=>{Z()&&(j(r),ee(()=>(e===0&&(i=te(()=>t(()=>Y(r)))),e+=1,()=>{T(()=>{e-=1,e===0&&(i?.(),i=void 0,Y(r))})})))}}var ke=ce|ue;function Ie(t,e,r,i){new Le(t,e,r,i)}class Le{parent;is_pending=!1;transform_error;#t;#_=v?g:null;#i;#o;#e;#n=null;#r=null;#s=null;#a=null;#l=0;#h=0;#d=!1;#p=new Set;#g=new Set;#f=null;#b=xe(()=>(this.#f=z(this.#l),()=>{this.#f=null}));constructor(e,r,i,n){this.#t=e,this.#i=r,this.#o=s=>{var a=m;a.b=this,a.f|=q,i(s)},this.parent=m.b,this.transform_error=n??this.parent?.transform_error??(s=>s),this.#e=re(()=>{if(v){const s=this.#_;se();const a=s.data===ie;if(s.data.startsWith(P)){const f=JSON.parse(s.data.slice(P.length));this.#E(f)}else a?this.#w():this.#m()}else this.#v()},ke),v&&(this.#t=g)}#m(){try{this.#n=p(()=>this.#o(this.#t))}catch(e){this.error(e)}}#E(e){const r=this.#i.failed;r&&(this.#s=p(()=>{r(this.#t,()=>e,()=>()=>{})}))}#w(){const e=this.#i.pending;e&&(this.is_pending=!0,this.#r=p(()=>e(this.#t)),T(()=>{var r=this.#a=document.createDocumentFragment(),i=J();r.append(i),this.#n=this.#u(()=>p(()=>this.#o(i))),this.#h===0&&(this.#t.before(r),this.#a=null,x(this.#r,()=>{this.#r=null}),this.#c(V))}))}#v(){try{if(this.is_pending=this.has_pending_snippet(),this.#h=0,this.#l=0,this.#n=p(()=>{this.#o(this.#t)}),this.#h>0){var e=this.#a=document.createDocumentFragment();ne(this.#n,e);const r=this.#i.pending;this.#r=p(()=>r(this.#t))}else this.#c(V)}catch(r){this.error(r)}}#c(e){this.is_pending=!1,e.transfer_effects(this.#p,this.#g)}defer_effect(e){ae(e,this.#p,this.#g)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#i.pending}#u(e){var r=m,i=G,n=K;N(this.#e),D(this.#e),W(this.#e.ctx);try{return fe.ensure(),e()}catch(s){return he(s),null}finally{N(r),D(i),W(n)}}#y(e,r){if(!this.has_pending_snippet()){this.parent&&this.parent.#y(e,r);return}this.#h+=e,this.#h===0&&(this.#c(r),this.#r&&x(this.#r,()=>{this.#r=null}),this.#a&&(this.#t.before(this.#a),this.#a=null))}update_pending_count(e,r){this.#y(e,r),this.#l+=e,!(!this.#f||this.#d)&&(this.#d=!0,T(()=>{this.#d=!1,this.#f&&oe(this.#f,this.#l)}))}get_effect_pending(){return this.#b(),j(this.#f)}error(e){var r=this.#i.onerror;let i=this.#i.failed;if(!r&&!i)throw e;this.#n&&(k(this.#n),this.#n=null),this.#r&&(k(this.#r),this.#r=null),this.#s&&(k(this.#s),this.#s=null),v&&(F(this.#_),le(),F(de()));var n=!1,s=!1;const a=()=>{if(n){pe();return}n=!0,s&&_e(),this.#s!==null&&x(this.#s,()=>{this.#s=null}),this.#u(()=>{this.#v()})},c=f=>{try{s=!0,r?.(f,a),s=!1}catch(h){S(h,this.#e&&this.#e.parent)}i&&(this.#s=this.#u(()=>{try{return p(()=>{var h=m;h.b=this,h.f|=q,i(this.#t,()=>f,()=>a)})}catch(h){return S(h,this.#e.parent),null}}))};T(()=>{var f;try{f=this.transform_error(e)}catch(h){S(h,this.#e&&this.#e.parent);return}f!==null&&typeof f=="object"&&typeof f.then=="function"?f.then(c,h=>S(h,this.#e&&this.#e.parent)):c(f)})}}const Me=["touchstart","touchmove"];function Ce(t){return Me.includes(t)}const w=Symbol("events"),Q=new Set,M=new Set;function He(t,e,r,i={}){function n(s){if(i.capture||C.call(e,s),!s.cancelBubble)return ve(()=>r?.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?T(()=>{e.addEventListener(t,n,i)}):e.addEventListener(t,n,i),n}function Pe(t,e,r,i,n){var s={capture:i,passive:n},a=He(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&ge(()=>{e.removeEventListener(t,a,s)})}function Ve(t,e,r){(e[w]??={})[t]=r}function We(t){for(var e=0;e<t.length;e++)Q.add(t[e]);for(var r of M)r(t)}let $=null;function C(t){var e=this,r=e.ownerDocument,i=t.type,n=t.composedPath?.()||[],s=n[0]||t.target;$=t;var a=0,c=$===t&&t[w];if(c){var f=n.indexOf(c);if(f!==-1&&(e===document||e===window)){t[w]=e;return}var h=n.indexOf(e);if(h===-1)return;f<=h&&(a=f)}if(s=n[a]||t.target,s!==e){ye(t,"currentTarget",{configurable:!0,get(){return s||r}});var y=G,E=m;D(null),N(null);try{for(var _,l=[];s!==null;){var o=s.assignedSlot||s.parentNode||s.host||null;try{var d=s[w]?.[i];d!=null&&(!s.disabled||t.target===s)&&d.call(s,t)}catch(u){_?l.push(u):_=u}if(t.cancelBubble||o===e||o===null)break;s=o}if(_){for(let u of l)queueMicrotask(()=>{throw u});throw _}}finally{t[w]=e,delete t.currentTarget,D(y),N(E)}}}function $e(t,e){var r=e==null?"":typeof e=="object"?`${e}`:e;r!==(t.__t??=t.nodeValue)&&(t.__t=r,t.nodeValue=`${r}`)}function Be(t,e){return X(t,e)}function je(t,e){I(),e.intro=e.intro??!1;const r=e.target,i=v,n=g;try{for(var s=be(r);s&&(s.nodeType!==U||s.data!==me);)s=Ee(s);if(!s)throw L;R(!0),F(s);const a=X(t,{...e,anchor:s});return R(!1),a}catch(a){if(a instanceof Error&&a.message.split(` 2 + `).some(c=>c.startsWith("https://svelte.dev/e/")))throw a;return a!==L&&console.warn("Failed to hydrate: ",a),e.recover===!1&&we(),I(),Te(r),R(!1),Be(t,e)}finally{R(i),F(n)}}const A=new Map;function X(t,{target:e,anchor:r,props:i={},events:n,context:s,intro:a=!0,transformError:c}){I();var f=void 0,h=Se(()=>{var y=r??e.appendChild(J());Ie(y,{pending:()=>{}},l=>{Ae({});var o=K;if(s&&(o.c=s),n&&(i.$$events=n),v&&Oe(l,null),f=t(l,i)||{},v&&(m.nodes.end=g,g===null||g.nodeType!==U||g.data!==Ne))throw De(),L;Fe()},c);var E=new Set,_=l=>{for(var o=0;o<l.length;o++){var d=l[o];if(!E.has(d)){E.add(d);var u=Ce(d);for(const O of[e,document]){var b=A.get(O);b===void 0&&(b=new Map,A.set(O,b));var B=b.get(d);B===void 0?(O.addEventListener(d,C,{passive:u}),b.set(d,1)):b.set(d,B+1)}}}};return _(Re(Q)),M.add(_),()=>{for(var l of E)for(const u of[e,document]){var o=A.get(u),d=o.get(l);--d==0?(u.removeEventListener(l,C),o.delete(l),o.size===0&&A.delete(u)):o.set(l,d)}M.delete(_),y!==r&&y.parentNode?.removeChild(y)}});return H.set(f,h),f}let H=new WeakMap;function ze(t,e){const r=H.get(t);return r?(H.delete(t),r(e)):Promise.resolve()}export{Ve as a,We as d,Pe as e,je as h,Be as m,$e as s,ze as u};
+1
build/_app/immutable/chunks/C0nNmPgn.js
··· 1 + import{ab as L,A as U,B as T,aO as te,b2 as gt}from"./CkzjbUDB.js";import{w as Ee,o as De}from"./DxGD2b0U.js";class Se{constructor(t,n){this.status=t,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${t}`}}toString(){return JSON.stringify(this.body)}}class Re{constructor(t,n){this.status=t,this.location=n}}class xe extends Error{constructor(t,n,r){super(r),this.status=t,this.text=n}}new URL("sveltekit-internal://");function _t(e,t){return e==="/"||t==="ignore"?e:t==="never"?e.endsWith("/")?e.slice(0,-1):e:t==="always"&&!e.endsWith("/")?e+"/":e}function mt(e){return e.split("%25").map(decodeURI).join("%25")}function vt(e){for(const t in e)e[t]=decodeURIComponent(e[t]);return e}function pe({href:e}){return e.split("#")[0]}function wt(...e){let t=5381;for(const n of e)if(typeof n=="string"){let r=n.length;for(;r;)t=t*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)t=t*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(t>>>0).toString(36)}new TextEncoder;new TextDecoder;function yt(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}const bt=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||"GET")!=="GET"&&G.delete(Ae(e)),bt(e,t));const G=new Map;function kt(e,t){const n=Ae(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:a,...i}=JSON.parse(r.textContent);const o=r.getAttribute("data-ttl");return o&&G.set(n,{body:a,init:i,ttl:1e3*Number(o)}),r.getAttribute("data-b64")!==null&&(a=yt(a)),Promise.resolve(new Response(a,i))}return window.fetch(e,t)}function Et(e,t,n){if(G.size>0){const r=Ae(e,n),a=G.get(r);if(a){if(performance.now()<a.ttl&&["default","force-cache","only-if-cached",void 0].includes(n?.cache))return new Response(a.body,a.init);G.delete(r)}}return window.fetch(t,n)}function Ae(e,t){let r=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){const a=[];t.headers&&a.push([...new Headers(t.headers)].join(",")),t.body&&(typeof t.body=="string"||ArrayBuffer.isView(t.body))&&a.push(t.body),r+=`[data-hash="${wt(...a)}"]`}return r}const St=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;function Rt(e){const t=[];return{pattern:e==="/"?/^\/$/:new RegExp(`^${At(e).map(r=>{const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return t.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const i=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(i)return t.push({name:i[1],matcher:i[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const o=r.split(/\[(.+?)\](?!\])/);return"/"+o.map((l,c)=>{if(c%2){if(l.startsWith("x+"))return ge(String.fromCharCode(parseInt(l.slice(2),16)));if(l.startsWith("u+"))return ge(String.fromCharCode(...l.slice(2).split("-").map(_=>parseInt(_,16))));const f=St.exec(l),[,p,v,h,u]=f;return t.push({name:h,matcher:u,optional:!!p,rest:!!v,chained:v?c===1&&o[0]==="":!1}),v?"([^]*?)":p?"([^/]*)?":"([^/]+?)"}return ge(l)}).join("")}).join("")}/?$`),params:t}}function xt(e){return e!==""&&!/^\([^)]+\)$/.test(e)}function At(e){return e.slice(1).split("/").filter(xt)}function Lt(e,t,n){const r={},a=e.slice(1),i=a.filter(s=>s!==void 0);let o=0;for(let s=0;s<t.length;s+=1){const l=t[s];let c=a[s-o];if(l.chained&&l.rest&&o&&(c=a.slice(s-o,s+1).filter(f=>f).join("/"),o=0),c===void 0)if(l.rest)c="";else continue;if(!l.matcher||n[l.matcher](c)){r[l.name]=c;const f=t[s+1],p=a[s+1];f&&!f.rest&&f.optional&&p&&l.chained&&(o=0),!f&&!p&&Object.keys(r).length===i.length&&(o=0);continue}if(l.optional&&l.chained){o++;continue}return}if(!o)return r}function ge(e){return e.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function Ut({nodes:e,server_loads:t,dictionary:n,matchers:r}){const a=new Set(t);return Object.entries(n).map(([s,[l,c,f]])=>{const{pattern:p,params:v}=Rt(s),h={id:s,exec:u=>{const _=p.exec(u);if(_)return Lt(_,v,r)},errors:[1,...f||[]].map(u=>e[u]),layouts:[0,...c||[]].map(o),leaf:i(l)};return h.errors.length=h.layouts.length=Math.max(h.errors.length,h.layouts.length),h});function i(s){const l=s<0;return l&&(s=~s),[l,e[s]]}function o(s){return s===void 0?s:[a.has(s),e[s]]}}function We(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function qe(e,t,n=JSON.stringify){const r=n(t);try{sessionStorage[e]=r}catch{}}const x=globalThis.__sveltekit_1gh8pzr?.base??"",Tt=globalThis.__sveltekit_1gh8pzr?.assets??x??"",It="1774912484423",Ye="sveltekit:snapshot",He="sveltekit:scroll",Je="sveltekit:states",Ot="sveltekit:pageurl",V="sveltekit:history",Y="sveltekit:navigation",j={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Le=location.origin;function Xe(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){const n=document.getElementsByTagName("base");t=n.length?n[0].href:document.URL}return new URL(e,t)}function D(){return{x:pageXOffset,y:pageYOffset}}function q(e,t){return e.getAttribute(`data-sveltekit-${t}`)}const Ve={...j,"":j.hover};function Qe(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function Ze(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()==="A"&&e.hasAttribute("href"))return e;e=Qe(e)}}function ve(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const s=location.hash.split("#")[1]||"/";r.hash=`#${s}${r.hash}`}}catch{}const a=e instanceof SVGAElement?e.target.baseVal:e.target,i=!r||!!a||ue(r,t,n)||(e.getAttribute("rel")||"").split(/\s+/).includes("external"),o=r?.origin===Le&&e.hasAttribute("download");return{url:r,external:i,target:a,download:o}}function ne(e){let t=null,n=null,r=null,a=null,i=null,o=null,s=e;for(;s&&s!==document.documentElement;)r===null&&(r=q(s,"preload-code")),a===null&&(a=q(s,"preload-data")),t===null&&(t=q(s,"keepfocus")),n===null&&(n=q(s,"noscroll")),i===null&&(i=q(s,"reload")),o===null&&(o=q(s,"replacestate")),s=Qe(s);function l(c){switch(c){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:Ve[r??"off"],preload_data:Ve[a??"off"],keepfocus:l(t),noscroll:l(n),reload:l(i),replace_state:l(o)}}function Be(e){const t=Ee(e);let n=!0;function r(){n=!0,t.update(o=>o)}function a(o){n=!1,t.set(o)}function i(o){let s;return t.subscribe(l=>{(s===void 0||n&&l!==s)&&o(s=l)})}return{notify:r,set:a,subscribe:i}}const et={v:()=>{}};function Pt(){const{set:e,subscribe:t}=Ee(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Tt}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const o=(await a.json()).version!==It;return o&&(e(!0),et.v(),clearTimeout(n)),o}catch{return!1}}return{subscribe:t,check:r}}function ue(e,t,n){return e.origin!==Le||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function ln(e){}const tt=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...tt];const $t=new Set([...tt]);[...$t];function Ct(e){return e.filter(t=>t!=null)}function Ue(e){return e instanceof Se||e instanceof xe?e.status:500}function jt(e){return e instanceof xe?e.text:"Internal Error"}let k,H,_e;const Nt=De.toString().includes("$$")||/function \w+\(\) \{\}/.test(De.toString()),ze="a:";Nt?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(ze)},H={current:null},_e={current:!1}):(k=new class{#e=L({});get data(){return U(this.#e)}set data(t){T(this.#e,t)}#t=L(null);get form(){return U(this.#t)}set form(t){T(this.#t,t)}#n=L(null);get error(){return U(this.#n)}set error(t){T(this.#n,t)}#r=L({});get params(){return U(this.#r)}set params(t){T(this.#r,t)}#a=L({id:null});get route(){return U(this.#a)}set route(t){T(this.#a,t)}#o=L({});get state(){return U(this.#o)}set state(t){T(this.#o,t)}#s=L(-1);get status(){return U(this.#s)}set status(t){T(this.#s,t)}#i=L(new URL(ze));get url(){return U(this.#i)}set url(t){T(this.#i,t)}},H=new class{#e=L(null);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},_e=new class{#e=L(!1);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},et.v=()=>_e.current=!0);function Dt(e){Object.assign(k,e)}const qt=new Set(["icon","shortcut icon","apple-touch-icon"]);let M=null;const C=We(He)??{},J=We(Ye)??{},$={url:Be({}),page:Be({}),navigating:Ee(null),updated:Pt()};function Te(e){C[e]=D()}function Vt(e,t){let n=e+1;for(;C[n];)delete C[n],n+=1;for(n=t+1;J[n];)delete J[n],n+=1}function X(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(()=>{})}async function nt(){if("serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration(x||"/");e&&await e.update()}}function Ke(){}let Ie,we,re,I,ye,y;const ae=[],oe=[];let A=null;function be(){A?.fork?.then(e=>e?.discard()),A=null}const ee=new Map,rt=new Set,Bt=new Set,W=new Set;let m={branch:[],error:null,url:null},at=!1,se=!1,Me=!0,Q=!1,F=!1,ot=!1,Oe=!1,st,w,R,N;const ie=new Set,Fe=new Map;async function dn(e,t,n){globalThis.__sveltekit_1gh8pzr?.data&&globalThis.__sveltekit_1gh8pzr.data,document.URL!==location.href&&(location.href=location.href),y=e,await e.hooks.init?.(),Ie=Ut(e),I=document.documentElement,ye=t,we=e.nodes[0],re=e.nodes[1],we(),re(),w=history.state?.[V],R=history.state?.[Y],w||(w=R=Date.now(),history.replaceState({...history.state,[V]:w,[Y]:R},""));const r=C[w];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await tn(ye,n)):(await B({type:"enter",url:Xe(y.hash?an(new URL(location.href)):location.href),replace_state:!0}),a()),en()}function zt(){ae.length=0,Oe=!1}function it(e){oe.some(t=>t?.snapshot)&&(J[e]=oe.map(t=>t?.snapshot?.capture()))}function lt(e){J[e]?.forEach((t,n)=>{oe[n]?.snapshot?.restore(t)})}function Ge(){Te(w),qe(He,C),it(R),qe(Ye,J)}async function Kt(e,t,n,r){let a;t.invalidateAll&&be(),await B({type:"goto",url:Xe(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:n,nav_token:r,accept:()=>{t.invalidateAll&&(Oe=!0,a=[...Fe.keys()]),t.invalidate&&t.invalidate.forEach(Zt)}}),t.invalidateAll&&te().then(te).then(()=>{Fe.forEach(({resource:i},o)=>{a?.includes(o)&&i.refresh?.()})})}async function Mt(e){if(e.id!==A?.id){be();const t={};ie.add(t),A={id:e.id,token:t,promise:ut({...e,preload:t}).then(n=>(ie.delete(t),n.type==="loaded"&&n.state.error&&be(),n)),fork:null}}return A.promise}async function me(e){const t=(await fe(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(n=>n[1]()))}async function ct(e,t,n){const r={params:m.params,route:{id:m.route?.id??null},url:new URL(location.href)};m={...e.state,nav:r};const a=document.querySelector("style[data-sveltekit]");if(a&&a.remove(),Object.assign(k,e.props.page),st=new y.root({target:t,props:{...e.props,stores:$,components:oe},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),lt(R),n){const i={from:null,to:{...r,scroll:C[w]??D()},willUnload:!1,type:"enter",complete:Promise.resolve()};W.forEach(o=>o(i))}se=!0}async function le({url:e,params:t,branch:n,errors:r,status:a,error:i,route:o,form:s}){let l="never";if(x&&(e.pathname===x||e.pathname===x+"/"))l="always";else for(const u of n)u?.slash!==void 0&&(l=u.slash);e.pathname=_t(e.pathname,l),e.search=e.search;const c={type:"loaded",state:{url:e,params:t,branch:n,error:i,route:o},props:{constructors:Ct(n).map(u=>u.node.component),page:Ne(k)}};s!==void 0&&(c.props.form=s);let f={},p=!k,v=0;for(let u=0;u<Math.max(n.length,m.branch.length);u+=1){const _=n[u],g=m.branch[u];_?.data!==g?.data&&(p=!0),_&&(f={...f,..._.data},p&&(c.props[`data_${v}`]=f),v+=1)}return(!m.url||e.href!==m.url.href||m.error!==i||s!==void 0&&s!==k.form||p)&&(c.props.page={error:i,params:t,route:{id:o?.id??null},state:{},status:a,url:new URL(e),form:s??null,data:p?f:k.data}),c}async function Pe({loader:e,parent:t,url:n,params:r,route:a,server_data_node:i}){let o=null;const s={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();return{node:l,loader:e,server:i,universal:l.universal?.load?{type:"data",data:o,uses:s}:null,data:o??i?.data??null,slash:l.universal?.trailingSlash??i?.slash}}function Ft(e,t,n){let r=e instanceof Request?e.url:e;const a=new URL(r,n);a.origin===n.origin&&(r=a.href.slice(n.origin.length));const i=se?Et(r,a.href,t):kt(r,t);return{resolved:a,promise:i}}function Gt(e,t,n,r,a,i){if(Oe)return!0;if(!a)return!1;if(a.parent&&e||a.route&&t||a.url&&n)return!0;for(const o of a.search_params)if(r.has(o))return!0;for(const o of a.params)if(i[o]!==m.params[o])return!0;for(const o of a.dependencies)if(ae.some(s=>s(new URL(o))))return!0;return!1}function $e(e,t){return e?.type==="data"?e:e?.type==="skip"?t??null:null}function Wt(e,t){if(!e)return new Set(t.searchParams.keys());const n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(const r of n){const a=e.searchParams.getAll(r),i=t.searchParams.getAll(r);a.every(o=>i.includes(o))&&i.every(o=>a.includes(o))&&n.delete(r)}return n}function Yt({error:e,url:t,route:n,params:r}){return{type:"loaded",state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:Ne(k),constructors:[]}}}async function ut({id:e,invalidating:t,url:n,params:r,route:a,preload:i}){if(A?.id===e)return ie.delete(A.token),A.promise;const{errors:o,layouts:s,leaf:l}=a,c=[...s,l];o.forEach(g=>g?.().catch(()=>{})),c.forEach(g=>g?.[1]().catch(()=>{}));const f=m.url?e!==ce(m.url):!1,p=m.route?a.id!==m.route.id:!1,v=Wt(m.url,n);let h=!1;const u=c.map(async(g,d)=>{if(!g)return;const E=m.branch[d];return g[1]===E?.loader&&!Gt(h,p,f,v,E.universal?.uses,r)?E:(h=!0,Pe({loader:g[1],url:n,params:r,route:a,parent:async()=>{const O={};for(let P=0;P<d;P+=1)Object.assign(O,(await u[P])?.data);return O},server_data_node:$e(g[0]?{type:"skip"}:null,g[0]?E?.server:void 0)}))});for(const g of u)g.catch(()=>{});const _=[];for(let g=0;g<c.length;g+=1)if(c[g])try{_.push(await u[g])}catch(d){if(d instanceof Re)return{type:"redirect",location:d.location};if(ie.has(i))return Yt({error:await Z(d,{params:r,url:n,route:{id:a.id}}),url:n,params:r,route:a});let E=Ue(d),S;if(d instanceof Se)S=d.body;else{if(await $.updated.check())return await nt(),await X(n);S=await Z(d,{params:r,url:n,route:{id:a.id}})}const O=await Ht(g,_,o);return O?le({url:n,params:r,branch:_.slice(0,O.idx).concat(O.node),errors:o,status:E,error:S,route:a}):await dt(n,{id:a.id},S,E)}else _.push(void 0);return le({url:n,params:r,branch:_,errors:o,status:200,error:null,route:a,form:t?void 0:null})}async function Ht(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)r-=1;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function Ce({status:e,error:t,url:n,route:r}){const a={};let i=null;try{const o=await Pe({loader:we,url:n,params:a,route:r,parent:()=>Promise.resolve({}),server_data_node:$e(i)}),s={node:await re(),loader:re,universal:null,server:null,data:null};return le({url:n,params:a,branch:[o,s],status:e,error:t,errors:[],route:null})}catch(o){if(o instanceof Re)return Kt(new URL(o.location,location.href),{},0);throw o}}async function Jt(e){const t=e.href;if(ee.has(t))return ee.get(t);let n;try{const r=(async()=>{let a=await y.hooks.reroute({url:new URL(e),fetch:async(i,o)=>Ft(i,o,e).promise})??e;if(typeof a=="string"){const i=new URL(e);y.hash?i.hash=a:i.pathname=a,a=i}return a})();ee.set(t,r),n=await r}catch{ee.delete(t);return}return n}async function fe(e,t){if(e&&!ue(e,x,y.hash)){const n=await Jt(e);if(!n)return;const r=Xt(n);for(const a of Ie){const i=a.exec(r);if(i)return{id:ce(e),invalidating:t,route:a,params:vt(i),url:e}}}}function Xt(e){return mt(y.hash?e.hash.replace(/^#/,"").replace(/[?#].+/,""):e.pathname.slice(x.length))||"/"}function ce(e){return(y.hash?e.hash.replace(/^#/,""):e.pathname)+e.search}function ft({url:e,type:t,intent:n,delta:r,event:a,scroll:i}){let o=!1;const s=je(m,n,e,t,i??null);r!==void 0&&(s.navigation.delta=r),a!==void 0&&(s.navigation.event=a);const l={...s.navigation,cancel:()=>{o=!0,s.reject(new Error("navigation cancelled"))}};return Q||rt.forEach(c=>c(l)),o?null:s}async function B({type:e,url:t,popped:n,keepfocus:r,noscroll:a,replace_state:i,state:o={},redirect_count:s=0,nav_token:l={},accept:c=Ke,block:f=Ke,event:p}){const v=N;N=l;const h=await fe(t,!1),u=e==="enter"?je(m,h,t,e):ft({url:t,type:e,delta:n?.delta,intent:h,scroll:n?.scroll,event:p});if(!u){f(),N===l&&(N=v);return}const _=w,g=R;c(),Q=!0,se&&u.navigation.type!=="enter"&&$.navigating.set(H.current=u.navigation);let d=h&&await ut(h);if(!d){if(ue(t,x,y.hash))return await X(t,i);d=await dt(t,{id:null},await Z(new xe(404,"Not Found",`Not found: ${t.pathname}`),{url:t,params:{},route:{id:null}}),404,i)}if(t=h?.url||t,N!==l)return u.reject(new Error("navigation aborted")),!1;if(d.type==="redirect"){if(s<20){await B({type:e,url:new URL(d.location,t),popped:n,keepfocus:r,noscroll:a,replace_state:i,state:o,redirect_count:s+1,nav_token:l}),u.fulfil(void 0);return}d=await Ce({status:500,error:await Z(new Error("Redirect loop"),{url:t,params:{},route:{id:null}}),url:t,route:{id:null}})}else d.props.page.status>=400&&await $.updated.check()&&(await nt(),await X(t,i));if(zt(),Te(_),it(g),d.props.page.url.pathname!==t.pathname&&(t.pathname=d.props.page.url.pathname),o=n?n.state:o,!n){const b=i?0:1,z={[V]:w+=b,[Y]:R+=b,[Je]:o};(i?history.replaceState:history.pushState).call(history,z,"",t),i||Vt(w,R)}const E=h&&A?.id===h.id?A.fork:null;A=null,d.props.page.state=o;let S;if(se){const b=(await Promise.all(Array.from(Bt,K=>K(u.navigation)))).filter(K=>typeof K=="function");if(b.length>0){let K=function(){b.forEach(he=>{W.delete(he)})};b.push(K),b.forEach(he=>{W.add(he)})}const z=u.navigation.to;m={...d.state,nav:{params:z.params,route:z.route,url:z.url}},d.props.page&&(d.props.page.url=t);const de=E&&await E;de?S=de.commit():(M=null,st.$set(d.props),M&&Object.assign(d.props.page,M),Dt(d.props.page),S=gt?.()),ot=!0}else await ct(d,ye,!1);const{activeElement:O}=document;await S,await te(),await te();let P=null;if(Me){const b=n?n.scroll:a?D():null;b?scrollTo(b.x,b.y):(P=t.hash&&document.getElementById(ht(t)))?P.scrollIntoView():scrollTo(0,0)}const pt=document.activeElement!==O&&document.activeElement!==document.body;!r&&!pt&&rn(t,!P),Me=!0,d.props.page&&(M&&Object.assign(d.props.page,M),Object.assign(k,d.props.page)),Q=!1,e==="popstate"&&lt(R),u.fulfil(void 0),u.navigation.to&&(u.navigation.to.scroll=D()),W.forEach(b=>b(u.navigation)),$.navigating.set(H.current=null)}async function dt(e,t,n,r,a){return e.origin===Le&&e.pathname===location.pathname&&!at?await Ce({status:r,error:n,url:e,route:t}):await X(e,a)}function Qt(){let e,t={element:void 0,href:void 0},n;I.addEventListener("mousemove",s=>{const l=s.target;clearTimeout(e),e=setTimeout(()=>{i(l,j.hover)},20)});function r(s){s.defaultPrevented||i(s.composedPath()[0],j.tap)}I.addEventListener("mousedown",r),I.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(s=>{for(const l of s)l.isIntersecting&&(me(new URL(l.target.href)),a.unobserve(l.target))},{threshold:0});async function i(s,l){const c=Ze(s,I),f=c===t.element&&c?.href===t.href&&l>=n;if(!c||f)return;const{url:p,external:v,download:h}=ve(c,x,y.hash);if(v||h)return;const u=ne(c),_=p&&ce(m.url)===ce(p);if(!(u.reload||_))if(l<=u.preload_data){t={element:c,href:c.href},n=j.tap;const g=await fe(p,!1);if(!g)return;Mt(g)}else l<=u.preload_code&&(t={element:c,href:c.href},n=l,me(p))}function o(){a.disconnect();for(const s of I.querySelectorAll("a")){const{url:l,external:c,download:f}=ve(s,x,y.hash);if(c||f)continue;const p=ne(s);p.reload||(p.preload_code===j.viewport&&a.observe(s),p.preload_code===j.eager&&me(l))}}W.add(o),o()}function Z(e,t){if(e instanceof Se)return e.body;const n=Ue(e),r=jt(e);return y.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function Zt(e){if(typeof e=="function")ae.push(e);else{const{href:t}=new URL(e,location.href);ae.push(n=>n.href===t)}}function en(){history.scrollRestoration="manual",addEventListener("beforeunload",t=>{let n=!1;if(Ge(),!Q){const r=je(m,void 0,null,"leave"),a={...r.navigation,cancel:()=>{n=!0,r.reject(new Error("navigation cancelled"))}};rt.forEach(i=>i(a))}n?(t.preventDefault(),t.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Ge()}),navigator.connection?.saveData||Qt(),I.addEventListener("click",async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;const n=Ze(t.composedPath()[0],I);if(!n)return;const{url:r,external:a,target:i,download:o}=ve(n,x,y.hash);if(!r)return;if(i==="_parent"||i==="_top"){if(window.parent!==window)return}else if(i&&i!=="_self")return;const s=ne(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&!(r.protocol==="https:"||r.protocol==="http:")||o)return;const[c,f]=(y.hash?r.hash.replace(/^#/,""):r.href).split("#"),p=c===pe(location);if(a||s.reload&&(!p||!f)){ft({url:r,type:"link",event:t})?Q=!0:t.preventDefault();return}if(f!==void 0&&p){const[,v]=m.url.href.split("#");if(v===f){if(t.preventDefault(),f===""||f==="top"&&n.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=n.ownerDocument.getElementById(decodeURIComponent(f));h&&(h.scrollIntoView(),h.focus())}return}if(F=!0,Te(w),e(r),!s.replace_state)return;F=!1}t.preventDefault(),await new Promise(v=>{requestAnimationFrame(()=>{setTimeout(v,0)}),setTimeout(v,100)}),await B({type:"link",url:r,keepfocus:s.keepfocus,noscroll:s.noscroll,replace_state:s.replace_state??r.href===location.href,event:t})}),I.addEventListener("submit",t=>{if(t.defaultPrevented)return;const n=HTMLFormElement.prototype.cloneNode.call(t.target),r=t.submitter;if((r?.formTarget||n.target)==="_blank"||(r?.formMethod||n.method)!=="get")return;const o=new URL(r?.hasAttribute("formaction")&&r?.formAction||n.action);if(ue(o,x,!1))return;const s=t.target,l=ne(s);if(l.reload)return;t.preventDefault(),t.stopPropagation();const c=new FormData(s,r);o.search=new URLSearchParams(c).toString(),B({type:"form",url:o,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??o.href===location.href,event:t})}),addEventListener("popstate",async t=>{if(!ke){if(t.state?.[V]){const n=t.state[V];if(N={},n===w)return;const r=C[n],a=t.state[Je]??{},i=new URL(t.state[Ot]??location.href),o=t.state[Y],s=m.url?pe(location)===pe(m.url):!1;if(o===R&&(ot||s)){a!==k.state&&(k.state=a),e(i),C[w]=D(),r&&scrollTo(r.x,r.y),w=n;return}const c=n-w;await B({type:"popstate",url:i,popped:{state:a,scroll:r,delta:c},accept:()=>{w=n,R=o},block:()=>{history.go(-c)},nav_token:N,event:t})}else if(!F){const n=new URL(location.href);e(n),y.hash&&location.reload()}}}),addEventListener("hashchange",()=>{F&&(F=!1,history.replaceState({...history.state,[V]:++w,[Y]:R},"",location.href))});for(const t of document.querySelectorAll("link"))qt.has(t.rel)&&(t.href=t.href);addEventListener("pageshow",t=>{t.persisted&&$.navigating.set(H.current=null)});function e(t){m.url=k.url=t,$.page.set(Ne(k)),$.page.notify()}}async function tn(e,{status:t=200,error:n,node_ids:r,params:a,route:i,server_route:o,data:s,form:l}){at=!0;const c=new URL(location.href);let f;({params:a={},route:i={id:null}}=await fe(c,!1)||{}),f=Ie.find(({id:h})=>h===i.id);let p,v=!0;try{const h=r.map(async(_,g)=>{const d=s[g];return d?.uses&&(d.uses=nn(d.uses)),Pe({loader:y.nodes[_],url:c,params:a,route:i,parent:async()=>{const E={};for(let S=0;S<g;S+=1)Object.assign(E,(await h[S]).data);return E},server_data_node:$e(d)})}),u=await Promise.all(h);if(f){const _=f.layouts;for(let g=0;g<_.length;g++)_[g]||u.splice(g,0,void 0)}p=await le({url:c,params:a,branch:u,status:t,error:n,errors:f?.errors,form:l,route:f??null})}catch(h){if(h instanceof Re){await X(new URL(h.location,location.href));return}p=await Ce({status:Ue(h),error:await Z(h,{url:c,params:a,route:i}),url:c,route:i}),e.textContent="",v=!1}p.props.page&&(p.props.page.state={}),await ct(p,e,v)}function nn(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}let ke=!1;function rn(e,t=!0){const n=document.querySelector("[autofocus]");if(n)n.focus();else{const r=ht(e);if(r&&document.getElementById(r)){const{x:i,y:o}=D();setTimeout(()=>{const s=history.state;ke=!0,location.replace(new URL(`#${r}`,location.href)),history.replaceState(s,"",e),t&&scrollTo(i,o),ke=!1})}else{const i=document.body,o=i.getAttribute("tabindex");i.tabIndex=-1,i.focus({preventScroll:!0,focusVisible:!1}),o!==null?i.setAttribute("tabindex",o):i.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const i=[];for(let o=0;o<a.rangeCount;o+=1)i.push(a.getRangeAt(o));setTimeout(()=>{if(a.rangeCount===i.length){for(let o=0;o<a.rangeCount;o+=1){const s=i[o],l=a.getRangeAt(o);if(s.commonAncestorContainer!==l.commonAncestorContainer||s.startContainer!==l.startContainer||s.endContainer!==l.endContainer||s.startOffset!==l.startOffset||s.endOffset!==l.endOffset)return}a.removeAllRanges()}})}}}function je(e,t,n,r,a=null){let i,o;const s=new Promise((c,f)=>{i=c,o=f});return s.catch(()=>{}),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:D()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:a},willUnload:!t,type:r,complete:s},fulfil:i,reject:o}}function Ne(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function an(e){const t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function ht(e){let t;if(y.hash){const[,,n]=e.hash.split("#",3);t=n??""}else t=e.hash.slice(1);return decodeURIComponent(t)}export{dn as a,ln as l,k as p,$ as s};
-1
build/_app/immutable/chunks/C6hdjiAW.js
··· 1 - import{o as h,v as B,w as N,t as b,x as A,D as Y,S as w,y as x,z as M,P as y,A as o,B as G,C as U,F as q,G as z,H as C,q as $,I as F,J as H,K as J,L as K,M as Z,N as j}from"./w0kPbzMq.js";let I=!1;function Q(r){var e=I;try{return I=!1,[r(),I]}finally{I=e}}function R(r,e){return r===e||r?.[w]===e}function W(r={},e,t,v){var f=h.r,u=A;return B(()=>{var d,a;return N(()=>{d=a,a=[],b(()=>{r!==t(...a)&&(e(r,...a),d&&R(t(...d),r)&&e(null,...d))})}),()=>{let i=u;for(;i!==f&&i.parent!==null&&i.parent.f&Y;)i=i.parent;const S=()=>{a&&R(t(...a),r)&&e(null,...a)},s=i.teardown;i.teardown=()=>{S(),s?.()}}}),r}function X(r,e,t,v){var f=!$||(t&F)!==0,u=(t&C)!==0,d=(t&Z)!==0,a=v,i=!0,S=()=>(i&&(i=!1,a=d?b(v):v),a);let s;if(u){var D=w in r||j in r;s=x(r,e)?.set??(D&&e in r?n=>r[e]=n:void 0)}var l,E=!1;u?[l,E]=Q(()=>r[e]):l=r[e],l===void 0&&v!==void 0&&(l=S(),s&&(f&&M(),s(l)));var _;if(f?_=()=>{var n=r[e];return n===void 0?S():(i=!0,n)}:_=()=>{var n=r[e];return n!==void 0&&(a=void 0),n===void 0?a:n},f&&(t&y)===0)return _;if(s){var L=r.$$legacy;return(function(n,P){return arguments.length>0?((!f||!P||L||E)&&s(P?_():n),n):_()})}var g=!1,c=((t&H)!==0?J:K)(()=>(g=!1,_()));u&&o(c);var T=A;return(function(n,P){if(arguments.length>0){const O=P?o(c):f&&u?G(n):n;return U(c,O),g=!0,a!==void 0&&(a=O),n}return q&&g||(T.f&z)!==0?c.v:o(c)})}export{W as b,X as p};
+1
build/_app/immutable/chunks/CFYBLbZM.js
··· 1 + import{d as l,f as o,p as u,g as n,h as d,i as m,j as p,k as _,m as v,s as k}from"./CkzjbUDB.js";class w{anchor;#t=new Map;#s=new Map;#e=new Map;#i=new Set;#f=!0;constructor(t,s=!0){this.anchor=t,this.#f=s}#a=t=>{if(this.#t.has(t)){var s=this.#t.get(t),e=this.#s.get(s);if(e)l(e),this.#i.delete(s);else{var f=this.#e.get(s);f&&(this.#s.set(s,f.effect),this.#e.delete(s),f.fragment.lastChild.remove(),this.anchor.before(f.fragment),e=f.effect)}for(const[i,a]of this.#t){if(this.#t.delete(i),i===t)break;const r=this.#e.get(a);r&&(o(r.effect),this.#e.delete(a))}for(const[i,a]of this.#s){if(i===s||this.#i.has(i))continue;const r=()=>{if(Array.from(this.#t.values()).includes(i)){var c=document.createDocumentFragment();v(a,c),c.append(n()),this.#e.set(i,{effect:a,fragment:c})}else o(a);this.#i.delete(i),this.#s.delete(i)};this.#f||!e?(this.#i.add(i),u(a,r,!1)):r()}}};#r=t=>{this.#t.delete(t);const s=Array.from(this.#t.values());for(const[e,f]of this.#e)s.includes(e)||(o(f.effect),this.#e.delete(e))};ensure(t,s){var e=m,f=k();if(s&&!this.#s.has(t)&&!this.#e.has(t))if(f){var i=document.createDocumentFragment(),a=n();i.append(a),this.#e.set(t,{effect:d(()=>s(a)),fragment:i})}else this.#s.set(t,d(()=>s(this.anchor)));if(this.#t.set(e,t),f){for(const[r,h]of this.#s)r===t?e.unskip_effect(h):e.skip_effect(h);for(const[r,h]of this.#e)r===t?e.unskip_effect(h.effect):e.skip_effect(h.effect);e.oncommit(this.#a),e.ondiscard(this.#r)}else p&&(this.anchor=_),this.#a(e)}}export{w as B};
-1
build/_app/immutable/chunks/C_B-Ij-b.js
··· 1 - import{r as v,d as c,p as b,c as u,b as _,a as g,h as o,f as m,m as k,s as y,g as w,i as A,E,j as F,k as M,l as x,n as p}from"./w0kPbzMq.js";class T{anchor;#t=new Map;#s=new Map;#e=new Map;#a=new Set;#i=!0;constructor(t,s=!0){this.anchor=t,this.#i=s}#r=t=>{if(this.#t.has(t)){var s=this.#t.get(t),e=this.#s.get(s);if(e)v(e),this.#a.delete(s);else{var r=this.#e.get(s);r&&(this.#s.set(s,r.effect),this.#e.delete(s),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),e=r.effect)}for(const[i,f]of this.#t){if(this.#t.delete(i),i===t)break;const a=this.#e.get(f);a&&(c(a.effect),this.#e.delete(f))}for(const[i,f]of this.#s){if(i===s||this.#a.has(i))continue;const a=()=>{if(Array.from(this.#t.values()).includes(i)){var h=document.createDocumentFragment();k(f,h),h.append(u()),this.#e.set(i,{effect:f,fragment:h})}else c(f);this.#a.delete(i),this.#s.delete(i)};this.#i||!e?(this.#a.add(i),b(f,a,!1)):a()}}};#f=t=>{this.#t.delete(t);const s=Array.from(this.#t.values());for(const[e,r]of this.#e)s.includes(e)||(c(r.effect),this.#e.delete(e))};ensure(t,s){var e=g,r=y();if(s&&!this.#s.has(t)&&!this.#e.has(t))if(r){var i=document.createDocumentFragment(),f=u();i.append(f),this.#e.set(t,{effect:_(()=>s(f)),fragment:i})}else this.#s.set(t,_(()=>s(this.anchor)));if(this.#t.set(e,t),r){for(const[a,n]of this.#s)a===t?e.unskip_effect(n):e.skip_effect(n);for(const[a,n]of this.#e)a===t?e.unskip_effect(n.effect):e.skip_effect(n.effect);e.oncommit(this.#r),e.ondiscard(this.#f)}else o&&(this.anchor=m),this.#r(e)}}function C(d,t,s=!1){var e;o&&(e=m,A());var r=new T(d),i=s?E:0;function f(a,n){if(o){var h=F(e);if(a!==parseInt(h.substring(1))){var l=M();x(l),r.anchor=l,p(!1),r.ensure(a,n),p(!0);return}}r.ensure(a,n)}w(()=>{var a=!1;t((n,h=0)=>{a=!0,f(h,n)}),a||f(-1,null)},i)}export{T as B,C as i};
+1
build/_app/immutable/chunks/CkzjbUDB.js
··· 1 + var Ht=Array.isArray,Ut=Array.prototype.indexOf,ie=Array.prototype.includes,Cn=Array.from,Mn=Object.defineProperty,ve=Object.getOwnPropertyDescriptor,Vt=Object.getOwnPropertyDescriptors,Bt=Object.prototype,zt=Array.prototype,it=Object.getPrototypeOf,Qe=Object.isExtensible;const Gt=()=>{};function Fn(e){return e()}function Kt(e){for(var t=0;t<e.length;t++)e[t]()}function ft(){var e,t,n=new Promise((r,s)=>{e=r,t=s});return{promise:n,resolve:e,reject:t}}const E=2,Q=4,we=8,ut=1<<24,q=16,F=32,ee=64,$t=128,k=512,g=1024,b=2048,j=4096,P=8192,C=16384,le=32768,et=1<<25,Ae=65536,Me=1<<17,Xt=1<<18,ye=1<<19,ot=1<<20,jn=1<<25,te=65536,Fe=1<<21,Oe=1<<22,B=1<<23,de=Symbol("$state"),Ln=Symbol("legacy props"),Yn=Symbol(""),Y=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Hn=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),Ne=3,ct=8;function Zt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Un(e,t,n){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Wt(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Jt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Qt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function en(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Vn(){throw new Error("https://svelte.dev/e/hydration_failed")}function Bn(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function tn(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function nn(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function rn(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function zn(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Gn=1,Kn=2,$n=16,Xn=1,Zn=2,Wn=4,Jn=8,Qn=16,er=1,tr=2,sn="[",ln="[!",nr="[?",an="]",Ue={},m=Symbol(),fn="http://www.w3.org/1999/xhtml";function Ve(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function rr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let ne=!1;function sr(e){ne=e}let S;function fe(e){if(e===null)throw Ve(),Ue;return S=e}function lr(){return fe($(S))}function ar(e){if(ne){if($(S)!==null)throw Ve(),Ue;S=e}}function ir(e=1){if(ne){for(var t=e,n=S;t--;)n=$(n);S=n}}function fr(e=!0){for(var t=0,n=S;;){if(n.nodeType===ct){var r=n.data;if(r===an){if(t===0)return n;t-=1}else(r===sn||r===ln||r[0]==="["&&!isNaN(Number(r.slice(1))))&&(t+=1)}var s=$(n);e&&n.remove(),n=s}}function ur(e){if(!e||e.nodeType!==ct)throw Ve(),Ue;return e.data}function _t(e){return e===this.v}function un(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function vt(e){return!un(e,this.v)}let De=!1;function or(){De=!0}let T=null;function Se(e){T=e}function cr(e,t=!1,n){T={p:T,i:!1,c:null,e:null,s:e,x:null,r:d,l:De&&!t?{s:null,u:null,$:[]}:null}}function _r(e){var t=T,n=t.e;if(n!==null){t.e=null;for(var r of n)Ot(r)}return t.i=!0,T=t.p,{}}function ge(){return!De||T!==null&&T.l===null}let X=[];function dt(){var e=X;X=[],Kt(e)}function tt(e){if(X.length===0&&!he){var t=X;queueMicrotask(()=>{t===X&&dt()})}X.push(e)}function on(){for(;X.length>0;)dt()}function cn(e){var t=d;if(t===null)return v.f|=B,e;if((t.f&le)===0&&(t.f&Q)===0)throw e;Re(e,t)}function Re(e,t){for(;t!==null;){if((t.f&$t)!==0){if((t.f&le)===0)throw e;try{t.b.error(e);return}catch(n){e=n}}t=t.parent}throw e}const _n=-7169;function y(e,t){e.f=e.f&_n|t}function Be(e){(e.f&k)!==0||e.deps===null?y(e,g):y(e,j)}function ht(e){if(e!==null)for(const t of e)(t.f&E)===0||(t.f&te)===0||(t.f^=te,ht(t.deps))}function vn(e,t,n){(e.f&b)!==0?t.add(e):(e.f&j)!==0&&n.add(e),ht(e.deps),y(e,g)}const H=new Set;let w=null,D=null,je=null,he=!1,Pe=!1,ae=null,be=null;var nt=0;let dn=1;class G{id=dn++;current=new Map;previous=new Map;#i=new Set;#f=new Set;#r=new Map;#t=new Map;#_=null;#e=[];#v=[];#l=new Set;#s=new Set;#n=new Map;is_fork=!1;#u=!1;#a=new Set;#o(){return this.is_fork||this.#t.size>0}#p(){for(const r of this.#a)for(const s of r.#t.keys()){for(var t=!1,n=s;n.parent!==null;){if(this.#n.has(n)){t=!0;break}n=n.parent}if(!t)return!0}return!1}skip_effect(t){this.#n.has(t)||this.#n.set(t,{d:[],m:[]})}unskip_effect(t){var n=this.#n.get(t);if(n){this.#n.delete(t);for(var r of n.d)y(r,b),this.schedule(r);for(r of n.m)y(r,j),this.schedule(r)}}#c(){if(nt++>1e3&&(H.delete(this),pn()),!this.#o()){for(const a of this.#l)this.#s.delete(a),y(a,b),this.schedule(a);for(const a of this.#s)y(a,j),this.schedule(a)}const t=this.#e;this.#e=[],this.apply();var n=ae=[],r=[],s=be=[];for(const a of t)try{this.#d(a,n,r)}catch(i){throw yt(a),i}if(w=null,s.length>0){var l=G.ensure();for(const a of s)l.schedule(a)}if(ae=null,be=null,this.#o()||this.#p()){this.#h(r),this.#h(n);for(const[a,i]of this.#n)wt(a,i)}else{this.#r.size===0&&H.delete(this),this.#l.clear(),this.#s.clear();for(const a of this.#i)a(this);this.#i.clear(),rt(r),rt(n),this.#_?.resolve()}var u=w;if(this.#e.length>0){const a=u??=this;a.#e.push(...this.#e.filter(i=>!a.#e.includes(i)))}u!==null&&(H.add(u),u.#c()),H.has(this)||this.#w()}#d(t,n,r){t.f^=g;for(var s=t.first;s!==null;){var l=s.f,u=(l&(F|ee))!==0,a=u&&(l&g)!==0,i=a||(l&P)!==0||this.#n.has(s);if(!i&&s.fn!==null){u?s.f^=g:(l&Q)!==0?n.push(s):Ee(s)&&((l&q)!==0&&this.#s.add(s),oe(s));var o=s.first;if(o!==null){s=o;continue}}for(;s!==null;){var f=s.next;if(f!==null){s=f;break}s=s.parent}}}#h(t){for(var n=0;n<t.length;n+=1)vn(t[n],this.#l,this.#s)}capture(t,n,r=!1){n!==m&&!this.previous.has(t)&&this.previous.set(t,n),(t.f&B)===0&&(this.current.set(t,[t.v,r]),D?.set(t,t.v))}activate(){w=this}deactivate(){w=null,D=null}flush(){try{Pe=!0,w=this,this.#c()}finally{nt=0,je=null,ae=null,be=null,Pe=!1,w=null,D=null,z.clear()}}discard(){for(const t of this.#f)t(this);this.#f.clear(),H.delete(this)}register_created_effect(t){this.#v.push(t)}#w(){for(const f of H){var t=f.id<this.id,n=[];for(const[c,[_,p]]of this.current){if(f.current.has(c)){var r=f.current.get(c)[0];if(t&&_!==r)f.current.set(c,[_,p]);else continue}n.push(c)}var s=[...f.current.keys()].filter(c=>!this.current.has(c));if(s.length===0)t&&f.discard();else if(n.length>0){f.activate();var l=new Set,u=new Map;for(var a of n)pt(a,s,l,u);u=new Map;var i=[...f.current.keys()].filter(c=>this.current.has(c)?this.current.get(c)[0]!==c:!0);for(const c of this.#v)(c.f&(C|P|Me))===0&&ze(c,i,u)&&((c.f&(Oe|q))!==0?(y(c,b),f.schedule(c)):f.#l.add(c));if(f.#e.length>0){f.apply();for(var o of f.#e)f.#d(o,[],[]);f.#e=[]}f.deactivate()}}for(const f of H)f.#a.has(this)&&(f.#a.delete(this),f.#a.size===0&&!f.#o()&&(f.activate(),f.#c()))}increment(t,n){let r=this.#r.get(n)??0;if(this.#r.set(n,r+1),t){let s=this.#t.get(n)??0;this.#t.set(n,s+1)}}decrement(t,n,r){let s=this.#r.get(n)??0;if(s===1?this.#r.delete(n):this.#r.set(n,s-1),t){let l=this.#t.get(n)??0;l===1?this.#t.delete(n):this.#t.set(n,l-1)}this.#u||r||(this.#u=!0,tt(()=>{this.#u=!1,this.flush()}))}transfer_effects(t,n){for(const r of t)this.#l.add(r);for(const r of n)this.#s.add(r);t.clear(),n.clear()}oncommit(t){this.#i.add(t)}ondiscard(t){this.#f.add(t)}settled(){return(this.#_??=ft()).promise}static ensure(){if(w===null){const t=w=new G;Pe||(H.add(w),he||tt(()=>{w===t&&t.flush()}))}return w}apply(){{D=null;return}}schedule(t){if(je=t,t.b?.is_pending&&(t.f&(Q|we|ut))!==0&&(t.f&le)===0){t.b.defer_effect(t);return}for(var n=t;n.parent!==null;){n=n.parent;var r=n.f;if(ae!==null&&n===d&&(v===null||(v.f&E)===0))return;if((r&(ee|F))!==0){if((r&g)===0)return;n.f^=g}}this.#e.push(n)}}function hn(e){var t=he;he=!0;try{for(var n;;){if(on(),w===null)return n;w.flush()}}finally{he=t}}function pn(){try{en()}catch(e){Re(e,je)}}let L=null;function rt(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if((r.f&(C|P))===0&&Ee(r)&&(L=new Set,oe(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&Dt(r),L?.size>0)){z.clear();for(const s of L){if((s.f&(C|P))!==0)continue;const l=[s];let u=s.parent;for(;u!==null;)L.has(u)&&(L.delete(u),l.push(u)),u=u.parent;for(let a=l.length-1;a>=0;a--){const i=l[a];(i.f&(C|P))===0&&oe(i)}}L.clear()}}L=null}}function pt(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(const s of e.reactions){const l=s.f;(l&E)!==0?pt(s,t,n,r):(l&(Oe|q))!==0&&(l&b)===0&&ze(s,t,r)&&(y(s,b),Ge(s))}}function ze(e,t,n){const r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(ie.call(t,s))return!0;if((s.f&E)!==0&&ze(s,t,n))return n.set(s,!0),!0}return n.set(e,!1),!1}function Ge(e){w.schedule(e)}function wt(e,t){if(!((e.f&F)!==0&&(e.f&g)!==0)){(e.f&b)!==0?t.d.push(e):(e.f&j)!==0&&t.m.push(e),y(e,g);for(var n=e.first;n!==null;)wt(n,t),n=n.next}}function yt(e){y(e,g);for(var t=e.first;t!==null;)yt(t),t=t.next}function gt(e,t,n,r){const s=ge()?$e:gn;var l=e.filter(_=>!_.settled);if(n.length===0&&l.length===0){r(t.map(s));return}var u=d,a=wn(),i=l.length===1?l[0].promise:l.length>1?Promise.all(l.map(_=>_.promise)):null;function o(_){a();try{r(_)}catch(p){(u.f&C)===0&&Re(p,u)}xe()}if(n.length===0){i.then(()=>o(t.map(s)));return}var f=Ke();function c(){Promise.all(n.map(_=>yn(_))).then(_=>o([...t.map(s),..._])).catch(_=>Re(_,u)).finally(()=>f())}i?i.then(()=>{a(),c(),xe()}):c()}function wn(){var e=d,t=v,n=T,r=w;return function(l=!0){ue(e),K(t),Se(n),l&&(e.f&C)===0&&(r?.activate(),r?.apply())}}function xe(e=!0){ue(null),K(null),Se(null),e&&w?.deactivate()}function Ke(){var e=d,t=e.b,n=w,r=t.is_rendered();return t.update_pending_count(1,n),n.increment(r,e),(s=!1)=>{t.update_pending_count(-1,n),n.decrement(r,e,s)}}function $e(e){var t=E|b,n=v!==null&&(v.f&E)!==0?v:null;return d!==null&&(d.f|=ye),{ctx:T,deps:null,effects:null,equals:_t,f:t,fn:e,reactions:null,rv:0,v:m,wv:0,parent:n??d,ac:null}}function yn(e,t,n){let r=d;r===null&&Zt();var s=void 0,l=Ze(m),u=!v,a=new Map;return kn(()=>{var i=d,o=ft();s=o.promise;try{Promise.resolve(e()).then(o.resolve,o.reject).finally(xe)}catch(p){o.reject(p),xe()}var f=w;if(u){if((i.f&le)!==0)var c=Ke();if(r.b.is_rendered())a.get(f)?.reject(Y),a.delete(f);else{for(const p of a.values())p.reject(Y);a.clear()}a.set(f,o)}const _=(p,h=void 0)=>{if(c){var N=h===Y;c(N)}if(!(h===Y||(i.f&C)!==0)){if(f.activate(),h)l.f|=B,Ye(l,h);else{(l.f&B)!==0&&(l.f^=B),Ye(l,p);for(const[ce,me]of a){if(a.delete(ce),ce===f)break;me.reject(Y)}}f.deactivate()}};o.promise.then(_,p=>_(null,p||"unknown"))}),xn(()=>{for(const i of a.values())i.reject(Y)}),new Promise(i=>{function o(f){function c(){f===s?i(l):o(s)}f.then(c,c)}o(s)})}function vr(e){const t=$e(e);return Ct(t),t}function gn(e){const t=$e(e);return t.equals=vt,t}function En(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)re(t[n])}}function mn(e){for(var t=e.parent;t!==null;){if((t.f&E)===0)return(t.f&C)===0?t:null;t=t.parent}return null}function Xe(e){var t,n=d;ue(mn(e));try{e.f&=~te,En(e),t=Lt(e)}finally{ue(n)}return t}function Et(e){var t=e.v,n=Xe(e);if(!e.equals(n)&&(e.wv=Ft(),(!w?.is_fork||e.deps===null)&&(e.v=n,w?.capture(e,t,!0),e.deps===null))){y(e,g);return}se||(D!==null?(kt()||w?.is_fork)&&D.set(e,n):Be(e))}function bn(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac?.abort(Y),t.teardown=Gt,t.ac=null,pe(t,0),Je(t))}function mt(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&oe(t)}let Le=new Set;const z=new Map;let bt=!1;function Ze(e,t){var n={f:0,v:e,reactions:null,equals:_t,rv:0,wv:0};return n}function U(e,t){const n=Ze(e);return Ct(n),n}function dr(e,t=!1,n=!0){const r=Ze(e);return t||(r.equals=vt),De&&n&&T!==null&&T.l!==null&&(T.l.s??=[]).push(r),r}function V(e,t,n=!1){v!==null&&(!I||(v.f&Me)!==0)&&ge()&&(v.f&(E|q|Oe|Me))!==0&&(O===null||!ie.call(O,e))&&rn();let r=n?_e(t):t;return Ye(e,r,be)}function Ye(e,t,n=null){if(!e.equals(t)){var r=e.v;se?z.set(e,t):z.set(e,r),e.v=t;var s=G.ensure();if(s.capture(e,r),(e.f&E)!==0){const l=e;(e.f&b)!==0&&Xe(l),D===null&&Be(l)}e.wv=Ft(),Tt(e,b,n),ge()&&d!==null&&(d.f&g)!==0&&(d.f&(F|ee))===0&&(x===null?In([e]):x.push(e)),!s.is_fork&&Le.size>0&&!bt&&Tn()}return t}function Tn(){bt=!1;for(const e of Le)(e.f&g)!==0&&y(e,j),Ee(e)&&oe(e);Le.clear()}function hr(e,t=1){var n=W(e),r=t===1?n++:n--;return V(e,n),r}function Ce(e){V(e,e.v+1)}function Tt(e,t,n){var r=e.reactions;if(r!==null)for(var s=ge(),l=r.length,u=0;u<l;u++){var a=r[u],i=a.f;if(!(!s&&a===d)){var o=(i&b)===0;if(o&&y(a,t),(i&E)!==0){var f=a;D?.delete(f),(i&te)===0&&(i&k&&(a.f|=te),Tt(f,j,n))}else if(o){var c=a;(i&q)!==0&&L!==null&&L.add(c),n!==null?n.push(c):Ge(c)}}}}function _e(e){if(typeof e!="object"||e===null||de in e)return e;const t=it(e);if(t!==Bt&&t!==zt)return e;var n=new Map,r=Ht(e),s=U(0),l=J,u=a=>{if(J===l)return a();var i=v,o=J;K(null),at(l);var f=a();return K(i),at(o),f};return r&&n.set("length",U(e.length)),new Proxy(e,{defineProperty(a,i,o){(!("value"in o)||o.configurable===!1||o.enumerable===!1||o.writable===!1)&&tn();var f=n.get(i);return f===void 0?u(()=>{var c=U(o.value);return n.set(i,c),c}):V(f,o.value,!0),!0},deleteProperty(a,i){var o=n.get(i);if(o===void 0){if(i in a){const f=u(()=>U(m));n.set(i,f),Ce(s)}}else V(o,m),Ce(s);return!0},get(a,i,o){if(i===de)return e;var f=n.get(i),c=i in a;if(f===void 0&&(!c||ve(a,i)?.writable)&&(f=u(()=>{var p=_e(c?a[i]:m),h=U(p);return h}),n.set(i,f)),f!==void 0){var _=W(f);return _===m?void 0:_}return Reflect.get(a,i,o)},getOwnPropertyDescriptor(a,i){var o=Reflect.getOwnPropertyDescriptor(a,i);if(o&&"value"in o){var f=n.get(i);f&&(o.value=W(f))}else if(o===void 0){var c=n.get(i),_=c?.v;if(c!==void 0&&_!==m)return{enumerable:!0,configurable:!0,value:_,writable:!0}}return o},has(a,i){if(i===de)return!0;var o=n.get(i),f=o!==void 0&&o.v!==m||Reflect.has(a,i);if(o!==void 0||d!==null&&(!f||ve(a,i)?.writable)){o===void 0&&(o=u(()=>{var _=f?_e(a[i]):m,p=U(_);return p}),n.set(i,o));var c=W(o);if(c===m)return!1}return f},set(a,i,o,f){var c=n.get(i),_=i in a;if(r&&i==="length")for(var p=o;p<c.v;p+=1){var h=n.get(p+"");h!==void 0?V(h,m):p in a&&(h=u(()=>U(m)),n.set(p+"",h))}if(c===void 0)(!_||ve(a,i)?.writable)&&(c=u(()=>U(void 0)),V(c,_e(o)),n.set(i,c));else{_=c.v!==m;var N=u(()=>_e(o));V(c,N)}var ce=Reflect.getOwnPropertyDescriptor(a,i);if(ce?.set&&ce.set.call(f,o),!_){if(r&&typeof i=="string"){var me=n.get("length"),Ie=Number(i);Number.isInteger(Ie)&&Ie>=me.v&&V(me,Ie+1)}Ce(s)}return!0},ownKeys(a){W(s);var i=Reflect.ownKeys(a).filter(c=>{var _=n.get(c);return _===void 0||_.v!==m});for(var[o,f]of n)f.v!==m&&!(o in a)&&i.push(o);return i},setPrototypeOf(){nn()}})}var st,An,Sn,At,St;function pr(){if(st===void 0){st=window,An=document,Sn=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;At=ve(t,"firstChild").get,St=ve(t,"nextSibling").get,Qe(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),Qe(n)&&(n.__t=void 0)}}function ke(e=""){return document.createTextNode(e)}function qe(e){return At.call(e)}function $(e){return St.call(e)}function wr(e,t){if(!ne)return qe(e);var n=qe(S);if(n===null)n=S.appendChild(ke());else if(t&&n.nodeType!==Ne){var r=ke();return n?.before(r),fe(r),r}return t&&We(n),fe(n),n}function yr(e,t=!1){if(!ne){var n=qe(e);return n instanceof Comment&&n.data===""?$(n):n}if(t){if(S?.nodeType!==Ne){var r=ke();return S?.before(r),fe(r),r}We(S)}return S}function gr(e,t=1,n=!1){let r=ne?S:e;for(var s;t--;)s=r,r=$(r);if(!ne)return r;if(n){if(r?.nodeType!==Ne){var l=ke();return r===null?s?.after(l):r.before(l),fe(l),l}We(r)}return fe(r),r}function Er(e){e.textContent=""}function mr(){return!1}function br(e,t,n){return document.createElementNS(fn,e,void 0)}function We(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===Ne;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function Rt(e){var t=v,n=d;K(null),ue(null);try{return e()}finally{K(t),ue(n)}}function xt(e){d===null&&(v===null&&Qt(),Jt()),se&&Wt()}function Rn(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function M(e,t){var n=d;n!==null&&(n.f&P)!==0&&(e|=P);var r={ctx:T,deps:null,nodes:null,f:e|b|k,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};w?.register_created_effect(r);var s=r;if((e&Q)!==0)ae!==null?ae.push(r):G.ensure().schedule(r);else if(t!==null){try{oe(r)}catch(u){throw re(r),u}s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&(s.f&ye)===0&&(s=s.first,(e&q)!==0&&(e&Ae)!==0&&s!==null&&(s.f|=Ae))}if(s!==null&&(s.parent=n,n!==null&&Rn(s,n),v!==null&&(v.f&E)!==0&&(e&ee)===0)){var l=v;(l.effects??=[]).push(s)}return r}function kt(){return v!==null&&!I}function xn(e){const t=M(we,null);return y(t,g),t.teardown=e,t}function Tr(e){xt();var t=d.f,n=!v&&(t&F)!==0&&(t&le)===0;if(n){var r=T;(r.e??=[]).push(e)}else return Ot(e)}function Ot(e){return M(Q|ot,e)}function Ar(e){return xt(),M(we|ot,e)}function Sr(e){G.ensure();const t=M(ee|ye,e);return(n={})=>new Promise(r=>{n.outro?Dn(t,()=>{re(t),r(void 0)}):(re(t),r(void 0))})}function Rr(e){return M(Q,e)}function kn(e){return M(Oe|ye,e)}function xr(e,t=0){return M(we|t,e)}function kr(e,t=[],n=[],r=[]){gt(r,t,n,s=>{M(we,()=>e(...s.map(W)))})}function Or(e,t=[],n=[],r=[]){if(n.length>0||r.length>0)var s=Ke();gt(r,t,n,l=>{M(Q,()=>e(...l.map(W))),s&&s()})}function Nr(e,t=0){var n=M(q|t,e);return n}function Dr(e){return M(F|ye,e)}function Nt(e){var t=e.teardown;if(t!==null){const n=se,r=v;lt(!0),K(null);try{t.call(null)}finally{lt(n),K(r)}}}function Je(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){const s=n.ac;s!==null&&Rt(()=>{s.abort(Y)});var r=n.next;(n.f&ee)!==0?n.parent=null:re(n,t),n=r}}function On(e){for(var t=e.first;t!==null;){var n=t.next;(t.f&F)===0&&re(t),t=n}}function re(e,t=!0){var n=!1;(t||(e.f&Xt)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Nn(e.nodes.start,e.nodes.end),n=!0),y(e,et),Je(e,t&&!n),pe(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(const l of r)l.stop();Nt(e),e.f^=et,e.f|=C;var s=e.parent;s!==null&&s.first!==null&&Dt(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Nn(e,t){for(;e!==null;){var n=e===t?null:$(e);e.remove(),e=n}}function Dt(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Dn(e,t,n=!0){var r=[];It(e,r,!0);var s=()=>{n&&re(e),t&&t()},l=r.length;if(l>0){var u=()=>--l||s();for(var a of r)a.out(u)}else s()}function It(e,t,n){if((e.f&P)===0){e.f^=P;var r=e.nodes&&e.nodes.t;if(r!==null)for(const a of r)(a.is_global||n)&&t.push(a);for(var s=e.first;s!==null;){var l=s.next,u=(s.f&Ae)!==0||(s.f&F)!==0&&(e.f&q)!==0;It(s,t,u?n:!1),s=l}}}function Ir(e){Pt(e,!0)}function Pt(e,t){if((e.f&P)!==0){e.f^=P,(e.f&g)===0&&(y(e,b),G.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,s=(n.f&Ae)!==0||(n.f&F)!==0;Pt(n,s?t:!1),n=r}var l=e.nodes&&e.nodes.t;if(l!==null)for(const u of l)(u.is_global||t)&&u.in()}}function Pr(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var s=n===r?null:$(n);t.append(n),n=s}}let Te=!1,se=!1;function lt(e){se=e}let v=null,I=!1;function K(e){v=e}let d=null;function ue(e){d=e}let O=null;function Ct(e){v!==null&&(O===null?O=[e]:O.push(e))}let A=null,R=0,x=null;function In(e){x=e}let Mt=1,Z=0,J=Z;function at(e){J=e}function Ft(){return++Mt}function Ee(e){var t=e.f;if((t&b)!==0)return!0;if(t&E&&(e.f&=~te),(t&j)!==0){for(var n=e.deps,r=n.length,s=0;s<r;s++){var l=n[s];if(Ee(l)&&Et(l),l.wv>e.wv)return!0}(t&k)!==0&&D===null&&y(e,g)}return!1}function jt(e,t,n=!0){var r=e.reactions;if(r!==null&&!(O!==null&&ie.call(O,e)))for(var s=0;s<r.length;s++){var l=r[s];(l.f&E)!==0?jt(l,t,!1):t===l&&(n?y(l,b):(l.f&g)!==0&&y(l,j),Ge(l))}}function Lt(e){var t=A,n=R,r=x,s=v,l=O,u=T,a=I,i=J,o=e.f;A=null,R=0,x=null,v=(o&(F|ee))===0?e:null,O=null,Se(e.ctx),I=!1,J=++Z,e.ac!==null&&(Rt(()=>{e.ac.abort(Y)}),e.ac=null);try{e.f|=Fe;var f=e.fn,c=f();e.f|=le;var _=e.deps,p=w?.is_fork;if(A!==null){var h;if(p||pe(e,R),_!==null&&R>0)for(_.length=R+A.length,h=0;h<A.length;h++)_[R+h]=A[h];else e.deps=_=A;if(kt()&&(e.f&k)!==0)for(h=R;h<_.length;h++)(_[h].reactions??=[]).push(e)}else!p&&_!==null&&R<_.length&&(pe(e,R),_.length=R);if(ge()&&x!==null&&!I&&_!==null&&(e.f&(E|j|b))===0)for(h=0;h<x.length;h++)jt(x[h],e);if(s!==null&&s!==e){if(Z++,s.deps!==null)for(let N=0;N<n;N+=1)s.deps[N].rv=Z;if(t!==null)for(const N of t)N.rv=Z;x!==null&&(r===null?r=x:r.push(...x))}return(e.f&B)!==0&&(e.f^=B),c}catch(N){return cn(N)}finally{e.f^=Fe,A=t,R=n,x=r,v=s,O=l,Se(u),I=a,J=i}}function Pn(e,t){let n=t.reactions;if(n!==null){var r=Ut.call(n,e);if(r!==-1){var s=n.length-1;s===0?n=t.reactions=null:(n[r]=n[s],n.pop())}}if(n===null&&(t.f&E)!==0&&(A===null||!ie.call(A,t))){var l=t;(l.f&k)!==0&&(l.f^=k,l.f&=~te),Be(l),bn(l),pe(l,0)}}function pe(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)Pn(e,n[r])}function oe(e){var t=e.f;if((t&C)===0){y(e,g);var n=d,r=Te;d=e,Te=!0;try{(t&(q|ut))!==0?On(e):Je(e),Nt(e);var s=Lt(e);e.teardown=typeof s=="function"?s:null,e.wv=Mt;var l}finally{Te=r,d=n}}}async function Cr(){await Promise.resolve(),hn()}function Mr(){return G.ensure().settled()}function W(e){var t=e.f,n=(t&E)!==0;if(v!==null&&!I){var r=d!==null&&(d.f&C)!==0;if(!r&&(O===null||!ie.call(O,e))){var s=v.deps;if((v.f&Fe)!==0)e.rv<Z&&(e.rv=Z,A===null&&s!==null&&s[R]===e?R++:A===null?A=[e]:A.push(e));else{(v.deps??=[]).push(e);var l=e.reactions;l===null?e.reactions=[v]:ie.call(l,v)||l.push(v)}}}if(se&&z.has(e))return z.get(e);if(n){var u=e;if(se){var a=u.v;return((u.f&g)===0&&u.reactions!==null||qt(u))&&(a=Xe(u)),z.set(u,a),a}var i=(u.f&k)===0&&!I&&v!==null&&(Te||(v.f&k)!==0),o=(u.f&le)===0;Ee(u)&&(i&&(u.f|=k),Et(u)),i&&!o&&(mt(u),Yt(u))}if(D?.has(e))return D.get(e);if((e.f&B)!==0)throw e.v;return e.v}function Yt(e){if(e.f|=k,e.deps!==null)for(const t of e.deps)(t.reactions??=[]).push(e),(t.f&E)!==0&&(t.f&k)===0&&(mt(t),Yt(t))}function qt(e){if(e.v===m)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(z.has(t)||(t.f&E)!==0&&qt(t))return!0;return!1}function Fr(e){var t=I;try{return I=!0,e()}finally{I=t}}function jr(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(de in e)He(e);else if(!Array.isArray(e))for(let t in e){const n=e[t];typeof n=="object"&&n&&de in n&&He(n)}}}function He(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let r in e)try{He(e[r],t)}catch{}const n=it(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){const r=Vt(n);for(let s in r){const l=r[s].get;if(l)try{l.call(e)}catch{}}}}}export{Fn as $,W as A,V as B,ct as C,et as D,Ae as E,lr as F,ur as G,Xt as H,fr as I,ve as J,Bn as K,_e as L,se as M,C as N,Jn as O,Wn as P,De as Q,Zn as R,de as S,Xn as T,$e as U,gn as V,Qn as W,Ln as X,Ar as Y,Tr as Z,Kt as _,Rr as a,Hn as a$,jr as a0,cr as a1,yr as a2,kr as a3,_r as a4,wr as a5,ar as a6,gr as a7,Or as a8,An as a9,Re as aA,zn as aB,rr as aC,Rt as aD,pr as aE,sn as aF,Ue as aG,Vn as aH,Er as aI,Sr as aJ,Cn as aK,an as aL,Ve as aM,hn as aN,Cr as aO,jn as aP,Un as aQ,Ht as aR,Gn as aS,$n as aT,Kn as aU,P as aV,F as aW,st as aX,hr as aY,Yn as aZ,fn as a_,ir as aa,U as ab,vr as ac,un as ad,br as ae,Sn as af,er as ag,tr as ah,le as ai,Ne as aj,We as ak,kt as al,Ze as am,Ce as an,tt as ao,$t as ap,ln as aq,nr as ar,vn as as,ue as at,K as au,Se as av,G as aw,cn as ax,v as ay,Ye as az,d as b,it as b0,Vt as b1,Mr as b2,T as c,Ir as d,or as e,re as f,ke as g,Dr as h,w as i,ne as j,S as k,Nr as l,Pr as m,ye as n,$ as o,Dn as p,sr as q,xr as r,mr as s,fe as t,Fr as u,qe as v,xn as w,Mn as x,Gt as y,dr as z};
-1
build/_app/immutable/chunks/D9RahMPT.js
··· 1 - import{aZ as ge,a_ as mt,aJ as L,A as U,C as T,aI as ne,a$ as wt}from"./w0kPbzMq.js";import{o as Ve}from"./B43_79mg.js";const D=[];function Re(e,t=ge){let n=null;const r=new Set;function a(o){if(mt(e,o)&&(e=o,n)){const l=!D.length;for(const c of r)c[1](),D.push(c,e);if(l){for(let c=0;c<D.length;c+=2)D[c][0](D[c+1]);D.length=0}}}function i(o){a(o(e))}function s(o,l=ge){const c=[o,l];return r.add(c),r.size===1&&(n=t(a,i)||ge),o(e),()=>{r.delete(c),r.size===0&&n&&(n(),n=null)}}return{set:a,update:i,subscribe:s}}class xe{constructor(t,n){this.status=t,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${t}`}}toString(){return JSON.stringify(this.body)}}class Ae{constructor(t,n){this.status=t,this.location=n}}class Le extends Error{constructor(t,n,r){super(r),this.status=t,this.text=n}}new URL("sveltekit-internal://");function vt(e,t){return e==="/"||t==="ignore"?e:t==="never"?e.endsWith("/")?e.slice(0,-1):e:t==="always"&&!e.endsWith("/")?e+"/":e}function yt(e){return e.split("%25").map(decodeURI).join("%25")}function bt(e){for(const t in e)e[t]=decodeURIComponent(e[t]);return e}function _e({href:e}){return e.split("#")[0]}function kt(...e){let t=5381;for(const n of e)if(typeof n=="string"){let r=n.length;for(;r;)t=t*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)t=t*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(t>>>0).toString(36)}new TextEncoder;new TextDecoder;function St(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}const Et=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||"GET")!=="GET"&&W.delete(Ue(e)),Et(e,t));const W=new Map;function Rt(e,t){const n=Ue(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:a,...i}=JSON.parse(r.textContent);const s=r.getAttribute("data-ttl");return s&&W.set(n,{body:a,init:i,ttl:1e3*Number(s)}),r.getAttribute("data-b64")!==null&&(a=St(a)),Promise.resolve(new Response(a,i))}return window.fetch(e,t)}function xt(e,t,n){if(W.size>0){const r=Ue(e,n),a=W.get(r);if(a){if(performance.now()<a.ttl&&["default","force-cache","only-if-cached",void 0].includes(n?.cache))return new Response(a.body,a.init);W.delete(r)}}return window.fetch(t,n)}function Ue(e,t){let r=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){const a=[];t.headers&&a.push([...new Headers(t.headers)].join(",")),t.body&&(typeof t.body=="string"||ArrayBuffer.isView(t.body))&&a.push(t.body),r+=`[data-hash="${kt(...a)}"]`}return r}const At=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;function Lt(e){const t=[];return{pattern:e==="/"?/^\/$/:new RegExp(`^${Tt(e).map(r=>{const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return t.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const i=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(i)return t.push({name:i[1],matcher:i[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const s=r.split(/\[(.+?)\](?!\])/);return"/"+s.map((l,c)=>{if(c%2){if(l.startsWith("x+"))return me(String.fromCharCode(parseInt(l.slice(2),16)));if(l.startsWith("u+"))return me(String.fromCharCode(...l.slice(2).split("-").map(_=>parseInt(_,16))));const f=At.exec(l),[,p,w,h,u]=f;return t.push({name:h,matcher:u,optional:!!p,rest:!!w,chained:w?c===1&&s[0]==="":!1}),w?"([^]*?)":p?"([^/]*)?":"([^/]+?)"}return me(l)}).join("")}).join("")}/?$`),params:t}}function Ut(e){return e!==""&&!/^\([^)]+\)$/.test(e)}function Tt(e){return e.slice(1).split("/").filter(Ut)}function It(e,t,n){const r={},a=e.slice(1),i=a.filter(o=>o!==void 0);let s=0;for(let o=0;o<t.length;o+=1){const l=t[o];let c=a[o-s];if(l.chained&&l.rest&&s&&(c=a.slice(o-s,o+1).filter(f=>f).join("/"),s=0),c===void 0)if(l.rest)c="";else continue;if(!l.matcher||n[l.matcher](c)){r[l.name]=c;const f=t[o+1],p=a[o+1];f&&!f.rest&&f.optional&&p&&l.chained&&(s=0),!f&&!p&&Object.keys(r).length===i.length&&(s=0);continue}if(l.optional&&l.chained){s++;continue}return}if(!s)return r}function me(e){return e.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function Ot({nodes:e,server_loads:t,dictionary:n,matchers:r}){const a=new Set(t);return Object.entries(n).map(([o,[l,c,f]])=>{const{pattern:p,params:w}=Lt(o),h={id:o,exec:u=>{const _=p.exec(u);if(_)return It(_,w,r)},errors:[1,...f||[]].map(u=>e[u]),layouts:[0,...c||[]].map(s),leaf:i(l)};return h.errors.length=h.layouts.length=Math.max(h.errors.length,h.layouts.length),h});function i(o){const l=o<0;return l&&(o=~o),[l,e[o]]}function s(o){return o===void 0?o:[a.has(o),e[o]]}}function Ye(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function Be(e,t,n=JSON.stringify){const r=n(t);try{sessionStorage[e]=r}catch{}}const x=globalThis.__sveltekit_1uytokf?.base??"",Pt=globalThis.__sveltekit_1uytokf?.assets??x??"",$t="1774903841109",He="sveltekit:snapshot",Xe="sveltekit:scroll",Ze="sveltekit:states",Ct="sveltekit:pageurl",B="sveltekit:history",Y="sveltekit:navigation",j={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Te=location.origin;function Qe(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){const n=document.getElementsByTagName("base");t=n.length?n[0].href:document.URL}return new URL(e,t)}function q(){return{x:pageXOffset,y:pageYOffset}}function V(e,t){return e.getAttribute(`data-sveltekit-${t}`)}const Ke={...j,"":j.hover};function et(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function tt(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()==="A"&&e.hasAttribute("href"))return e;e=et(e)}}function ye(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const o=location.hash.split("#")[1]||"/";r.hash=`#${o}${r.hash}`}}catch{}const a=e instanceof SVGAElement?e.target.baseVal:e.target,i=!r||!!a||fe(r,t,n)||(e.getAttribute("rel")||"").split(/\s+/).includes("external"),s=r?.origin===Te&&e.hasAttribute("download");return{url:r,external:i,target:a,download:s}}function re(e){let t=null,n=null,r=null,a=null,i=null,s=null,o=e;for(;o&&o!==document.documentElement;)r===null&&(r=V(o,"preload-code")),a===null&&(a=V(o,"preload-data")),t===null&&(t=V(o,"keepfocus")),n===null&&(n=V(o,"noscroll")),i===null&&(i=V(o,"reload")),s===null&&(s=V(o,"replacestate")),o=et(o);function l(c){switch(c){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:Ke[r??"off"],preload_data:Ke[a??"off"],keepfocus:l(t),noscroll:l(n),reload:l(i),replace_state:l(s)}}function Me(e){const t=Re(e);let n=!0;function r(){n=!0,t.update(s=>s)}function a(s){n=!1,t.set(s)}function i(s){let o;return t.subscribe(l=>{(o===void 0||n&&l!==o)&&s(o=l)})}return{notify:r,set:a,subscribe:i}}const nt={v:()=>{}};function jt(){const{set:e,subscribe:t}=Re(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Pt}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const s=(await a.json()).version!==$t;return s&&(e(!0),nt.v(),clearTimeout(n)),s}catch{return!1}}return{subscribe:t,check:r}}function fe(e,t,n){return e.origin!==Te||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function fn(e){}const rt=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...rt];const Nt=new Set([...rt]);[...Nt];function qt(e){return e.filter(t=>t!=null)}function Ie(e){return e instanceof xe||e instanceof Le?e.status:500}function Dt(e){return e instanceof Le?e.text:"Internal Error"}let k,H,we;const Vt=Ve.toString().includes("$$")||/function \w+\(\) \{\}/.test(Ve.toString()),ze="a:";Vt?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(ze)},H={current:null},we={current:!1}):(k=new class{#e=L({});get data(){return U(this.#e)}set data(t){T(this.#e,t)}#t=L(null);get form(){return U(this.#t)}set form(t){T(this.#t,t)}#n=L(null);get error(){return U(this.#n)}set error(t){T(this.#n,t)}#r=L({});get params(){return U(this.#r)}set params(t){T(this.#r,t)}#a=L({id:null});get route(){return U(this.#a)}set route(t){T(this.#a,t)}#o=L({});get state(){return U(this.#o)}set state(t){T(this.#o,t)}#s=L(-1);get status(){return U(this.#s)}set status(t){T(this.#s,t)}#i=L(new URL(ze));get url(){return U(this.#i)}set url(t){T(this.#i,t)}},H=new class{#e=L(null);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},we=new class{#e=L(!1);get current(){return U(this.#e)}set current(t){T(this.#e,t)}},nt.v=()=>we.current=!0);function Bt(e){Object.assign(k,e)}const Kt=new Set(["icon","shortcut icon","apple-touch-icon"]);let F=null;const C=Ye(Xe)??{},X=Ye(He)??{},$={url:Me({}),page:Me({}),navigating:Re(null),updated:jt()};function Oe(e){C[e]=q()}function Mt(e,t){let n=e+1;for(;C[n];)delete C[n],n+=1;for(n=t+1;X[n];)delete X[n],n+=1}function Z(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(()=>{})}async function at(){if("serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration(x||"/");e&&await e.update()}}function Fe(){}let Pe,be,ae,I,ke,y;const oe=[],se=[];let A=null;function Se(){A?.fork?.then(e=>e?.discard()),A=null}const te=new Map,ot=new Set,zt=new Set,J=new Set;let m={branch:[],error:null,url:null},st=!1,ie=!1,Ge=!0,Q=!1,G=!1,it=!1,$e=!1,lt,v,R,N;const le=new Set,We=new Map;async function gn(e,t,n){globalThis.__sveltekit_1uytokf?.data&&globalThis.__sveltekit_1uytokf.data,document.URL!==location.href&&(location.href=location.href),y=e,await e.hooks.init?.(),Pe=Ot(e),I=document.documentElement,ke=t,be=e.nodes[0],ae=e.nodes[1],be(),ae(),v=history.state?.[B],R=history.state?.[Y],v||(v=R=Date.now(),history.replaceState({...history.state,[B]:v,[Y]:R},""));const r=C[v];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await an(ke,n)):(await K({type:"enter",url:Qe(y.hash?ln(new URL(location.href)):location.href),replace_state:!0}),a()),rn()}function Ft(){oe.length=0,$e=!1}function ct(e){se.some(t=>t?.snapshot)&&(X[e]=se.map(t=>t?.snapshot?.capture()))}function ut(e){X[e]?.forEach((t,n)=>{se[n]?.snapshot?.restore(t)})}function Je(){Oe(v),Be(Xe,C),ct(R),Be(He,X)}async function Gt(e,t,n,r){let a;t.invalidateAll&&Se(),await K({type:"goto",url:Qe(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:n,nav_token:r,accept:()=>{t.invalidateAll&&($e=!0,a=[...We.keys()]),t.invalidate&&t.invalidate.forEach(nn)}}),t.invalidateAll&&ne().then(ne).then(()=>{We.forEach(({resource:i},s)=>{a?.includes(s)&&i.refresh?.()})})}async function Wt(e){if(e.id!==A?.id){Se();const t={};le.add(t),A={id:e.id,token:t,promise:dt({...e,preload:t}).then(n=>(le.delete(t),n.type==="loaded"&&n.state.error&&Se(),n)),fork:null}}return A.promise}async function ve(e){const t=(await de(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(n=>n[1]()))}async function ft(e,t,n){const r={params:m.params,route:{id:m.route?.id??null},url:new URL(location.href)};m={...e.state,nav:r};const a=document.querySelector("style[data-sveltekit]");if(a&&a.remove(),Object.assign(k,e.props.page),lt=new y.root({target:t,props:{...e.props,stores:$,components:se},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),ut(R),n){const i={from:null,to:{...r,scroll:C[v]??q()},willUnload:!1,type:"enter",complete:Promise.resolve()};J.forEach(s=>s(i))}ie=!0}async function ce({url:e,params:t,branch:n,errors:r,status:a,error:i,route:s,form:o}){let l="never";if(x&&(e.pathname===x||e.pathname===x+"/"))l="always";else for(const u of n)u?.slash!==void 0&&(l=u.slash);e.pathname=vt(e.pathname,l),e.search=e.search;const c={type:"loaded",state:{url:e,params:t,branch:n,error:i,route:s},props:{constructors:qt(n).map(u=>u.node.component),page:De(k)}};o!==void 0&&(c.props.form=o);let f={},p=!k,w=0;for(let u=0;u<Math.max(n.length,m.branch.length);u+=1){const _=n[u],g=m.branch[u];_?.data!==g?.data&&(p=!0),_&&(f={...f,..._.data},p&&(c.props[`data_${w}`]=f),w+=1)}return(!m.url||e.href!==m.url.href||m.error!==i||o!==void 0&&o!==k.form||p)&&(c.props.page={error:i,params:t,route:{id:s?.id??null},state:{},status:a,url:new URL(e),form:o??null,data:p?f:k.data}),c}async function Ce({loader:e,parent:t,url:n,params:r,route:a,server_data_node:i}){let s=null;const o={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();return{node:l,loader:e,server:i,universal:l.universal?.load?{type:"data",data:s,uses:o}:null,data:s??i?.data??null,slash:l.universal?.trailingSlash??i?.slash}}function Jt(e,t,n){let r=e instanceof Request?e.url:e;const a=new URL(r,n);a.origin===n.origin&&(r=a.href.slice(n.origin.length));const i=ie?xt(r,a.href,t):Rt(r,t);return{resolved:a,promise:i}}function Yt(e,t,n,r,a,i){if($e)return!0;if(!a)return!1;if(a.parent&&e||a.route&&t||a.url&&n)return!0;for(const s of a.search_params)if(r.has(s))return!0;for(const s of a.params)if(i[s]!==m.params[s])return!0;for(const s of a.dependencies)if(oe.some(o=>o(new URL(s))))return!0;return!1}function je(e,t){return e?.type==="data"?e:e?.type==="skip"?t??null:null}function Ht(e,t){if(!e)return new Set(t.searchParams.keys());const n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(const r of n){const a=e.searchParams.getAll(r),i=t.searchParams.getAll(r);a.every(s=>i.includes(s))&&i.every(s=>a.includes(s))&&n.delete(r)}return n}function Xt({error:e,url:t,route:n,params:r}){return{type:"loaded",state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:De(k),constructors:[]}}}async function dt({id:e,invalidating:t,url:n,params:r,route:a,preload:i}){if(A?.id===e)return le.delete(A.token),A.promise;const{errors:s,layouts:o,leaf:l}=a,c=[...o,l];s.forEach(g=>g?.().catch(()=>{})),c.forEach(g=>g?.[1]().catch(()=>{}));const f=m.url?e!==ue(m.url):!1,p=m.route?a.id!==m.route.id:!1,w=Ht(m.url,n);let h=!1;const u=c.map(async(g,d)=>{if(!g)return;const S=m.branch[d];return g[1]===S?.loader&&!Yt(h,p,f,w,S.universal?.uses,r)?S:(h=!0,Ce({loader:g[1],url:n,params:r,route:a,parent:async()=>{const O={};for(let P=0;P<d;P+=1)Object.assign(O,(await u[P])?.data);return O},server_data_node:je(g[0]?{type:"skip"}:null,g[0]?S?.server:void 0)}))});for(const g of u)g.catch(()=>{});const _=[];for(let g=0;g<c.length;g+=1)if(c[g])try{_.push(await u[g])}catch(d){if(d instanceof Ae)return{type:"redirect",location:d.location};if(le.has(i))return Xt({error:await ee(d,{params:r,url:n,route:{id:a.id}}),url:n,params:r,route:a});let S=Ie(d),E;if(d instanceof xe)E=d.body;else{if(await $.updated.check())return await at(),await Z(n);E=await ee(d,{params:r,url:n,route:{id:a.id}})}const O=await Zt(g,_,s);return O?ce({url:n,params:r,branch:_.slice(0,O.idx).concat(O.node),errors:s,status:S,error:E,route:a}):await pt(n,{id:a.id},E,S)}else _.push(void 0);return ce({url:n,params:r,branch:_,errors:s,status:200,error:null,route:a,form:t?void 0:null})}async function Zt(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)r-=1;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function Ne({status:e,error:t,url:n,route:r}){const a={};let i=null;try{const s=await Ce({loader:be,url:n,params:a,route:r,parent:()=>Promise.resolve({}),server_data_node:je(i)}),o={node:await ae(),loader:ae,universal:null,server:null,data:null};return ce({url:n,params:a,branch:[s,o],status:e,error:t,errors:[],route:null})}catch(s){if(s instanceof Ae)return Gt(new URL(s.location,location.href),{},0);throw s}}async function Qt(e){const t=e.href;if(te.has(t))return te.get(t);let n;try{const r=(async()=>{let a=await y.hooks.reroute({url:new URL(e),fetch:async(i,s)=>Jt(i,s,e).promise})??e;if(typeof a=="string"){const i=new URL(e);y.hash?i.hash=a:i.pathname=a,a=i}return a})();te.set(t,r),n=await r}catch{te.delete(t);return}return n}async function de(e,t){if(e&&!fe(e,x,y.hash)){const n=await Qt(e);if(!n)return;const r=en(n);for(const a of Pe){const i=a.exec(r);if(i)return{id:ue(e),invalidating:t,route:a,params:bt(i),url:e}}}}function en(e){return yt(y.hash?e.hash.replace(/^#/,"").replace(/[?#].+/,""):e.pathname.slice(x.length))||"/"}function ue(e){return(y.hash?e.hash.replace(/^#/,""):e.pathname)+e.search}function ht({url:e,type:t,intent:n,delta:r,event:a,scroll:i}){let s=!1;const o=qe(m,n,e,t,i??null);r!==void 0&&(o.navigation.delta=r),a!==void 0&&(o.navigation.event=a);const l={...o.navigation,cancel:()=>{s=!0,o.reject(new Error("navigation cancelled"))}};return Q||ot.forEach(c=>c(l)),s?null:o}async function K({type:e,url:t,popped:n,keepfocus:r,noscroll:a,replace_state:i,state:s={},redirect_count:o=0,nav_token:l={},accept:c=Fe,block:f=Fe,event:p}){const w=N;N=l;const h=await de(t,!1),u=e==="enter"?qe(m,h,t,e):ht({url:t,type:e,delta:n?.delta,intent:h,scroll:n?.scroll,event:p});if(!u){f(),N===l&&(N=w);return}const _=v,g=R;c(),Q=!0,ie&&u.navigation.type!=="enter"&&$.navigating.set(H.current=u.navigation);let d=h&&await dt(h);if(!d){if(fe(t,x,y.hash))return await Z(t,i);d=await pt(t,{id:null},await ee(new Le(404,"Not Found",`Not found: ${t.pathname}`),{url:t,params:{},route:{id:null}}),404,i)}if(t=h?.url||t,N!==l)return u.reject(new Error("navigation aborted")),!1;if(d.type==="redirect"){if(o<20){await K({type:e,url:new URL(d.location,t),popped:n,keepfocus:r,noscroll:a,replace_state:i,state:s,redirect_count:o+1,nav_token:l}),u.fulfil(void 0);return}d=await Ne({status:500,error:await ee(new Error("Redirect loop"),{url:t,params:{},route:{id:null}}),url:t,route:{id:null}})}else d.props.page.status>=400&&await $.updated.check()&&(await at(),await Z(t,i));if(Ft(),Oe(_),ct(g),d.props.page.url.pathname!==t.pathname&&(t.pathname=d.props.page.url.pathname),s=n?n.state:s,!n){const b=i?0:1,M={[B]:v+=b,[Y]:R+=b,[Ze]:s};(i?history.replaceState:history.pushState).call(history,M,"",t),i||Mt(v,R)}const S=h&&A?.id===h.id?A.fork:null;A=null,d.props.page.state=s;let E;if(ie){const b=(await Promise.all(Array.from(zt,z=>z(u.navigation)))).filter(z=>typeof z=="function");if(b.length>0){let z=function(){b.forEach(pe=>{J.delete(pe)})};b.push(z),b.forEach(pe=>{J.add(pe)})}const M=u.navigation.to;m={...d.state,nav:{params:M.params,route:M.route,url:M.url}},d.props.page&&(d.props.page.url=t);const he=S&&await S;he?E=he.commit():(F=null,lt.$set(d.props),F&&Object.assign(d.props.page,F),Bt(d.props.page),E=wt?.()),it=!0}else await ft(d,ke,!1);const{activeElement:O}=document;await E,await ne(),await ne();let P=null;if(Ge){const b=n?n.scroll:a?q():null;b?scrollTo(b.x,b.y):(P=t.hash&&document.getElementById(gt(t)))?P.scrollIntoView():scrollTo(0,0)}const _t=document.activeElement!==O&&document.activeElement!==document.body;!r&&!_t&&sn(t,!P),Ge=!0,d.props.page&&(F&&Object.assign(d.props.page,F),Object.assign(k,d.props.page)),Q=!1,e==="popstate"&&ut(R),u.fulfil(void 0),u.navigation.to&&(u.navigation.to.scroll=q()),J.forEach(b=>b(u.navigation)),$.navigating.set(H.current=null)}async function pt(e,t,n,r,a){return e.origin===Te&&e.pathname===location.pathname&&!st?await Ne({status:r,error:n,url:e,route:t}):await Z(e,a)}function tn(){let e,t={element:void 0,href:void 0},n;I.addEventListener("mousemove",o=>{const l=o.target;clearTimeout(e),e=setTimeout(()=>{i(l,j.hover)},20)});function r(o){o.defaultPrevented||i(o.composedPath()[0],j.tap)}I.addEventListener("mousedown",r),I.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(o=>{for(const l of o)l.isIntersecting&&(ve(new URL(l.target.href)),a.unobserve(l.target))},{threshold:0});async function i(o,l){const c=tt(o,I),f=c===t.element&&c?.href===t.href&&l>=n;if(!c||f)return;const{url:p,external:w,download:h}=ye(c,x,y.hash);if(w||h)return;const u=re(c),_=p&&ue(m.url)===ue(p);if(!(u.reload||_))if(l<=u.preload_data){t={element:c,href:c.href},n=j.tap;const g=await de(p,!1);if(!g)return;Wt(g)}else l<=u.preload_code&&(t={element:c,href:c.href},n=l,ve(p))}function s(){a.disconnect();for(const o of I.querySelectorAll("a")){const{url:l,external:c,download:f}=ye(o,x,y.hash);if(c||f)continue;const p=re(o);p.reload||(p.preload_code===j.viewport&&a.observe(o),p.preload_code===j.eager&&ve(l))}}J.add(s),s()}function ee(e,t){if(e instanceof xe)return e.body;const n=Ie(e),r=Dt(e);return y.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function nn(e){if(typeof e=="function")oe.push(e);else{const{href:t}=new URL(e,location.href);oe.push(n=>n.href===t)}}function rn(){history.scrollRestoration="manual",addEventListener("beforeunload",t=>{let n=!1;if(Je(),!Q){const r=qe(m,void 0,null,"leave"),a={...r.navigation,cancel:()=>{n=!0,r.reject(new Error("navigation cancelled"))}};ot.forEach(i=>i(a))}n?(t.preventDefault(),t.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Je()}),navigator.connection?.saveData||tn(),I.addEventListener("click",async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;const n=tt(t.composedPath()[0],I);if(!n)return;const{url:r,external:a,target:i,download:s}=ye(n,x,y.hash);if(!r)return;if(i==="_parent"||i==="_top"){if(window.parent!==window)return}else if(i&&i!=="_self")return;const o=re(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&!(r.protocol==="https:"||r.protocol==="http:")||s)return;const[c,f]=(y.hash?r.hash.replace(/^#/,""):r.href).split("#"),p=c===_e(location);if(a||o.reload&&(!p||!f)){ht({url:r,type:"link",event:t})?Q=!0:t.preventDefault();return}if(f!==void 0&&p){const[,w]=m.url.href.split("#");if(w===f){if(t.preventDefault(),f===""||f==="top"&&n.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=n.ownerDocument.getElementById(decodeURIComponent(f));h&&(h.scrollIntoView(),h.focus())}return}if(G=!0,Oe(v),e(r),!o.replace_state)return;G=!1}t.preventDefault(),await new Promise(w=>{requestAnimationFrame(()=>{setTimeout(w,0)}),setTimeout(w,100)}),await K({type:"link",url:r,keepfocus:o.keepfocus,noscroll:o.noscroll,replace_state:o.replace_state??r.href===location.href,event:t})}),I.addEventListener("submit",t=>{if(t.defaultPrevented)return;const n=HTMLFormElement.prototype.cloneNode.call(t.target),r=t.submitter;if((r?.formTarget||n.target)==="_blank"||(r?.formMethod||n.method)!=="get")return;const s=new URL(r?.hasAttribute("formaction")&&r?.formAction||n.action);if(fe(s,x,!1))return;const o=t.target,l=re(o);if(l.reload)return;t.preventDefault(),t.stopPropagation();const c=new FormData(o,r);s.search=new URLSearchParams(c).toString(),K({type:"form",url:s,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??s.href===location.href,event:t})}),addEventListener("popstate",async t=>{if(!Ee){if(t.state?.[B]){const n=t.state[B];if(N={},n===v)return;const r=C[n],a=t.state[Ze]??{},i=new URL(t.state[Ct]??location.href),s=t.state[Y],o=m.url?_e(location)===_e(m.url):!1;if(s===R&&(it||o)){a!==k.state&&(k.state=a),e(i),C[v]=q(),r&&scrollTo(r.x,r.y),v=n;return}const c=n-v;await K({type:"popstate",url:i,popped:{state:a,scroll:r,delta:c},accept:()=>{v=n,R=s},block:()=>{history.go(-c)},nav_token:N,event:t})}else if(!G){const n=new URL(location.href);e(n),y.hash&&location.reload()}}}),addEventListener("hashchange",()=>{G&&(G=!1,history.replaceState({...history.state,[B]:++v,[Y]:R},"",location.href))});for(const t of document.querySelectorAll("link"))Kt.has(t.rel)&&(t.href=t.href);addEventListener("pageshow",t=>{t.persisted&&$.navigating.set(H.current=null)});function e(t){m.url=k.url=t,$.page.set(De(k)),$.page.notify()}}async function an(e,{status:t=200,error:n,node_ids:r,params:a,route:i,server_route:s,data:o,form:l}){st=!0;const c=new URL(location.href);let f;({params:a={},route:i={id:null}}=await de(c,!1)||{}),f=Pe.find(({id:h})=>h===i.id);let p,w=!0;try{const h=r.map(async(_,g)=>{const d=o[g];return d?.uses&&(d.uses=on(d.uses)),Ce({loader:y.nodes[_],url:c,params:a,route:i,parent:async()=>{const S={};for(let E=0;E<g;E+=1)Object.assign(S,(await h[E]).data);return S},server_data_node:je(d)})}),u=await Promise.all(h);if(f){const _=f.layouts;for(let g=0;g<_.length;g++)_[g]||u.splice(g,0,void 0)}p=await ce({url:c,params:a,branch:u,status:t,error:n,errors:f?.errors,form:l,route:f??null})}catch(h){if(h instanceof Ae){await Z(new URL(h.location,location.href));return}p=await Ne({status:Ie(h),error:await ee(h,{url:c,params:a,route:i}),url:c,route:i}),e.textContent="",w=!1}p.props.page&&(p.props.page.state={}),await ft(p,e,w)}function on(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}let Ee=!1;function sn(e,t=!0){const n=document.querySelector("[autofocus]");if(n)n.focus();else{const r=gt(e);if(r&&document.getElementById(r)){const{x:i,y:s}=q();setTimeout(()=>{const o=history.state;Ee=!0,location.replace(new URL(`#${r}`,location.href)),history.replaceState(o,"",e),t&&scrollTo(i,s),Ee=!1})}else{const i=document.body,s=i.getAttribute("tabindex");i.tabIndex=-1,i.focus({preventScroll:!0,focusVisible:!1}),s!==null?i.setAttribute("tabindex",s):i.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const i=[];for(let s=0;s<a.rangeCount;s+=1)i.push(a.getRangeAt(s));setTimeout(()=>{if(a.rangeCount===i.length){for(let s=0;s<a.rangeCount;s+=1){const o=i[s],l=a.getRangeAt(s);if(o.commonAncestorContainer!==l.commonAncestorContainer||o.startContainer!==l.startContainer||o.endContainer!==l.endContainer||o.startOffset!==l.startOffset||o.endOffset!==l.endOffset)return}a.removeAllRanges()}})}}}function qe(e,t,n,r,a=null){let i,s;const o=new Promise((c,f)=>{i=c,s=f});return o.catch(()=>{}),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:q()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:a},willUnload:!t,type:r,complete:o},fulfil:i,reject:s}}function De(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function ln(e){const t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function gt(e){let t;if(y.hash){const[,,n]=e.hash.split("#",3);t=n??""}else t=e.hash.slice(1);return decodeURIComponent(t)}export{gn as a,fn as l,k as p,$ as s};
+1
build/_app/immutable/chunks/DGbOEUpF.js
··· 1 + import{ae as v,v as u,af as T,ag as p,ah as h,b as l,j as i,k as s,ai as g,F as E,g as d,aj as y,t as w,ak as N}from"./CkzjbUDB.js";const M=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:t=>t});function b(t){return M?.createHTML(t)??t}function x(t){var r=v("template");return r.innerHTML=b(t.replaceAll("<!>","<!---->")),r.content}function n(t,r){var e=l;e.nodes===null&&(e.nodes={start:t,end:r,a:null,t:null})}function O(t,r){var e=(r&p)!==0,f=(r&h)!==0,a,_=!t.startsWith("<!>");return()=>{if(i)return n(s,null),s;a===void 0&&(a=x(_?t:"<!>"+t),e||(a=u(a)));var o=f||T?document.importNode(a,!0):a.cloneNode(!0);if(e){var c=u(o),m=o.lastChild;n(c,m)}else n(o,o);return o}}function P(t=""){if(!i){var r=d(t+"");return n(r,r),r}var e=s;return e.nodeType!==y?(e.before(e=d()),w(e)):N(e),n(e,e),e}function R(){if(i)return n(s,null),s;var t=document.createDocumentFragment(),r=document.createComment(""),e=d();return t.append(r,e),n(r,e),t}function C(t,r){if(i){var e=l;((e.f&g)===0||e.nodes.end===null)&&(e.nodes.end=s),E();return}t!==null&&t.before(r)}const A="5";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add(A);export{C as a,n as b,R as c,O as f,P as t};
+2
build/_app/immutable/chunks/D_t83wNY.js
··· 1 + import{a as Z,f as z}from"./DGbOEUpF.js";import{j as B,aZ as at,a_ as ct,a$ as it,b0 as lt,b1 as pt,a1 as J,a5 as y,a7 as Y,a6 as w,a3 as ft,a4 as Q,aa as V}from"./CkzjbUDB.js";import{s as ut}from"./DmyE0d-6.js";import{p as $}from"./XE2G8ySY.js";import{d as ht,a as gt}from"./BsDbD4Ku.js";const G=[...` 2 + \r\f \v\uFEFF`];function Tt(t,e,s){var r=t==null?"":""+t;if(s){for(var n of Object.keys(s))if(s[n])r=r?r+" "+n:n;else if(r.length)for(var a=n.length,p=0;(p=r.indexOf(n,p))>=0;){var g=p+a;(p===0||G.includes(r[p-1]))&&(g===r.length||G.includes(r[g]))?r=(p===0?"":r.substring(0,p))+r.substring(g+1):p=g}}return r===""?null:r}function dt(t,e){return t==null?null:String(t)}function E(t,e,s,r){var n=t.__style;if(B||n!==e){var a=dt(e);(!B||a!==t.getAttribute("style"))&&(a==null?t.removeAttribute("style"):t.style.cssText=a),t.__style=e}return r}const vt=Symbol("is custom element"),mt=Symbol("is html"),kt=it?"link":"LINK";function j(t,e,s,r){var n=yt(t);B&&(n[e]=t.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&t.nodeName===kt)||n[e]!==(n[e]=s)&&(e==="loading"&&(t[at]=s),s==null?t.removeAttribute(e):typeof s!="string"&&wt(t).includes(e)?t[e]=s:t.setAttribute(e,s))}function yt(t){return t.__attributes??={[vt]:t.nodeName.includes("-"),[mt]:t.namespaceURI===ct}}var X=new Map;function wt(t){var e=t.getAttribute("is")||t.nodeName,s=X.get(e);if(s)return s;X.set(e,s=[]);for(var r,n=t,a=Element.prototype;a!==n;){r=pt(n);for(var p in r)r[p].set&&s.push(p);n=lt(n)}return s}const xt="https://iameli.com",_t="did:plc:rbvrr34edl5ddpuwcubjiost",bt="place.stream.video",St="https://vod-beta.stream.place/xrpc/place.stream.playback.getVideoPlaylist";async function Dt(t,e=20){const s=new URLSearchParams({repo:_t,collection:bt,limit:String(e)});t&&s.set("cursor",t);const r=await fetch(`${xt}/xrpc/com.atproto.repo.listRecords?${s}`);if(!r.ok)throw new Error(`Failed to fetch records: ${r.status}`);return r.json()}function Bt(t){return`${St}?uri=${encodeURIComponent(t)}`}function Nt(t){const e=Math.floor(t/1e9),s=Math.floor(e/3600),r=Math.floor(e%3600/60),n=e%60;return s>0?`${s}:${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`:`${r}:${String(n).padStart(2,"0")}`}function Ot(t){return new Date(t).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const Pt="https://public.api.bsky.app";async function Ht(t){const e=new URLSearchParams({actor:t}),s=await fetch(`${Pt}/xrpc/app.bsky.actor.getProfile?${e}`);if(!s.ok)throw new Error(`Failed to fetch profile: ${s.status}`);return s.json()}const T=new Map;async function Kt(t){if(T.has(t))return T.get(t);try{const e=await fetch(`https://plc.directory/${t}`);if(!e.ok)return t;const r=(await e.json()).alsoKnownAs?.[0],n=r?r.replace("at://","@"):t;return T.set(t,n),n}catch{return t}}const D=new Map;async function $t(t){if(D.has(t))return D.get(t);try{const e=await fetch(`https://plc.directory/${t}`);if(!e.ok)return null;const n=(await e.json()).service?.find(a=>a.id==="#atproto_pds"||a.type==="AtprotoPersonalDataServer")?.serviceEndpoint??null;return n&&D.set(t,n),n}catch{return null}}function At(t){const e=t.match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);return e?{repo:e[1],collection:e[2],rkey:e[3]}:null}const A=new Map;async function Wt(t){const e=t.value.livestream?.uri;if(!e)return null;if(A.has(e))return A.get(e);try{const s=At(e);if(!s)return null;const r=await $t(s.repo);if(!r)return null;const n=new URLSearchParams({repo:s.repo,collection:s.collection,rkey:s.rkey}),a=await fetch(`${r}/xrpc/com.atproto.repo.getRecord?${n}`);if(!a.ok)return null;const g=(await a.json()).value?.thumb?.ref?.$link;if(!g)return null;const _=`${r}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(s.repo)}&cid=${encodeURIComponent(g)}`;return A.set(e,_),_}catch{return A.set(e,null),null}}function v(t,e=0){let s=0;const r=t+String(e);for(let n=0;n<r.length;n++){const a=r.charCodeAt(n);s=(s<<5)-s+a|0}return(s%65536+65536)%65536/65536}function qt(t){const e=v(t,0),s=v(t,1),r=v(t,2);return{rotation:(e-.5)*6,translateX:(s-.5)*12,translateY:(r-.5)*60}}var Mt=z('<div class="wavy-container svelte-7frlgw"><div class="wavy-clipped svelte-7frlgw"><div class="wavy-fill svelte-7frlgw"></div> <div class="wavy-content svelte-7frlgw"><!></div></div> <svg class="wavy-stroke svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" overflow="visible"><path fill="none" stroke-linejoin="round" stroke-linecap="round"></path></svg></div>');function Yt(t,e){J(e,!0);let s=$(e,"fill",3,"#39FF44"),r=$(e,"strokeColor",3,"#0A182B"),n=$(e,"strokeWidth",3,3),a=$(e,"padding",3,"16px");const p=typeof a()=="number"?`${a()}px`:a(),{pts:g,svgPath:_}=et(e.seed),tt=`polygon(${g.map(([m,K])=>`${m.toFixed(2)}% ${K.toFixed(2)}%`).join(", ")})`;function et(m){const rt=[0,1,2,3].map(o=>({phase1:v(m,o*10+1)*Math.PI*2,phase2:v(m,o*10+2)*Math.PI*2,freq1:1.5+v(m,o*10+3)*1.5,freq2:3+v(m,o*10+4)*2,ampScale:.7+v(m,o*10+5)*.6}));function P(o,i){const l=rt[o],f=Math.sin(i*l.freq1*Math.PI*2+l.phase1)*2.5*.7,k=Math.sin(i*l.freq2*Math.PI*2+l.phase2)*2.5*.3;return(f+k)*l.ampScale}const c=[];for(let o=0;o<=16;o++){const i=o/16;c.push([1+i*98,1+P(0,i)])}for(let o=1;o<=16;o++){const i=o/16;c.push([99+P(1,i),1+i*98])}for(let o=1;o<=16;o++){const i=o/16;c.push([99-i*98,99+P(2,i)])}for(let o=1;o<16;o++){const i=o/16;c.push([1+P(3,i),99-i*98])}let C=`M ${c[0][0].toFixed(1)} ${c[0][1].toFixed(1)}`;for(let o=0;o<c.length;o++){const i=c[(o-1+c.length)%c.length],l=c[o],f=c[(o+1)%c.length],k=c[(o+2)%c.length],d=.3,I=l[0]+(f[0]-i[0])*d,L=l[1]+(f[1]-i[1])*d,F=f[0]-(k[0]-l[0])*d,U=f[1]-(k[1]-l[1])*d;C+=` C ${I.toFixed(1)} ${L.toFixed(1)}, ${F.toFixed(1)} ${U.toFixed(1)}, ${f[0].toFixed(1)} ${f[1].toFixed(1)}`}C+=" Z";const W=[],x=c.length,q=10;for(let o=0;o<x;o++){const i=c[(o-1+x)%x],l=c[o],f=c[(o+1)%x],k=c[(o+2)%x],d=.3,I=l[0]+(f[0]-i[0])*d,L=l[1]+(f[1]-i[1])*d,F=f[0]-(k[0]-l[0])*d,U=f[1]-(k[1]-l[1])*d;for(let R=0;R<q;R++){const u=R/q,h=1-u,nt=h*h*h*l[0]+3*h*h*u*I+3*h*u*u*F+u*u*u*f[0],ot=h*h*h*l[1]+3*h*h*u*L+3*h*u*u*U+u*u*u*f[1];W.push([nt,ot])}}return{pts:W,svgPath:C}}var b=Mt(),S=y(b),N=y(S),O=Y(N,2),st=y(O);ut(st,()=>e.children),w(O),w(S);var H=Y(S,2),M=y(H);w(H),w(b),ft(()=>{E(b,`--padding: ${p??""};`),E(S,`clip-path: ${tt};`),E(N,`background: ${s()??""};`),j(M,"d",_),j(M,"stroke",r()),j(M,"stroke-width",n())}),Z(t,b),Q()}var Ct=z('<header class="frog-header svelte-1kxia9k"><div class="title-area svelte-1kxia9k"><a href="/" class="logo-link svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1></a> <img src="/froggie.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k"><a href="https://witchsky.app/profile/goose.art" target="_blank" class="subtitle-link svelte-1kxia9k">@goose.art</a> using <a href="https://witchsky.app/profile/stream.place" target="_blank" class="subtitle-link svelte-1kxia9k">@stream.place</a></p></div></header>');function Vt(t,e){J(e,!0);function s(p){e.onHomeClick&&(p.preventDefault(),e.onHomeClick())}var r=Ct(),n=y(r),a=y(n);V(2),w(n),V(2),w(r),gt("click",a,s),Z(t,r),Q()}ht(["click"]);export{Vt as F,Yt as W,E as a,qt as b,Wt as c,Ot as d,Bt as e,Nt as f,Ht as g,Dt as l,Kt as r,j as s,Tt as t};
+1
build/_app/immutable/chunks/DmyE0d-6.js
··· 1 + import{l as o,E as p,g as u,H as y,n as _,j as l,C as g,o as r,q as E,t as d,k as m,v}from"./CkzjbUDB.js";import{B as T}from"./CFYBLbZM.js";function c(a,n,...s){var i=new T(a);o(()=>{const t=n()??null;i.ensure(t,t&&(e=>t(e,...s)))},p)}function N(a,n){let s=null,i=l;var t;if(l){s=m;for(var e=v(document.head);e!==null&&(e.nodeType!==g||e.data!==a);)e=r(e);if(e===null)E(!1);else{var f=r(e);e.remove(),d(f)}}l||(t=document.head.appendChild(u()));try{o(()=>n(t),y|_)}finally{i&&(E(!0),d(s))}}export{N as h,c as s};
+1
build/_app/immutable/chunks/Dr80VTgO.js
··· 1 + import{c as w,a as S,r as b,u as h,b as o,D as T,S as e}from"./CkzjbUDB.js";function n(r,s){return r===s||r?.[e]===s}function x(r={},s,i,l){var c=w.r,d=o;return S(()=>{var f,a;return b(()=>{f=a,a=[],h(()=>{r!==i(...a)&&(s(r,...a),f&&n(i(...f),r)&&s(null,...f))})}),()=>{let t=d;for(;t!==c&&t.parent!==null&&t.parent.f&T;)t=t.parent;const p=()=>{a&&n(i(...a),r)&&s(null,...a)},u=t.teardown;t.teardown=()=>{p(),u?.()}}}),r}export{x as b};
-1
build/_app/immutable/chunks/DsupRLPE.js
··· 1 - import{e}from"./w0kPbzMq.js";e();
+1
build/_app/immutable/chunks/DxGD2b0U.js
··· 1 + import{y as i,u as a,ad as d,Z as m,c as r,Q as g}from"./CkzjbUDB.js";function _(n){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function h(n,e,s){if(n==null)return e(void 0),i;const u=a(()=>n.subscribe(e,s));return u.unsubscribe?()=>u.unsubscribe():u}const c=[];function k(n,e=i){let s=null;const u=new Set;function f(o){if(d(n,o)&&(n=o,s)){const l=!c.length;for(const t of u)t[1](),c.push(t,n);if(l){for(let t=0;t<c.length;t+=2)c[t][0](c[t+1]);c.length=0}}}function b(o){f(o(n))}function p(o,l=i){const t=[o,l];return u.add(t),u.size===1&&(s=e(f,b)||i),o(n),()=>{u.delete(t),u.size===0&&s&&(s(),s=null)}}return{set:f,update:b,subscribe:p}}function x(n){let e;return h(n,s=>e=s)(),e}function y(n){r===null&&_(),g&&r.l!==null?w(r).m.push(n):m(()=>{const e=a(n);if(typeof e=="function")return e})}function z(n){r===null&&_(),y(()=>()=>a(n))}function w(n){var e=n.l;return e.u??={a:[],b:[],m:[]}}export{z as a,x as g,y as o,h as s,k as w};
+1
build/_app/immutable/chunks/XE2G8ySY.js
··· 1 + import{w as B,x as L,y as m,z as D,A as S,B as A,l as M,j as R,F as U,E as p,G as w,I as x,t as Y,q as T,k as F,J as $,K as q,P as z,L as C,M as G,b as j,N as J,O as K,u as Q,Q as V,R as W,T as X,U as Z,V as H,W as k,S as ee,X as re}from"./CkzjbUDB.js";import{B as ne}from"./CFYBLbZM.js";import{s as ae,g as se}from"./DxGD2b0U.js";let g=!1,E=Symbol();function _e(e,n,s){const r=s[n]??={store:null,source:D(void 0),unsubscribe:m};if(r.store!==e&&!(E in s))if(r.unsubscribe(),r.store=e??null,e==null)r.source.v=void 0,r.unsubscribe=m;else{var i=!0;r.unsubscribe=ae(e,u=>{i?r.source.v=u:A(r.source,u)}),i=!1}return e&&E in s?se(e):S(r.source)}function de(){const e={};function n(){B(()=>{for(var s in e)e[s].unsubscribe();L(e,E,{enumerable:!1,value:!0})})}return[e,n]}function te(e){var n=g;try{return g=!1,[e(),g]}finally{g=n}}function le(e,n,s=!1){var r;R&&(r=F,U());var i=new ne(e),u=s?p:0;function v(t,f){if(R){var d=w(r);if(t!==parseInt(d.substring(1))){var _=x();Y(_),i.anchor=_,T(!1),i.ensure(t,f),T(!0);return}}i.ensure(t,f)}M(()=>{var t=!1;n((f,d=0)=>{t=!0,v(d,f)}),t||v(-1,null)},u)}function oe(e,n,s,r){var i=!V||(s&W)!==0,u=(s&K)!==0,v=(s&k)!==0,t=r,f=!0,d=()=>(f&&(f=!1,t=v?Q(r):r),t);let _;if(u){var O=ee in e||re in e;_=$(e,n)?.set??(O&&n in e?a=>e[n]=a:void 0)}var o,I=!1;u?[o,I]=te(()=>e[n]):o=e[n],o===void 0&&r!==void 0&&(o=d(),_&&(i&&q(),_(o)));var l;if(i?l=()=>{var a=e[n];return a===void 0?d():(f=!0,a)}:l=()=>{var a=e[n];return a!==void 0&&(t=void 0),a===void 0?t:a},i&&(s&z)===0)return l;if(_){var y=e.$$legacy;return(function(a,b){return arguments.length>0?((!i||!b||y||I)&&_(b?l():a),a):l()})}var P=!1,c=((s&X)!==0?Z:H)(()=>(P=!1,l()));u&&S(c);var N=j;return(function(a,b){if(arguments.length>0){const h=b?S(c):i&&u?C(a):a;return A(c,h),P=!0,t!==void 0&&(t=h),a}return G&&P||(N.f&J)!==0?c.v:S(c)})}export{_e as a,le as i,oe as p,de as s};
-1
build/_app/immutable/chunks/mmStoiki.js
··· 1 - import{a4 as T,a3 as d,a5 as g,a6 as w,a7 as E,x as m,h as l,f as s,a8 as y,i as N,c as _,a9 as x,l as M,aa as A}from"./w0kPbzMq.js";const C=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function L(e){return C?.createHTML(e)??e}function v(e){var t=T("template");return t.innerHTML=L(e.replaceAll("<!>","<!---->")),t.content}function a(e,t){var r=m;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function R(e,t){var r=(t&w)!==0,c=(t&E)!==0,n,i=!e.startsWith("<!>");return()=>{if(l)return a(s,null),s;n===void 0&&(n=v(i?e:"<!>"+e),r||(n=d(n)));var o=c||g?document.importNode(n,!0):n.cloneNode(!0);if(r){var f=d(o),u=o.lastChild;a(f,u)}else a(o,o);return o}}function b(e,t,r="svg"){var c=!e.startsWith("<!>"),n=`<${r}>${c?e:"<!>"+e}</${r}>`,i;return()=>{if(l)return a(s,null),s;if(!i){var o=v(n),f=d(o);for(i=document.createDocumentFragment();d(f);)i.appendChild(d(f))}var u=i.cloneNode(!0);{var p=d(u),h=u.lastChild;a(p,h)}return u}}function D(e,t){return b(e,t,"svg")}function I(e=""){if(!l){var t=_(e+"");return a(t,t),t}var r=s;return r.nodeType!==x?(r.before(r=_()),M(r)):A(r),a(r,r),r}function F(){if(l)return a(s,null),s;var e=document.createDocumentFragment(),t=document.createComment(""),r=_();return e.append(t,r),a(t,r),e}function H(e,t){if(l){var r=m;((r.f&y)===0||r.nodes.end===null)&&(r.nodes.end=s),N();return}e!==null&&e.before(t)}const O="5";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add(O);export{H as a,a as b,F as c,D as d,R as f,I as t};
-1
build/_app/immutable/chunks/w0kPbzMq.js
··· 1 - var qt=Array.isArray,Ht=Array.prototype.indexOf,le=Array.prototype.includes,Cn=Array.from,Mn=Object.defineProperty,ve=Object.getOwnPropertyDescriptor,Ut=Object.getOwnPropertyDescriptors,Vt=Object.prototype,Bt=Array.prototype,it=Object.getPrototypeOf,Je=Object.isExtensible;const zt=()=>{};function Fn(e){return e()}function Gt(e){for(var t=0;t<e.length;t++)e[t]()}function at(){var e,t,n=new Promise((r,s)=>{e=r,t=s});return{promise:n,resolve:e,reject:t}}const E=2,ie=4,we=8,ft=1<<24,q=16,M=32,J=64,Kt=128,k=512,g=1024,b=2048,F=4096,P=8192,C=16384,re=32768,Qe=1<<25,Ae=65536,Me=1<<17,$t=1<<18,ye=1<<19,ut=1<<20,jn=1<<25,Q=65536,Fe=1<<21,Oe=1<<22,V=1<<23,de=Symbol("$state"),Ln=Symbol("legacy props"),Yn=Symbol(""),Y=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Hn=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),Ne=3,ot=8;function Xt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Un(e,t,n){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Zt(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Wt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Jt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function Qt(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Vn(){throw new Error("https://svelte.dev/e/hydration_failed")}function Bn(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function en(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function tn(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function nn(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function zn(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Gn=1,Kn=2,$n=16,Xn=1,Zn=2,Wn=4,Jn=8,Qn=16,er=1,tr=2,rn="[",sn="[!",nr="[?",ln="]",Ue={},m=Symbol(),an="http://www.w3.org/1999/xhtml";function Ve(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function rr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let ee=!1;function sr(e){ee=e}let S;function ae(e){if(e===null)throw Ve(),Ue;return S=e}function lr(){return ae(K(S))}function ir(e){if(ee){if(K(S)!==null)throw Ve(),Ue;S=e}}function ar(e=1){if(ee){for(var t=e,n=S;t--;)n=K(n);S=n}}function fr(e=!0){for(var t=0,n=S;;){if(n.nodeType===ot){var r=n.data;if(r===ln){if(t===0)return n;t-=1}else(r===rn||r===sn||r[0]==="["&&!isNaN(Number(r.slice(1))))&&(t+=1)}var s=K(n);e&&n.remove(),n=s}}function ur(e){if(!e||e.nodeType!==ot)throw Ve(),Ue;return e.data}function ct(e){return e===this.v}function fn(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function _t(e){return!fn(e,this.v)}let De=!1;function or(){De=!0}let T=null;function Se(e){T=e}function cr(e,t=!1,n){T={p:T,i:!1,c:null,e:null,s:e,x:null,r:d,l:De&&!t?{s:null,u:null,$:[]}:null}}function _r(e){var t=T,n=t.e;if(n!==null){t.e=null;for(var r of n)kt(r)}return t.i=!0,T=t.p,{}}function ge(){return!De||T!==null&&T.l===null}let X=[];function vt(){var e=X;X=[],Gt(e)}function et(e){if(X.length===0&&!he){var t=X;queueMicrotask(()=>{t===X&&vt()})}X.push(e)}function un(){for(;X.length>0;)vt()}function on(e){var t=d;if(t===null)return v.f|=V,e;if((t.f&re)===0&&(t.f&ie)===0)throw e;Re(e,t)}function Re(e,t){for(;t!==null;){if((t.f&Kt)!==0){if((t.f&re)===0)throw e;try{t.b.error(e);return}catch(n){e=n}}t=t.parent}throw e}const cn=-7169;function y(e,t){e.f=e.f&cn|t}function Be(e){(e.f&k)!==0||e.deps===null?y(e,g):y(e,F)}function dt(e){if(e!==null)for(const t of e)(t.f&E)===0||(t.f&Q)===0||(t.f^=Q,dt(t.deps))}function _n(e,t,n){(e.f&b)!==0?t.add(e):(e.f&F)!==0&&n.add(e),dt(e.deps),y(e,g)}const H=new Set;let w=null,D=null,je=null,he=!1,Pe=!1,se=null,be=null;var tt=0;let vn=1;class z{id=vn++;current=new Map;previous=new Map;#a=new Set;#f=new Set;#r=new Map;#t=new Map;#_=null;#e=[];#v=[];#l=new Set;#s=new Set;#n=new Map;is_fork=!1;#u=!1;#i=new Set;#o(){return this.is_fork||this.#t.size>0}#p(){for(const r of this.#i)for(const s of r.#t.keys()){for(var t=!1,n=s;n.parent!==null;){if(this.#n.has(n)){t=!0;break}n=n.parent}if(!t)return!0}return!1}skip_effect(t){this.#n.has(t)||this.#n.set(t,{d:[],m:[]})}unskip_effect(t){var n=this.#n.get(t);if(n){this.#n.delete(t);for(var r of n.d)y(r,b),this.schedule(r);for(r of n.m)y(r,F),this.schedule(r)}}#c(){if(tt++>1e3&&(H.delete(this),hn()),!this.#o()){for(const i of this.#l)this.#s.delete(i),y(i,b),this.schedule(i);for(const i of this.#s)y(i,F),this.schedule(i)}const t=this.#e;this.#e=[],this.apply();var n=se=[],r=[],s=be=[];for(const i of t)try{this.#d(i,n,r)}catch(a){throw wt(i),a}if(w=null,s.length>0){var l=z.ensure();for(const i of s)l.schedule(i)}if(se=null,be=null,this.#o()||this.#p()){this.#h(r),this.#h(n);for(const[i,a]of this.#n)pt(i,a)}else{this.#r.size===0&&H.delete(this),this.#l.clear(),this.#s.clear();for(const i of this.#a)i(this);this.#a.clear(),nt(r),nt(n),this.#_?.resolve()}var u=w;if(this.#e.length>0){const i=u??=this;i.#e.push(...this.#e.filter(a=>!i.#e.includes(a)))}u!==null&&(H.add(u),u.#c()),H.has(this)||this.#w()}#d(t,n,r){t.f^=g;for(var s=t.first;s!==null;){var l=s.f,u=(l&(M|J))!==0,i=u&&(l&g)!==0,a=i||(l&P)!==0||this.#n.has(s);if(!a&&s.fn!==null){u?s.f^=g:(l&ie)!==0?n.push(s):Ee(s)&&((l&q)!==0&&this.#s.add(s),ue(s));var o=s.first;if(o!==null){s=o;continue}}for(;s!==null;){var f=s.next;if(f!==null){s=f;break}s=s.parent}}}#h(t){for(var n=0;n<t.length;n+=1)_n(t[n],this.#l,this.#s)}capture(t,n,r=!1){n!==m&&!this.previous.has(t)&&this.previous.set(t,n),(t.f&V)===0&&(this.current.set(t,[t.v,r]),D?.set(t,t.v))}activate(){w=this}deactivate(){w=null,D=null}flush(){try{Pe=!0,w=this,this.#c()}finally{tt=0,je=null,se=null,be=null,Pe=!1,w=null,D=null,B.clear()}}discard(){for(const t of this.#f)t(this);this.#f.clear(),H.delete(this)}register_created_effect(t){this.#v.push(t)}#w(){for(const f of H){var t=f.id<this.id,n=[];for(const[c,[_,p]]of this.current){if(f.current.has(c)){var r=f.current.get(c)[0];if(t&&_!==r)f.current.set(c,[_,p]);else continue}n.push(c)}var s=[...f.current.keys()].filter(c=>!this.current.has(c));if(s.length===0)t&&f.discard();else if(n.length>0){f.activate();var l=new Set,u=new Map;for(var i of n)ht(i,s,l,u);u=new Map;var a=[...f.current.keys()].filter(c=>this.current.has(c)?this.current.get(c)[0]!==c:!0);for(const c of this.#v)(c.f&(C|P|Me))===0&&ze(c,a,u)&&((c.f&(Oe|q))!==0?(y(c,b),f.schedule(c)):f.#l.add(c));if(f.#e.length>0){f.apply();for(var o of f.#e)f.#d(o,[],[]);f.#e=[]}f.deactivate()}}for(const f of H)f.#i.has(this)&&(f.#i.delete(this),f.#i.size===0&&!f.#o()&&(f.activate(),f.#c()))}increment(t,n){let r=this.#r.get(n)??0;if(this.#r.set(n,r+1),t){let s=this.#t.get(n)??0;this.#t.set(n,s+1)}}decrement(t,n,r){let s=this.#r.get(n)??0;if(s===1?this.#r.delete(n):this.#r.set(n,s-1),t){let l=this.#t.get(n)??0;l===1?this.#t.delete(n):this.#t.set(n,l-1)}this.#u||r||(this.#u=!0,et(()=>{this.#u=!1,this.flush()}))}transfer_effects(t,n){for(const r of t)this.#l.add(r);for(const r of n)this.#s.add(r);t.clear(),n.clear()}oncommit(t){this.#a.add(t)}ondiscard(t){this.#f.add(t)}settled(){return(this.#_??=at()).promise}static ensure(){if(w===null){const t=w=new z;Pe||(H.add(w),he||et(()=>{w===t&&t.flush()}))}return w}apply(){{D=null;return}}schedule(t){if(je=t,t.b?.is_pending&&(t.f&(ie|we|ft))!==0&&(t.f&re)===0){t.b.defer_effect(t);return}for(var n=t;n.parent!==null;){n=n.parent;var r=n.f;if(se!==null&&n===d&&(v===null||(v.f&E)===0))return;if((r&(J|M))!==0){if((r&g)===0)return;n.f^=g}}this.#e.push(n)}}function dn(e){var t=he;he=!0;try{for(var n;;){if(un(),w===null)return n;w.flush()}}finally{he=t}}function hn(){try{Qt()}catch(e){Re(e,je)}}let L=null;function nt(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if((r.f&(C|P))===0&&Ee(r)&&(L=new Set,ue(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&Nt(r),L?.size>0)){B.clear();for(const s of L){if((s.f&(C|P))!==0)continue;const l=[s];let u=s.parent;for(;u!==null;)L.has(u)&&(L.delete(u),l.push(u)),u=u.parent;for(let i=l.length-1;i>=0;i--){const a=l[i];(a.f&(C|P))===0&&ue(a)}}L.clear()}}L=null}}function ht(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(const s of e.reactions){const l=s.f;(l&E)!==0?ht(s,t,n,r):(l&(Oe|q))!==0&&(l&b)===0&&ze(s,t,r)&&(y(s,b),Ge(s))}}function ze(e,t,n){const r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(le.call(t,s))return!0;if((s.f&E)!==0&&ze(s,t,n))return n.set(s,!0),!0}return n.set(e,!1),!1}function Ge(e){w.schedule(e)}function pt(e,t){if(!((e.f&M)!==0&&(e.f&g)!==0)){(e.f&b)!==0?t.d.push(e):(e.f&F)!==0&&t.m.push(e),y(e,g);for(var n=e.first;n!==null;)pt(n,t),n=n.next}}function wt(e){y(e,g);for(var t=e.first;t!==null;)wt(t),t=t.next}function pn(e,t,n,r){const s=ge()?Ke:gn;var l=e.filter(_=>!_.settled);if(n.length===0&&l.length===0){r(t.map(s));return}var u=d,i=wn(),a=l.length===1?l[0].promise:l.length>1?Promise.all(l.map(_=>_.promise)):null;function o(_){i();try{r(_)}catch(p){(u.f&C)===0&&Re(p,u)}xe()}if(n.length===0){a.then(()=>o(t.map(s)));return}var f=yt();function c(){Promise.all(n.map(_=>yn(_))).then(_=>o([...t.map(s),..._])).catch(_=>Re(_,u)).finally(()=>f())}a?a.then(()=>{i(),c(),xe()}):c()}function wn(){var e=d,t=v,n=T,r=w;return function(l=!0){fe(e),G(t),Se(n),l&&(e.f&C)===0&&(r?.activate(),r?.apply())}}function xe(e=!0){fe(null),G(null),Se(null),e&&w?.deactivate()}function yt(){var e=d,t=e.b,n=w,r=t.is_rendered();return t.update_pending_count(1,n),n.increment(r,e),(s=!1)=>{t.update_pending_count(-1,n),n.decrement(r,e,s)}}function Ke(e){var t=E|b,n=v!==null&&(v.f&E)!==0?v:null;return d!==null&&(d.f|=ye),{ctx:T,deps:null,effects:null,equals:ct,f:t,fn:e,reactions:null,rv:0,v:m,wv:0,parent:n??d,ac:null}}function yn(e,t,n){let r=d;r===null&&Xt();var s=void 0,l=Xe(m),u=!v,i=new Map;return kn(()=>{var a=d,o=at();s=o.promise;try{Promise.resolve(e()).then(o.resolve,o.reject).finally(xe)}catch(p){o.reject(p),xe()}var f=w;if(u){if((a.f&re)!==0)var c=yt();if(r.b.is_rendered())i.get(f)?.reject(Y),i.delete(f);else{for(const p of i.values())p.reject(Y);i.clear()}i.set(f,o)}const _=(p,h=void 0)=>{if(c){var N=h===Y;c(N)}if(!(h===Y||(a.f&C)!==0)){if(f.activate(),h)l.f|=V,Ye(l,h);else{(l.f&V)!==0&&(l.f^=V),Ye(l,p);for(const[oe,me]of i){if(i.delete(oe),oe===f)break;me.reject(Y)}}f.deactivate()}};o.promise.then(_,p=>_(null,p||"unknown"))}),xn(()=>{for(const a of i.values())a.reject(Y)}),new Promise(a=>{function o(f){function c(){f===s?a(l):o(s)}f.then(c,c)}o(s)})}function vr(e){const t=Ke(e);return Pt(t),t}function gn(e){const t=Ke(e);return t.equals=_t,t}function En(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)te(t[n])}}function mn(e){for(var t=e.parent;t!==null;){if((t.f&E)===0)return(t.f&C)===0?t:null;t=t.parent}return null}function $e(e){var t,n=d;fe(mn(e));try{e.f&=~Q,En(e),t=jt(e)}finally{fe(n)}return t}function gt(e){var t=e.v,n=$e(e);if(!e.equals(n)&&(e.wv=Mt(),(!w?.is_fork||e.deps===null)&&(e.v=n,w?.capture(e,t,!0),e.deps===null))){y(e,g);return}ne||(D!==null?(xt()||w?.is_fork)&&D.set(e,n):Be(e))}function bn(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac?.abort(Y),t.teardown=zt,t.ac=null,pe(t,0),We(t))}function Et(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&ue(t)}let Le=new Set;const B=new Map;let mt=!1;function Xe(e,t){var n={f:0,v:e,reactions:null,equals:ct,rv:0,wv:0};return n}function U(e,t){const n=Xe(e);return Pt(n),n}function dr(e,t=!1,n=!0){const r=Xe(e);return t||(r.equals=_t),De&&n&&T!==null&&T.l!==null&&(T.l.s??=[]).push(r),r}function $(e,t,n=!1){v!==null&&(!I||(v.f&Me)!==0)&&ge()&&(v.f&(E|q|Oe|Me))!==0&&(O===null||!le.call(O,e))&&nn();let r=n?ce(t):t;return Ye(e,r,be)}function Ye(e,t,n=null){if(!e.equals(t)){var r=e.v;ne?B.set(e,t):B.set(e,r),e.v=t;var s=z.ensure();if(s.capture(e,r),(e.f&E)!==0){const l=e;(e.f&b)!==0&&$e(l),D===null&&Be(l)}e.wv=Mt(),bt(e,b,n),ge()&&d!==null&&(d.f&g)!==0&&(d.f&(M|J))===0&&(x===null?In([e]):x.push(e)),!s.is_fork&&Le.size>0&&!mt&&Tn()}return t}function Tn(){mt=!1;for(const e of Le)(e.f&g)!==0&&y(e,F),Ee(e)&&ue(e);Le.clear()}function Ce(e){$(e,e.v+1)}function bt(e,t,n){var r=e.reactions;if(r!==null)for(var s=ge(),l=r.length,u=0;u<l;u++){var i=r[u],a=i.f;if(!(!s&&i===d)){var o=(a&b)===0;if(o&&y(i,t),(a&E)!==0){var f=i;D?.delete(f),(a&Q)===0&&(a&k&&(i.f|=Q),bt(f,F,n))}else if(o){var c=i;(a&q)!==0&&L!==null&&L.add(c),n!==null?n.push(c):Ge(c)}}}}function ce(e){if(typeof e!="object"||e===null||de in e)return e;const t=it(e);if(t!==Vt&&t!==Bt)return e;var n=new Map,r=qt(e),s=U(0),l=W,u=i=>{if(W===l)return i();var a=v,o=W;G(null),lt(l);var f=i();return G(a),lt(o),f};return r&&n.set("length",U(e.length)),new Proxy(e,{defineProperty(i,a,o){(!("value"in o)||o.configurable===!1||o.enumerable===!1||o.writable===!1)&&en();var f=n.get(a);return f===void 0?u(()=>{var c=U(o.value);return n.set(a,c),c}):$(f,o.value,!0),!0},deleteProperty(i,a){var o=n.get(a);if(o===void 0){if(a in i){const f=u(()=>U(m));n.set(a,f),Ce(s)}}else $(o,m),Ce(s);return!0},get(i,a,o){if(a===de)return e;var f=n.get(a),c=a in i;if(f===void 0&&(!c||ve(i,a)?.writable)&&(f=u(()=>{var p=ce(c?i[a]:m),h=U(p);return h}),n.set(a,f)),f!==void 0){var _=_e(f);return _===m?void 0:_}return Reflect.get(i,a,o)},getOwnPropertyDescriptor(i,a){var o=Reflect.getOwnPropertyDescriptor(i,a);if(o&&"value"in o){var f=n.get(a);f&&(o.value=_e(f))}else if(o===void 0){var c=n.get(a),_=c?.v;if(c!==void 0&&_!==m)return{enumerable:!0,configurable:!0,value:_,writable:!0}}return o},has(i,a){if(a===de)return!0;var o=n.get(a),f=o!==void 0&&o.v!==m||Reflect.has(i,a);if(o!==void 0||d!==null&&(!f||ve(i,a)?.writable)){o===void 0&&(o=u(()=>{var _=f?ce(i[a]):m,p=U(_);return p}),n.set(a,o));var c=_e(o);if(c===m)return!1}return f},set(i,a,o,f){var c=n.get(a),_=a in i;if(r&&a==="length")for(var p=o;p<c.v;p+=1){var h=n.get(p+"");h!==void 0?$(h,m):p in i&&(h=u(()=>U(m)),n.set(p+"",h))}if(c===void 0)(!_||ve(i,a)?.writable)&&(c=u(()=>U(void 0)),$(c,ce(o)),n.set(a,c));else{_=c.v!==m;var N=u(()=>ce(o));$(c,N)}var oe=Reflect.getOwnPropertyDescriptor(i,a);if(oe?.set&&oe.set.call(f,o),!_){if(r&&typeof a=="string"){var me=n.get("length"),Ie=Number(a);Number.isInteger(Ie)&&Ie>=me.v&&$(me,Ie+1)}Ce(s)}return!0},ownKeys(i){_e(s);var a=Reflect.ownKeys(i).filter(c=>{var _=n.get(c);return _===void 0||_.v!==m});for(var[o,f]of n)f.v!==m&&!(o in i)&&a.push(o);return a},setPrototypeOf(){tn()}})}var rt,An,Sn,Tt,At;function hr(){if(rt===void 0){rt=window,An=document,Sn=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;Tt=ve(t,"firstChild").get,At=ve(t,"nextSibling").get,Je(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),Je(n)&&(n.__t=void 0)}}function ke(e=""){return document.createTextNode(e)}function qe(e){return Tt.call(e)}function K(e){return At.call(e)}function pr(e,t){if(!ee)return qe(e);var n=qe(S);if(n===null)n=S.appendChild(ke());else if(t&&n.nodeType!==Ne){var r=ke();return n?.before(r),ae(r),r}return t&&Ze(n),ae(n),n}function wr(e,t=!1){if(!ee){var n=qe(e);return n instanceof Comment&&n.data===""?K(n):n}if(t){if(S?.nodeType!==Ne){var r=ke();return S?.before(r),ae(r),r}Ze(S)}return S}function yr(e,t=1,n=!1){let r=ee?S:e;for(var s;t--;)s=r,r=K(r);if(!ee)return r;if(n){if(r?.nodeType!==Ne){var l=ke();return r===null?s?.after(l):r.before(l),ae(l),l}Ze(r)}return ae(r),r}function gr(e){e.textContent=""}function Er(){return!1}function mr(e,t,n){return document.createElementNS(an,e,void 0)}function Ze(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===Ne;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function St(e){var t=v,n=d;G(null),fe(null);try{return e()}finally{G(t),fe(n)}}function Rt(e){d===null&&(v===null&&Jt(),Wt()),ne&&Zt()}function Rn(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function j(e,t){var n=d;n!==null&&(n.f&P)!==0&&(e|=P);var r={ctx:T,deps:null,nodes:null,f:e|b|k,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};w?.register_created_effect(r);var s=r;if((e&ie)!==0)se!==null?se.push(r):z.ensure().schedule(r);else if(t!==null){try{ue(r)}catch(u){throw te(r),u}s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&(s.f&ye)===0&&(s=s.first,(e&q)!==0&&(e&Ae)!==0&&s!==null&&(s.f|=Ae))}if(s!==null&&(s.parent=n,n!==null&&Rn(s,n),v!==null&&(v.f&E)!==0&&(e&J)===0)){var l=v;(l.effects??=[]).push(s)}return r}function xt(){return v!==null&&!I}function xn(e){const t=j(we,null);return y(t,g),t.teardown=e,t}function br(e){Rt();var t=d.f,n=!v&&(t&M)!==0&&(t&re)===0;if(n){var r=T;(r.e??=[]).push(e)}else return kt(e)}function kt(e){return j(ie|ut,e)}function Tr(e){return Rt(),j(we|ut,e)}function Ar(e){z.ensure();const t=j(J|ye,e);return(n={})=>new Promise(r=>{n.outro?Dn(t,()=>{te(t),r(void 0)}):(te(t),r(void 0))})}function Sr(e){return j(ie,e)}function kn(e){return j(Oe|ye,e)}function Rr(e,t=0){return j(we|t,e)}function xr(e,t=[],n=[],r=[]){pn(r,t,n,s=>{j(we,()=>e(...s.map(_e)))})}function kr(e,t=0){var n=j(q|t,e);return n}function Or(e){return j(M|ye,e)}function Ot(e){var t=e.teardown;if(t!==null){const n=ne,r=v;st(!0),G(null);try{t.call(null)}finally{st(n),G(r)}}}function We(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){const s=n.ac;s!==null&&St(()=>{s.abort(Y)});var r=n.next;(n.f&J)!==0?n.parent=null:te(n,t),n=r}}function On(e){for(var t=e.first;t!==null;){var n=t.next;(t.f&M)===0&&te(t),t=n}}function te(e,t=!0){var n=!1;(t||(e.f&$t)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Nn(e.nodes.start,e.nodes.end),n=!0),y(e,Qe),We(e,t&&!n),pe(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(const l of r)l.stop();Ot(e),e.f^=Qe,e.f|=C;var s=e.parent;s!==null&&s.first!==null&&Nt(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Nn(e,t){for(;e!==null;){var n=e===t?null:K(e);e.remove(),e=n}}function Nt(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Dn(e,t,n=!0){var r=[];Dt(e,r,!0);var s=()=>{n&&te(e),t&&t()},l=r.length;if(l>0){var u=()=>--l||s();for(var i of r)i.out(u)}else s()}function Dt(e,t,n){if((e.f&P)===0){e.f^=P;var r=e.nodes&&e.nodes.t;if(r!==null)for(const i of r)(i.is_global||n)&&t.push(i);for(var s=e.first;s!==null;){var l=s.next,u=(s.f&Ae)!==0||(s.f&M)!==0&&(e.f&q)!==0;Dt(s,t,u?n:!1),s=l}}}function Nr(e){It(e,!0)}function It(e,t){if((e.f&P)!==0){e.f^=P,(e.f&g)===0&&(y(e,b),z.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,s=(n.f&Ae)!==0||(n.f&M)!==0;It(n,s?t:!1),n=r}var l=e.nodes&&e.nodes.t;if(l!==null)for(const u of l)(u.is_global||t)&&u.in()}}function Dr(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var s=n===r?null:K(n);t.append(n),n=s}}let Te=!1,ne=!1;function st(e){ne=e}let v=null,I=!1;function G(e){v=e}let d=null;function fe(e){d=e}let O=null;function Pt(e){v!==null&&(O===null?O=[e]:O.push(e))}let A=null,R=0,x=null;function In(e){x=e}let Ct=1,Z=0,W=Z;function lt(e){W=e}function Mt(){return++Ct}function Ee(e){var t=e.f;if((t&b)!==0)return!0;if(t&E&&(e.f&=~Q),(t&F)!==0){for(var n=e.deps,r=n.length,s=0;s<r;s++){var l=n[s];if(Ee(l)&&gt(l),l.wv>e.wv)return!0}(t&k)!==0&&D===null&&y(e,g)}return!1}function Ft(e,t,n=!0){var r=e.reactions;if(r!==null&&!(O!==null&&le.call(O,e)))for(var s=0;s<r.length;s++){var l=r[s];(l.f&E)!==0?Ft(l,t,!1):t===l&&(n?y(l,b):(l.f&g)!==0&&y(l,F),Ge(l))}}function jt(e){var t=A,n=R,r=x,s=v,l=O,u=T,i=I,a=W,o=e.f;A=null,R=0,x=null,v=(o&(M|J))===0?e:null,O=null,Se(e.ctx),I=!1,W=++Z,e.ac!==null&&(St(()=>{e.ac.abort(Y)}),e.ac=null);try{e.f|=Fe;var f=e.fn,c=f();e.f|=re;var _=e.deps,p=w?.is_fork;if(A!==null){var h;if(p||pe(e,R),_!==null&&R>0)for(_.length=R+A.length,h=0;h<A.length;h++)_[R+h]=A[h];else e.deps=_=A;if(xt()&&(e.f&k)!==0)for(h=R;h<_.length;h++)(_[h].reactions??=[]).push(e)}else!p&&_!==null&&R<_.length&&(pe(e,R),_.length=R);if(ge()&&x!==null&&!I&&_!==null&&(e.f&(E|F|b))===0)for(h=0;h<x.length;h++)Ft(x[h],e);if(s!==null&&s!==e){if(Z++,s.deps!==null)for(let N=0;N<n;N+=1)s.deps[N].rv=Z;if(t!==null)for(const N of t)N.rv=Z;x!==null&&(r===null?r=x:r.push(...x))}return(e.f&V)!==0&&(e.f^=V),c}catch(N){return on(N)}finally{e.f^=Fe,A=t,R=n,x=r,v=s,O=l,Se(u),I=i,W=a}}function Pn(e,t){let n=t.reactions;if(n!==null){var r=Ht.call(n,e);if(r!==-1){var s=n.length-1;s===0?n=t.reactions=null:(n[r]=n[s],n.pop())}}if(n===null&&(t.f&E)!==0&&(A===null||!le.call(A,t))){var l=t;(l.f&k)!==0&&(l.f^=k,l.f&=~Q),Be(l),bn(l),pe(l,0)}}function pe(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)Pn(e,n[r])}function ue(e){var t=e.f;if((t&C)===0){y(e,g);var n=d,r=Te;d=e,Te=!0;try{(t&(q|ft))!==0?On(e):We(e),Ot(e);var s=jt(e);e.teardown=typeof s=="function"?s:null,e.wv=Ct;var l}finally{Te=r,d=n}}}async function Ir(){await Promise.resolve(),dn()}function Pr(){return z.ensure().settled()}function _e(e){var t=e.f,n=(t&E)!==0;if(v!==null&&!I){var r=d!==null&&(d.f&C)!==0;if(!r&&(O===null||!le.call(O,e))){var s=v.deps;if((v.f&Fe)!==0)e.rv<Z&&(e.rv=Z,A===null&&s!==null&&s[R]===e?R++:A===null?A=[e]:A.push(e));else{(v.deps??=[]).push(e);var l=e.reactions;l===null?e.reactions=[v]:le.call(l,v)||l.push(v)}}}if(ne&&B.has(e))return B.get(e);if(n){var u=e;if(ne){var i=u.v;return((u.f&g)===0&&u.reactions!==null||Yt(u))&&(i=$e(u)),B.set(u,i),i}var a=(u.f&k)===0&&!I&&v!==null&&(Te||(v.f&k)!==0),o=(u.f&re)===0;Ee(u)&&(a&&(u.f|=k),gt(u)),a&&!o&&(Et(u),Lt(u))}if(D?.has(e))return D.get(e);if((e.f&V)!==0)throw e.v;return e.v}function Lt(e){if(e.f|=k,e.deps!==null)for(const t of e.deps)(t.reactions??=[]).push(e),(t.f&E)!==0&&(t.f&k)===0&&(Et(t),Lt(t))}function Yt(e){if(e.v===m)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(B.has(t)||(t.f&E)!==0&&Yt(t))return!0;return!1}function Cr(e){var t=I;try{return I=!0,e()}finally{I=t}}function Mr(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(de in e)He(e);else if(!Array.isArray(e))for(let t in e){const n=e[t];typeof n=="object"&&n&&de in n&&He(n)}}}function He(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let r in e)try{He(e[r],t)}catch{}const n=it(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){const r=Ut(n);for(let s in r){const l=r[s].get;if(l)try{l.call(e)}catch{}}}}}export{$t as $,_e as A,ce as B,$ as C,Qe as D,Ae as E,ne as F,C as G,Jn as H,Zn as I,Xn as J,Ke as K,gn as L,Qn as M,Ln as N,Tr as O,Wn as P,Gt as Q,Fn as R,de as S,Mr as T,cr as U,wr as V,xr as W,_r as X,pr as Y,ir as Z,yr as _,w as a,Pr as a$,ye as a0,ot as a1,K as a2,qe as a3,mr as a4,Sn as a5,er as a6,tr as a7,re as a8,Ne as a9,Vn as aA,gr as aB,Ar as aC,Cn as aD,ln as aE,Ve as aF,dn as aG,dr as aH,Ir as aI,U as aJ,vr as aK,jn as aL,Un as aM,qt as aN,Gn as aO,$n as aP,Kn as aQ,P as aR,M as aS,Yn as aT,an as aU,Hn as aV,it as aW,Ut as aX,An as aY,zt as aZ,fn as a_,Ze as aa,xt as ab,Xe as ac,Ce as ad,et as ae,Kt as af,sn as ag,nr as ah,_n as ai,fe as aj,G as ak,Se as al,z as am,on as an,v as ao,Ye as ap,ar as aq,Re as ar,zn as as,rr as at,Mn as au,xn as av,St as aw,hr as ax,rn as ay,Ue as az,Or as b,ke as c,te as d,or as e,S as f,kr as g,ee as h,lr as i,ur as j,fr as k,ae as l,Dr as m,sr as n,T as o,Dn as p,De as q,Nr as r,Er as s,Cr as t,br as u,Sr as v,Rr as w,d as x,ve as y,Bn as z};
-2
build/_app/immutable/entry/app.BiVWJwsp.js
··· 1 - const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.D6CLfhqK.js","../chunks/mmStoiki.js","../chunks/w0kPbzMq.js","../chunks/8u-mThFx.js","../chunks/C_B-Ij-b.js","../chunks/DsupRLPE.js","../assets/0.CyGpFWYY.css","../nodes/1.xyjmz21p.js","../chunks/BcVkVDn_.js","../chunks/D9RahMPT.js","../chunks/B43_79mg.js","../nodes/2.D4xyri_M.js","../chunks/C6hdjiAW.js","../assets/2.BKmFmlcI.css"])))=>i.map(i=>d[i]); 2 - import{h as I,i as G,g as H,E as W,j as J,k as K,l as X,n as D,ay as Z,f as z,C as O,N as Q,A as f,aG as $,au as ee,aH as te,U as re,O as se,u as ae,aI as ne,V as w,_ as oe,X as ce,aJ as p,Y as ie,Z as le,W as ue,aK as x}from"../chunks/w0kPbzMq.js";import{h as de,m as fe,u as me,s as he}from"../chunks/BcVkVDn_.js";import{a as P,c as A,f as V,t as _e}from"../chunks/mmStoiki.js";import{o as ve}from"../chunks/B43_79mg.js";import{B as ge,i as S}from"../chunks/C_B-Ij-b.js";import{p as T,b as j}from"../chunks/C6hdjiAW.js";function C(o,e,s){var l;I&&(l=z,G());var c=new ge(o);H(()=>{var t=e()??null;if(I){var r=J(l),a=r===Z,E=t!==null;if(a!==E){var m=K();X(m),c.anchor=m,D(!1),c.ensure(t,t&&(n=>s(n,t))),D(!0);return}}c.ensure(t,t&&(n=>s(n,t)))},W)}function ye(o){return class extends Ee{constructor(e){super({component:o,...e})}}}class Ee{#t;#e;constructor(e){var s=new Map,l=(t,r)=>{var a=te(r,!1,!1);return s.set(t,a),a};const c=new Proxy({...e.props||{},$$events:{}},{get(t,r){return f(s.get(r)??l(r,Reflect.get(t,r)))},has(t,r){return r===Q?!0:(f(s.get(r)??l(r,Reflect.get(t,r))),Reflect.has(t,r))},set(t,r,a){return O(s.get(r)??l(r,a),a),Reflect.set(t,r,a)}});this.#e=(e.hydrate?de:fe)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),(!e?.props?.$$host||e.sync===!1)&&$(),this.#t=c.$$events;for(const t of Object.keys(this.#e))t==="$set"||t==="$destroy"||t==="$on"||ee(this,t,{get(){return this.#e[t]},set(r){this.#e[t]=r},enumerable:!0});this.#e.$set=t=>{Object.assign(c,t)},this.#e.$destroy=()=>{me(this.#e)}}$set(e){this.#e.$set(e)}$on(e,s){this.#t[e]=this.#t[e]||[];const l=(...c)=>s.call(this,...c);return this.#t[e].push(l),()=>{this.#t[e]=this.#t[e].filter(c=>c!==l)}}$destroy(){this.#e.$destroy()}}const be="modulepreload",Pe=function(o,e){return new URL(o,e).href},M={},L=function(e,s,l){let c=Promise.resolve();if(s&&s.length>0){let m=function(n){return Promise.all(n.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),E=a?.nonce||a?.getAttribute("nonce");c=m(s.map(n=>{if(n=Pe(n,l),n in M)return;M[n]=!0;const d=n.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(l)for(let _=r.length-1;_>=0;_--){const i=r[_];if(i.href===n&&(!d||i.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":be,d||(u.as="script"),u.crossOrigin="",u.href=n,E&&u.setAttribute("nonce",E),document.head.appendChild(u),d)return new Promise((_,i)=>{u.addEventListener("load",_),u.addEventListener("error",()=>i(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return c.then(r=>{for(const a of r||[])a.status==="rejected"&&t(a.reason);return e().catch(t)})},Le={};var Re=V('<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px"><!></div>'),ke=V("<!> <!>",1);function we(o,e){re(e,!0);let s=T(e,"components",23,()=>[]),l=T(e,"data_0",3,null),c=T(e,"data_1",3,null);se(()=>e.stores.page.set(e.page)),ae(()=>{e.stores,e.page,e.constructors,s(),e.form,l(),c(),e.stores.page.notify()});let t=p(!1),r=p(!1),a=p(null);ve(()=>{const i=e.stores.page.subscribe(()=>{f(t)&&(O(r,!0),ne().then(()=>{O(a,document.title||"untitled page",!0)}))});return O(t,!0),i});const E=x(()=>e.constructors[1]);var m=ke(),n=w(m);{var d=i=>{const v=x(()=>e.constructors[0]);var g=A(),R=w(g);C(R,()=>f(v),(y,b)=>{j(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params},children:(k,pe)=>{var N=A(),U=w(N);C(U,()=>f(E),(Y,q)=>{j(q(Y,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),F=>s()[1]=F,()=>s()?.[1])}),P(k,N)},$$slots:{default:!0}}),k=>s()[0]=k,()=>s()?.[0])}),P(i,g)},h=i=>{const v=x(()=>e.constructors[0]);var g=A(),R=w(g);C(R,()=>f(v),(y,b)=>{j(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params}}),k=>s()[0]=k,()=>s()?.[0])}),P(i,g)};S(n,i=>{e.constructors[1]?i(d):i(h,-1)})}var u=oe(n,2);{var _=i=>{var v=Re(),g=ie(v);{var R=y=>{var b=_e();ue(()=>he(b,f(a))),P(y,b)};S(g,y=>{f(r)&&y(R)})}le(v),P(i,v)};S(u,i=>{f(t)&&i(_)})}P(o,m),ce()}const Ne=ye(we),Ie=[()=>L(()=>import("../nodes/0.D6CLfhqK.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url),()=>L(()=>import("../nodes/1.xyjmz21p.js"),__vite__mapDeps([7,1,2,5,8,9,10]),import.meta.url),()=>L(()=>import("../nodes/2.D4xyri_M.js"),__vite__mapDeps([11,1,2,10,8,4,3,12,5,13]),import.meta.url)],De=[],Me={"/":[2]},B={handleError:(({error:o})=>{console.error(o)}),reroute:(()=>{}),transport:{}},Oe=Object.fromEntries(Object.entries(B.transport).map(([o,e])=>[o,e.decode])),Ve=Object.fromEntries(Object.entries(B.transport).map(([o,e])=>[o,e.encode])),Be=!1,Ue=(o,e)=>Oe[o](e);export{Ue as decode,Oe as decoders,Me as dictionary,Ve as encoders,Be as hash,B as hooks,Le as matchers,Ie as nodes,Ne as root,De as server_loads};
+2
build/_app/immutable/entry/app.CwuxgLSd.js
··· 1 + const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.Cq8Xsn4J.js","../chunks/DGbOEUpF.js","../chunks/CkzjbUDB.js","../chunks/DmyE0d-6.js","../chunks/CFYBLbZM.js","../chunks/B46dcLgj.js","../assets/0.DIlgUleF.css","../nodes/1.BfJAtU5y.js","../chunks/BsDbD4Ku.js","../chunks/C0nNmPgn.js","../chunks/DxGD2b0U.js","../nodes/2.DCJPxWEg.js","../chunks/XE2G8ySY.js","../chunks/D_t83wNY.js","../assets/FrogHeader.8kzFzgPu.css","../chunks/Dr80VTgO.js","../assets/2.CHt1yucP.css","../nodes/3.CW9t1woG.js","../assets/3.CjGf6tQE.css"])))=>i.map(i=>d[i]); 2 + import{j as I,F as U,l as z,E as H,G as W,I as X,t as Z,q as D,aF as J,k as K,B as O,X as Q,A as f,aN as $,x as ee,z as te,a1 as re,Y as se,Z as ae,aO as ne,a2 as k,a7 as oe,a4 as ce,ab as x,a5 as ie,a6 as le,a3 as ue,ac as A}from"../chunks/CkzjbUDB.js";import{h as de,m as fe,u as me,s as he}from"../chunks/BsDbD4Ku.js";import{a as P,c as S,f as F,t as _e}from"../chunks/DGbOEUpF.js";import{o as ve}from"../chunks/DxGD2b0U.js";import{p as T,i as j}from"../chunks/XE2G8ySY.js";import{B as ge}from"../chunks/CFYBLbZM.js";import{b as L}from"../chunks/Dr80VTgO.js";function C(o,e,s){var l;I&&(l=K,U());var c=new ge(o);z(()=>{var t=e()??null;if(I){var r=W(l),a=r===J,E=t!==null;if(a!==E){var m=X();Z(m),c.anchor=m,D(!1),c.ensure(t,t&&(n=>s(n,t))),D(!0);return}}c.ensure(t,t&&(n=>s(n,t)))},H)}function ye(o){return class extends Ee{constructor(e){super({component:o,...e})}}}class Ee{#t;#e;constructor(e){var s=new Map,l=(t,r)=>{var a=te(r,!1,!1);return s.set(t,a),a};const c=new Proxy({...e.props||{},$$events:{}},{get(t,r){return f(s.get(r)??l(r,Reflect.get(t,r)))},has(t,r){return r===Q?!0:(f(s.get(r)??l(r,Reflect.get(t,r))),Reflect.has(t,r))},set(t,r,a){return O(s.get(r)??l(r,a),a),Reflect.set(t,r,a)}});this.#e=(e.hydrate?de:fe)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),(!e?.props?.$$host||e.sync===!1)&&$(),this.#t=c.$$events;for(const t of Object.keys(this.#e))t==="$set"||t==="$destroy"||t==="$on"||ee(this,t,{get(){return this.#e[t]},set(r){this.#e[t]=r},enumerable:!0});this.#e.$set=t=>{Object.assign(c,t)},this.#e.$destroy=()=>{me(this.#e)}}$set(e){this.#e.$set(e)}$on(e,s){this.#t[e]=this.#t[e]||[];const l=(...c)=>s.call(this,...c);return this.#t[e].push(l),()=>{this.#t[e]=this.#t[e].filter(c=>c!==l)}}$destroy(){this.#e.$destroy()}}const be="modulepreload",Pe=function(o,e){return new URL(o,e).href},B={},w=function(e,s,l){let c=Promise.resolve();if(s&&s.length>0){let m=function(n){return Promise.all(n.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),E=a?.nonce||a?.getAttribute("nonce");c=m(s.map(n=>{if(n=Pe(n,l),n in B)return;B[n]=!0;const d=n.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(l)for(let _=r.length-1;_>=0;_--){const i=r[_];if(i.href===n&&(!d||i.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${h}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":be,d||(u.as="script"),u.crossOrigin="",u.href=n,E&&u.setAttribute("nonce",E),document.head.appendChild(u),d)return new Promise((_,i)=>{u.addEventListener("load",_),u.addEventListener("error",()=>i(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return c.then(r=>{for(const a of r||[])a.status==="rejected"&&t(a.reason);return e().catch(t)})},Ne={};var Re=F('<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px"><!></div>'),pe=F("<!> <!>",1);function ke(o,e){re(e,!0);let s=T(e,"components",23,()=>[]),l=T(e,"data_0",3,null),c=T(e,"data_1",3,null);se(()=>e.stores.page.set(e.page)),ae(()=>{e.stores,e.page,e.constructors,s(),e.form,l(),c(),e.stores.page.notify()});let t=x(!1),r=x(!1),a=x(null);ve(()=>{const i=e.stores.page.subscribe(()=>{f(t)&&(O(r,!0),ne().then(()=>{O(a,document.title||"untitled page",!0)}))});return O(t,!0),i});const E=A(()=>e.constructors[1]);var m=pe(),n=k(m);{var d=i=>{const v=A(()=>e.constructors[0]);var g=S(),R=k(g);C(R,()=>f(v),(y,b)=>{L(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params},children:(p,Oe)=>{var N=S(),V=k(N);C(V,()=>f(E),(q,Y)=>{L(Y(q,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),G=>s()[1]=G,()=>s()?.[1])}),P(p,N)},$$slots:{default:!0}}),p=>s()[0]=p,()=>s()?.[0])}),P(i,g)},h=i=>{const v=A(()=>e.constructors[0]);var g=S(),R=k(g);C(R,()=>f(v),(y,b)=>{L(b(y,{get data(){return l()},get form(){return e.form},get params(){return e.page.params}}),p=>s()[0]=p,()=>s()?.[0])}),P(i,g)};j(n,i=>{e.constructors[1]?i(d):i(h,-1)})}var u=oe(n,2);{var _=i=>{var v=Re(),g=ie(v);{var R=y=>{var b=_e();ue(()=>he(b,f(a))),P(y,b)};j(g,y=>{f(r)&&y(R)})}le(v),P(i,v)};j(u,i=>{f(t)&&i(_)})}P(o,m),ce()}const Ie=ye(ke),De=[()=>w(()=>import("../nodes/0.Cq8Xsn4J.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url),()=>w(()=>import("../nodes/1.BfJAtU5y.js"),__vite__mapDeps([7,1,2,5,8,9,10]),import.meta.url),()=>w(()=>import("../nodes/2.DCJPxWEg.js"),__vite__mapDeps([11,1,2,10,8,12,4,3,13,14,15,16]),import.meta.url),()=>w(()=>import("../nodes/3.CW9t1woG.js"),__vite__mapDeps([17,1,2,10,8,12,4,3,13,14,9,18]),import.meta.url)],Be=[],Fe={"/":[2],"/profile/[handle]":[3]},M={handleError:(({error:o})=>{console.error(o)}),reroute:(()=>{}),transport:{}},we=Object.fromEntries(Object.entries(M.transport).map(([o,e])=>[o,e.decode])),Me=Object.fromEntries(Object.entries(M.transport).map(([o,e])=>[o,e.encode])),Ve=!1,qe=(o,e)=>we[o](e);export{qe as decode,we as decoders,Fe as dictionary,Me as encoders,Ve as hash,M as hooks,Ne as matchers,De as nodes,Ie as root,Be as server_loads};
+1
build/_app/immutable/entry/start.BUzUbSG3.js
··· 1 + import{l as o,a as r}from"../chunks/C0nNmPgn.js";export{o as load_css,r as start};
-1
build/_app/immutable/entry/start.YsP-T6iU.js
··· 1 - import{l as o,a as r}from"../chunks/D9RahMPT.js";export{o as load_css,r as start};
+7
build/_app/immutable/nodes/0.Cq8Xsn4J.js
··· 1 + import{a as s,f as r}from"../chunks/DGbOEUpF.js";import{a2 as f,aa as d,a7 as p}from"../chunks/CkzjbUDB.js";import{h as g,s as h}from"../chunks/DmyE0d-6.js";import"../chunks/B46dcLgj.js";const v=!0,m=!1,A=Object.freeze(Object.defineProperty({__proto__:null,prerender:v,ssr:m},Symbol.toStringTag,{value:"Module"}));var y=r('<div class="mesh-bg svelte-17k46oa"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" preserveAspectRatio="none" class="mesh-svg svelte-17k46oa"><defs><radialGradient id="g1" cx="50%" cy="40%" r="70%"><stop offset="0%" stop-color="#39FF44"></stop><stop offset="60%" stop-color="#2BBF33"></stop><stop offset="100%" stop-color="#1A8C22"></stop></radialGradient><radialGradient id="g2" cx="90%" cy="5%" r="45%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.9"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.4"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g3" cx="5%" cy="95%" r="40%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.7"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g4" cx="15%" cy="10%" r="50%"><stop offset="0%" stop-color="#5FFF66" stop-opacity="0.6"></stop><stop offset="100%" stop-color="#39FF44" stop-opacity="0"></stop></radialGradient><radialGradient id="g5" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#4AFF54" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#2BBF33" stop-opacity="0"></stop></radialGradient></defs><rect width="1000" height="1000" fill="url(#g1)"></rect><rect width="1000" height="1000" fill="url(#g2)"></rect><rect width="1000" height="1000" fill="url(#g3)"></rect><rect width="1000" height="1000" fill="url(#g4)"></rect><rect width="1000" height="1000" fill="url(#g5)"></rect></svg></div>');function u(t){var o=y();s(t,o)}var F=r('<div class="plant-overlay svelte-11afcec"><img src="/leaves.png" alt="" class="leaves svelte-11afcec"/></div>');function w(t){var o=F();s(t,o)}var _=r(`<link rel="icon" href="/frogicon.png"/> <link rel="preconnect" href="https://fonts.googleapis.com"/> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"/> <link href="https://fonts.googleapis.com/css2?family=Shrikhand&amp;family=Nunito:wght@400;700&amp;display=swap" rel="stylesheet"/> <style>/* Cursor must be in global head style to override everything */ 2 + *, *::before, *::after { 3 + cursor: url('/frogcursor-small.png') 8 4, auto !important; 4 + } 5 + a, button, [role="button"], input[type="submit"], select, summary { 6 + cursor: url('/frogcursor-small.png') 8 4, pointer !important; 7 + }</style>`,1),b=r("<!> <!> <!>",1);function O(t,o){var e=b();g("12qhfyh",c=>{var n=_();d(8),s(c,n)});var a=f(e);u(a);var i=p(a,2);w(i);var l=p(i,2);h(l,()=>o.children),s(t,e)}export{O as component,A as universal};
-7
build/_app/immutable/nodes/0.D6CLfhqK.js
··· 1 - import{a as o,f as c,d as v}from"../chunks/mmStoiki.js";import{W as g,Y as d,Z as x,aq as y,V as h,_ as n}from"../chunks/w0kPbzMq.js";import{s as u,h as B,a as A}from"../chunks/8u-mThFx.js";import"../chunks/DsupRLPE.js";import{i as F}from"../chunks/C_B-Ij-b.js";const _=!0,w=!1,z=Object.freeze(Object.defineProperty({__proto__:null,prerender:_,ssr:w},Symbol.toStringTag,{value:"Module"}));var b=c('<div class="mesh-bg svelte-17k46oa"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" preserveAspectRatio="none" class="mesh-svg svelte-17k46oa"><defs><radialGradient id="g1" cx="50%" cy="40%" r="70%"><stop offset="0%" stop-color="#39FF44"></stop><stop offset="60%" stop-color="#2BBF33"></stop><stop offset="100%" stop-color="#1A8C22"></stop></radialGradient><radialGradient id="g2" cx="90%" cy="5%" r="45%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.9"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.4"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g3" cx="5%" cy="95%" r="40%"><stop offset="0%" stop-color="#3992FF" stop-opacity="0.7"></stop><stop offset="50%" stop-color="#3992FF" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#3992FF" stop-opacity="0"></stop></radialGradient><radialGradient id="g4" cx="15%" cy="10%" r="50%"><stop offset="0%" stop-color="#5FFF66" stop-opacity="0.6"></stop><stop offset="100%" stop-color="#39FF44" stop-opacity="0"></stop></radialGradient><radialGradient id="g5" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#4AFF54" stop-opacity="0.3"></stop><stop offset="100%" stop-color="#2BBF33" stop-opacity="0"></stop></radialGradient></defs><rect width="1000" height="1000" fill="url(#g1)"></rect><rect width="1000" height="1000" fill="url(#g2)"></rect><rect width="1000" height="1000" fill="url(#g3)"></rect><rect width="1000" height="1000" fill="url(#g4)"></rect><rect width="1000" height="1000" fill="url(#g5)"></rect></svg></div>');function k(l){var e=b();o(l,e)}var G=v('<path d="M 50 900 Q 55 780 42 660 Q 35 540 48 420 Q 55 300 40 180 Q 30 80 50 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="42" cy="140" rx="40" ry="14" fill="#0A182B" transform="rotate(-35 42 140)"></ellipse><ellipse cx="48" cy="290" rx="44" ry="15" fill="#0A182B" transform="rotate(25 48 290)"></ellipse><ellipse cx="38" cy="440" rx="38" ry="13" fill="#0A182B" transform="rotate(-30 38 440)"></ellipse><ellipse cx="52" cy="570" rx="42" ry="14" fill="#0A182B" transform="rotate(20 52 570)"></ellipse><ellipse cx="44" cy="710" rx="40" ry="14" fill="#0A182B" transform="rotate(-22 44 710)"></ellipse><ellipse cx="48" cy="830" rx="36" ry="12" fill="#0A182B" transform="rotate(18 48 830)"></ellipse><ellipse cx="55" cy="210" rx="28" ry="10" fill="#0A182B" transform="rotate(40 55 210)"></ellipse><ellipse cx="50" cy="370" rx="24" ry="9" fill="#0A182B" transform="rotate(35 50 370)"></ellipse><ellipse cx="45" cy="510" rx="30" ry="11" fill="#0A182B" transform="rotate(-28 45 510)"></ellipse><ellipse cx="52" cy="650" rx="26" ry="9" fill="#0A182B" transform="rotate(30 52 650)"></ellipse><ellipse cx="40" cy="780" rx="22" ry="8" fill="#0A182B" transform="rotate(-25 40 780)"></ellipse>',1),Q=v('<path d="M 110 900 Q 105 780 118 660 Q 125 540 112 420 Q 105 300 120 180 Q 130 80 110 0" stroke="#0A182B" stroke-width="7" fill="none" stroke-linecap="round"></path><ellipse cx="118" cy="170" rx="40" ry="14" fill="#0A182B" transform="rotate(35 118 170)"></ellipse><ellipse cx="112" cy="320" rx="44" ry="15" fill="#0A182B" transform="rotate(-25 112 320)"></ellipse><ellipse cx="122" cy="470" rx="38" ry="13" fill="#0A182B" transform="rotate(30 122 470)"></ellipse><ellipse cx="108" cy="610" rx="42" ry="14" fill="#0A182B" transform="rotate(-20 108 610)"></ellipse><ellipse cx="116" cy="750" rx="40" ry="14" fill="#0A182B" transform="rotate(22 116 750)"></ellipse><ellipse cx="112" cy="860" rx="36" ry="12" fill="#0A182B" transform="rotate(-18 112 860)"></ellipse><ellipse cx="105" cy="240" rx="28" ry="10" fill="#0A182B" transform="rotate(-40 105 240)"></ellipse><ellipse cx="110" cy="400" rx="24" ry="9" fill="#0A182B" transform="rotate(-35 110 400)"></ellipse><ellipse cx="115" cy="540" rx="30" ry="11" fill="#0A182B" transform="rotate(28 115 540)"></ellipse><ellipse cx="108" cy="680" rx="26" ry="9" fill="#0A182B" transform="rotate(-30 108 680)"></ellipse>',1),M=c('<div><svg viewBox="0 0 160 900" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" class="svelte-11afcec"><!></svg></div>');function m(l,e){var t=M(),s=d(t),a=d(s);{var p=r=>{var i=G();y(11),o(r,i)},f=r=>{var i=Q();y(10),o(r,i)};F(a,r=>{e.side==="left"?r(p):r(f,-1)})}x(s),x(t),g(()=>u(t,1,`plant-overlay ${e.side??""}`,"svelte-11afcec")),o(l,t)}var O=c(`<link rel="icon" href="/frogcursor.png"/> <style>/* Cursor must be in global head style to override everything */ 2 - *, *::before, *::after { 3 - cursor: url('/frogcursor-small.png') 8 4, auto !important; 4 - } 5 - a, button, [role="button"], input[type="submit"], select, summary { 6 - cursor: url('/frogcursor-small.png') 8 4, pointer !important; 7 - }</style>`,1),j=c("<!> <!> <!> <!>",1);function T(l,e){var t=j();B("12qhfyh",r=>{var i=O();y(2),o(r,i)});var s=h(t);k(s);var a=n(s,2);m(a,{side:"left"});var p=n(a,2);m(p,{side:"right"});var f=n(p,2);A(f,()=>e.children),o(l,t)}export{T as component,z as universal};
+1
build/_app/immutable/nodes/1.BfJAtU5y.js
··· 1 + import{a as b,f as k}from"../chunks/DGbOEUpF.js";import"../chunks/B46dcLgj.js";import{c as x,Y as $,Z as i,u as y,_ as l,$ as A,A as v,a0 as E,U,a1 as Y,a2 as Z,a3 as j,a4 as q,a5 as u,a6 as m,a7 as w}from"../chunks/CkzjbUDB.js";import{s as _}from"../chunks/BsDbD4Ku.js";import{s as z,p as g}from"../chunks/C0nNmPgn.js";function B(r=!1){const e=x,t=e.l.u;if(!t)return;let a=()=>E(e.s);if(r){let o=0,s={};const f=U(()=>{let p=!1;const c=e.s;for(const n in c)c[n]!==s[n]&&(s[n]=c[n],p=!0);return p&&o++,o});a=()=>v(f)}t.b.length&&$(()=>{h(e,a),l(t.b)}),i(()=>{const o=y(()=>t.m.map(A));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{h(e,a),l(t.a)})}function h(r,e){if(r.l.s)for(const t of r.l.s)v(t);e()}const C={get error(){return g.error},get status(){return g.status}};z.updated.check;const d=C;var D=k("<h1> </h1> <p> </p>",1);function K(r,e){Y(e,!1),B();var t=D(),a=Z(t),o=u(a,!0);m(a);var s=w(a,2),f=u(s,!0);m(s),j(()=>{_(o,d.status),_(f,d.error?.message)}),b(r,t),q()}export{K as component};
-1
build/_app/immutable/nodes/1.xyjmz21p.js
··· 1 - import{a as b,f as k}from"../chunks/mmStoiki.js";import"../chunks/DsupRLPE.js";import{o as x,O as $,u as i,t as y,Q as l,R as A,A as v,T as E,K,U as O,V as Q,W as R,X as T,Y as u,Z as m,_ as U}from"../chunks/w0kPbzMq.js";import{s as _}from"../chunks/BcVkVDn_.js";import{s as V,p as g}from"../chunks/D9RahMPT.js";function W(a=!1){const e=x,t=e.l.u;if(!t)return;let r=()=>E(e.s);if(a){let o=0,s={};const f=K(()=>{let c=!1;const p=e.s;for(const n in p)p[n]!==s[n]&&(s[n]=p[n],c=!0);return c&&o++,o});r=()=>v(f)}t.b.length&&$(()=>{h(e,r),l(t.b)}),i(()=>{const o=y(()=>t.m.map(A));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{h(e,r),l(t.a)})}function h(a,e){if(a.l.s)for(const t of a.l.s)v(t);e()}const X={get error(){return g.error},get status(){return g.status}};V.updated.check;const d=X;var Y=k("<h1> </h1> <p> </p>",1);function B(a,e){O(e,!1),W();var t=Y(),r=Q(t),o=u(r,!0);m(r);var s=U(r,2),f=u(s,!0);m(s),R(()=>{_(o,d.status),_(f,d.error?.message)}),b(a,t),T()}export{B as component};
-40
build/_app/immutable/nodes/2.D4xyri_M.js
··· 1 - import{a as we,f as Fe}from"../chunks/mmStoiki.js";import{o as zn,a as $o}from"../chunks/B43_79mg.js";import{c as Xs,g as Go,h as ct,l as zs,a3 as Ko,i as Vo,A as H,j as Ho,ag as Yo,k as Lr,n as Qs,f as ns,a1 as Wo,aE as qo,ap as Rr,a as jo,aL as ht,b as Li,aM as Xo,s as zo,L as Qo,aN as Zo,aD as Xi,aO as Jo,aP as el,aH as tl,ac as br,aQ as sl,G as il,r as Qn,p as Zn,aR as Zs,aS as rl,aB as nl,m as al,d as ol,a2 as ll,aT as cl,aU as hl,aV as ul,aW as dl,aX as fl,U as Vs,Y as he,aq as Jn,Z as oe,_ as ye,W as Ze,X as Hs,u as gl,C as se,aJ as xe,B as ea,V as ml,aK as ta,v as pl,aY as yl}from"../chunks/w0kPbzMq.js";import{s as qe,d as sa,e as _r,a as Ps}from"../chunks/BcVkVDn_.js";import{i as It}from"../chunks/C_B-Ij-b.js";import{t as El,a as vl,s as Dr,h as Tl}from"../chunks/8u-mThFx.js";import{p as as,b as Ri}from"../chunks/C6hdjiAW.js";import"../chunks/DsupRLPE.js";function Sl(a,e,t){for(var s=[],i=e.length,r,n=e.length,o=0;o<i;o++){let u=e[o];Zn(u,()=>{if(r){if(r.pending.delete(u),r.done.add(u),r.pending.size===0){var d=a.outrogroups;bi(a,Xi(r.done)),d.delete(r),d.size===0&&(a.outrogroups=null)}}else n-=1},!1)}if(n===0){var c=s.length===0&&t!==null;if(c){var l=t,h=l.parentNode;nl(h),h.append(l),a.items.clear()}bi(a,e,!c)}else r={pending:new Set(e),done:new Set},(a.outrogroups??=new Set).add(r)}function bi(a,e,t=!0){var s;if(a.pending.size>0){s=new Set;for(const n of a.pending.values())for(const o of n)s.add(a.items.get(o).e)}for(var i=0;i<e.length;i++){var r=e[i];if(s?.has(r)){r.f|=ht;const n=document.createDocumentFragment();al(r,n)}else ol(e[i],t)}}var Cr;function xl(a,e,t,s,i,r=null){var n=a,o=new Map;{var c=a;n=ct?zs(Ko(c)):c.appendChild(Xs())}ct&&Vo();var l=null,h=Qo(()=>{var v=t();return Zo(v)?v:v==null?[]:Xi(v)}),u,d=new Map,g=!0;function f(v){(E.effect.f&il)===0&&(E.pending.delete(v),E.fallback=l,Al(E,u,n,e,s),l!==null&&(u.length===0?(l.f&ht)===0?Qn(l):(l.f^=ht,Yt(l,null,n)):Zn(l,()=>{l=null})))}function p(v){E.pending.delete(v)}var y=Go(()=>{u=H(h);var v=u.length;let T=!1;if(ct){var x=Ho(n)===Yo;x!==(v===0)&&(n=Lr(),zs(n),Qs(!1),T=!0)}for(var S=new Set,R=jo,A=zo(),I=0;I<v;I+=1){ct&&ns.nodeType===Wo&&ns.data===qo&&(n=ns,T=!0,Qs(!1));var b=u[I],L=s(b,I),C=g?null:o.get(L);C?(C.v&&Rr(C.v,b),C.i&&Rr(C.i,I),A&&R.unskip_effect(C.e)):(C=Il(o,g?n:Cr??=Xs(),b,L,I,i,e,t),g||(C.e.f|=ht),o.set(L,C)),S.add(L)}if(v===0&&r&&!l&&(g?l=Li(()=>r(n)):(l=Li(()=>r(Cr??=Xs())),l.f|=ht)),v>S.size&&Xo(),ct&&v>0&&zs(Lr()),!g)if(d.set(R,S),A){for(const[w,U]of o)S.has(w)||R.skip_effect(U.e);R.oncommit(f),R.ondiscard(p)}else f(R);T&&Qs(!0),H(h)}),E={effect:y,items:o,pending:d,outrogroups:null,fallback:l};g=!1,ct&&(n=ns)}function Vt(a){for(;a!==null&&(a.f&rl)===0;)a=a.next;return a}function Al(a,e,t,s,i){var r=e.length,n=a.items,o=Vt(a.effect.first),c,l=null,h=[],u=[],d,g,f,p;for(p=0;p<r;p+=1){if(d=e[p],g=i(d,p),f=n.get(g).e,a.outrogroups!==null)for(const I of a.outrogroups)I.pending.delete(f),I.done.delete(f);if((f.f&Zs)!==0&&Qn(f),(f.f&ht)!==0)if(f.f^=ht,f===o)Yt(f,null,t);else{var y=l?l.next:o;f===a.effect.last&&(a.effect.last=f.prev),f.prev&&(f.prev.next=f.next),f.next&&(f.next.prev=f.prev),ut(a,l,f),ut(a,f,y),Yt(f,y,t),l=f,h=[],u=[],o=Vt(l.next);continue}if(f!==o){if(c!==void 0&&c.has(f)){if(h.length<u.length){var E=u[0],v;l=E.prev;var T=h[0],x=h[h.length-1];for(v=0;v<h.length;v+=1)Yt(h[v],E,t);for(v=0;v<u.length;v+=1)c.delete(u[v]);ut(a,T.prev,x.next),ut(a,l,T),ut(a,x,E),o=E,l=x,p-=1,h=[],u=[]}else c.delete(f),Yt(f,o,t),ut(a,f.prev,f.next),ut(a,f,l===null?a.effect.first:l.next),ut(a,l,f),l=f;continue}for(h=[],u=[];o!==null&&o!==f;)(c??=new Set).add(o),u.push(o),o=Vt(o.next);if(o===null)continue}(f.f&ht)===0&&h.push(f),l=f,o=Vt(f.next)}if(a.outrogroups!==null){for(const I of a.outrogroups)I.pending.size===0&&(bi(a,Xi(I.done)),a.outrogroups?.delete(I));a.outrogroups.size===0&&(a.outrogroups=null)}if(o!==null||c!==void 0){var S=[];if(c!==void 0)for(f of c)(f.f&Zs)===0&&S.push(f);for(;o!==null;)(o.f&Zs)===0&&o!==a.fallback&&S.push(o),o=Vt(o.next);var R=S.length;if(R>0){var A=r===0?t:null;Sl(a,S,A)}}}function Il(a,e,t,s,i,r,n,o){var c=(n&Jo)!==0?(n&el)===0?tl(t,!1,!1):br(t):null,l=(n&sl)!==0?br(i):null;return{v:c,i:l,e:Li(()=>(r(e,c??t,l??i,o),()=>{a.delete(s)}))}}function Yt(a,e,t){if(a.nodes)for(var s=a.nodes.start,i=a.nodes.end,r=e&&(e.f&ht)===0?e.nodes.start:t;s!==null;){var n=ll(s);if(r.before(s),s===i)return;s=n}}function ut(a,e,t){e===null?a.effect.first=t:e.next=t,t===null?a.effect.last=e:t.prev=e}function _i(a,e,t,s){var i=a.__style;if(ct||i!==e){var r=El(e);(!ct||r!==a.getAttribute("style"))&&(r==null?a.removeAttribute("style"):a.style.cssText=r),a.__style=e}return s}const Ll=Symbol("is custom element"),Rl=Symbol("is html"),bl=ul?"link":"LINK";function at(a,e,t,s){var i=_l(a);ct&&(i[e]=a.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&a.nodeName===bl)||i[e]!==(i[e]=t)&&(e==="loading"&&(a[cl]=t),t==null?a.removeAttribute(e):typeof t!="string"&&Dl(a).includes(e)?a[e]=t:a.setAttribute(e,t))}function _l(a){return a.__attributes??={[Ll]:a.nodeName.includes("-"),[Rl]:a.namespaceURI===hl}}var Pr=new Map;function Dl(a){var e=a.getAttribute("is")||a.nodeName,t=Pr.get(e);if(t)return t;Pr.set(e,t=[]);for(var s,i=a,r=Element.prototype;r!==i;){s=fl(i);for(var n in s)s[n].set&&t.push(n);i=dl(i)}return t}const Cl="https://iameli.com",Pl="did:plc:rbvrr34edl5ddpuwcubjiost",kl="place.stream.video",wl="https://vod-beta.stream.place/xrpc/place.stream.playback.getVideoPlaylist";async function Ol(a,e=20){const t=new URLSearchParams({repo:Pl,collection:kl,limit:String(e)});a&&t.set("cursor",a);const s=await fetch(`${Cl}/xrpc/com.atproto.repo.listRecords?${t}`);if(!s.ok)throw new Error(`Failed to fetch records: ${s.status}`);return s.json()}function ia(a){return`${wl}?uri=${encodeURIComponent(a)}`}function ra(a){const e=Math.floor(a/1e9),t=Math.floor(e/3600),s=Math.floor(e%3600/60),i=e%60;return t>0?`${t}:${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`:`${s}:${String(i).padStart(2,"0")}`}function na(a){return new Date(a).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const Js=new Map;async function aa(a){if(Js.has(a))return Js.get(a);try{const e=await fetch(`https://plc.directory/${a}`);if(!e.ok)return a;const s=(await e.json()).alsoKnownAs?.[0],i=s?s.replace("at://","@"):a;return Js.set(a,i),i}catch{return a}}const ei=new Map;async function Fl(a){if(ei.has(a))return ei.get(a);try{const e=await fetch(`https://plc.directory/${a}`);if(!e.ok)return null;const i=(await e.json()).service?.find(r=>r.id==="#atproto_pds"||r.type==="AtprotoPersonalDataServer")?.serviceEndpoint??null;return i&&ei.set(a,i),i}catch{return null}}function Ml(a){const e=a.match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);return e?{repo:e[1],collection:e[2],rkey:e[3]}:null}const os=new Map;async function Nl(a){const e=a.value.livestream?.uri;if(!e)return null;if(os.has(e))return os.get(e);try{const t=Ml(e);if(!t)return null;const s=await Fl(t.repo);if(!s)return null;const i=new URLSearchParams({repo:t.repo,collection:t.collection,rkey:t.rkey}),r=await fetch(`${s}/xrpc/com.atproto.repo.getRecord?${i}`);if(!r.ok)return null;const o=(await r.json()).value?.thumb?.ref?.$link;if(!o)return null;const c=`${s}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(t.repo)}&cid=${encodeURIComponent(o)}`;return os.set(e,c),c}catch{return os.set(e,null),null}}const G=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Bl=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Ul},Ul=Number.MAX_SAFE_INTEGER||9007199254740991;let Y=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),D=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a})({}),m=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a})({});var J={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class bt{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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 $l{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new bt(e),this.fast_=new bt(t),this.defaultTTFB_=i,this.ttfb_=new bt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new bt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new bt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new bt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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 Gl(a,e,t){return(e=Vl(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ne(){return ne=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ne.apply(null,arguments)}function kr(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function ie(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kr(Object(t),!0).forEach(function(s){Gl(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):kr(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Kl(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Vl(a){var e=Kl(a,"string");return typeof e=="symbol"?e:e+""}class Ve{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=gt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const gt=function(){},Hl={trace:gt,debug:gt,log:gt,warn:gt,info:gt,error:gt};function Di(){return ne({},Hl)}function Yl(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):gt}function wr(a,e,t){return e[a]?e[a].bind(e):Yl(a,t)}const Ci=Di();function Wl(a,e,t){const s=Di();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=wr(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Di()}i.forEach(r=>{Ci[r]=wr(r,a)})}else ne(Ci,s);return s}const re=Ci;function Et(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ql(a){return typeof self<"u"&&a===self.ManagedMediaSource}function oa(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function $e(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function Le(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function la(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function jl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ti={exports:{}},Or;function Xl(){return Or||(Or=1,(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var y=g.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()})(ti)),ti.exports}var zi=Xl();class Qi{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ca{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ql(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[le.AUDIO]:null,[le.VIDEO]:null,[le.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Qi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=zi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}}function me(a){return a.sn!=="initSegment"}class si extends ca{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(G(e)&&G(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=G(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return me(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 s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class zl extends ca{constructor(e,t,s,i,r){super(s),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=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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 ha(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||ha(t,e)}}function Ql(a,e){const t=ha(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Fr=Math.pow(2,32)-1,Zl=[].push,ua={video:1,audio:2,id3:3,text:4};function pe(a){return String.fromCharCode.apply(null,a)}function da(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function q(a,e){const t=fa(a,e);return t<0?4294967296+t:t}function Mr(a,e){let t=q(a,e);return t*=Math.pow(2,32),t+=q(a,e+4),t}function fa(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Jl(a){const e=a.byteLength;for(let t=0;t<e;){const s=q(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Q(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=q(a,i),n=pe(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=Q(a.subarray(i+8,o),e.slice(1));c.length&&Zl.apply(t,c)}i=o}return t}function ec(a){const e=[],t=a[0];let s=8;const i=q(a,s);s+=4;let r=0,n=0;t===0?(r=q(a,s),n=q(a,s+4),s+=8):(r=Mr(a,s),n=Mr(a,s+8),s+=16),s+=2;let o=a.length+n;const c=da(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=q(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return re.warn("SIDX has hierarchical references (not supported)"),null;const f=q(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function ga(a){const e=[],t=Q(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=Q(r,["tkhd"])[0];if(n){let o=n[0];const c=q(n,o===0?12:20),l=Q(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=q(l,o===0?12:20),u=Q(r,["mdia","hdlr"])[0];if(u){const d=pe(u.subarray(8,12)),g={soun:le.AUDIO,vide:le.VIDEO}[d],f=Q(r,["mdia","minf","stbl","stsd"])[0],p=tc(f);g?(e[c]={timescale:h,type:g,stsd:p},e[g]=ie({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return Q(a,["moov","mvex","trex"]).forEach(i=>{const r=q(i,4),n=e[r];n&&(n.default={duration:q(i,12),flags:q(i,20)})}),e}function tc(a){const e=a.subarray(8),t=e.subarray(86),s=pe(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=Q(e,[s])[0].subarray(s==="enca"?28:78);Q(l,["sinf"]).forEach(u=>{const d=Q(u,["schm"])[0];if(d){const g=pe(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=Q(u,["frma"])[0];f&&(i=pe(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Q(t,["avcC"])[0];c&&c.length>3&&(i+="."+cs(c[1])+cs(c[2])+cs(c[3]),r=ls(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Q(e,[s])[0],l=Q(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=ii(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=ii(l,h);const d=l[h++];if(d===64)i+="."+cs(d);else break;if(h+=12,l[h++]!==5)break;h=ii(l,h);const g=l[h++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[h]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=Q(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=q(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+sc(d).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let E=p.length;E--;){const v=p[E];(v||y)&&(y="."+v.toString(16).toUpperCase()+y)}i+=y}r=ls(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=ls(i,t)||i;break}case"vp09":{const c=Q(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+ze(l)+"."+ze(h)+"."+ze(u)}break}case"av01":{const c=Q(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&d?g?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,v=c[2]&3;i+="."+l+"."+ze(h)+u+"."+ze(f)+"."+p+"."+y+E+v+"."+ze(1)+"."+ze(1)+"."+ze(1)+"."+0,r=ls("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function ls(a,e){const t=Q(e,["dvvC"]),s=t.length?t[0]:Q(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+ze(i)+"."+ze(r)}}function sc(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function ii(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function cs(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function ze(a){return(a<10?"0":"")+a}function ic(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&ma(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(re.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Le(r)} -> ${Le(t)}`),s.set(t,8))})}function rc(a){const e=[];return ma(a,t=>e.push(t.subarray(8,24))),e}function ma(a,e){Q(a,["moov","trak"]).forEach(s=>{const i=Q(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=Q(r,["enca"]);const o=n.length>0;o||(n=Q(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);Q(l,["sinf"]).forEach(u=>{const d=pa(u);d&&e(d,o)})})})}function pa(a){const e=Q(a,["schm"])[0];if(e){const t=pe(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=Q(a,["schi","tenc"])[0];if(s)return s}}}function nc(a,e,t){const s={},i=Q(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=Q(n,["tfhd"])[0],c=q(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=Q(n,["tfdt"])[0];if(u){const T=u[0];let x=q(u,4);T===1&&(x===Fr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(x*=Fr+1,x+=q(u,8))),G(x)&&(!G(h.start)||x<h.start)&&(h.start=x)}const d=l.default,g=q(o,0)|d?.flags;let f=d?.duration||0;g&8&&(g&2?f=q(o,12):f=q(o,8));const p=Q(n,["trun"]);let y=h.start||0,E=0,v=f;for(let T=0;T<p.length;T++){const x=p[T],S=q(x,4),R=h.sampleCount;h.sampleCount+=S;const A=x[3]&1,I=x[3]&4,b=x[2]&1,L=x[2]&2,C=x[2]&4,w=x[2]&8;let U=8,F=S;for(A&&(U+=4),I&&S&&(!(x[U+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=R),U+=4,b?(v=q(x,U),U+=4):v=f,L&&(U+=4),w&&(U+=4),y+=v,E+=v,F--);F--;)b?(v=q(x,U),U+=4):v=f,L&&(U+=4),C&&(x[U+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(F+1),h.keyFrameStart=y),U+=4),w&&(U+=4),y+=v,E+=v;!E&&f&&(E+=f*S)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=Q(a,["sidx"]);for(let c=0;c<o.length;c++){const l=ec(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&G(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function ac(a){const e={valid:null,remainder:null},t=Q(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function Ke(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Nr(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return Q(s,["moof"]).map(c=>{const l=c.byteOffset-8;Q(c,["traf"]).map(u=>{const d=Q(u,["tfdt"]).map(g=>{const f=g[0];let p=q(g,4);return f===1&&(p*=Math.pow(2,32),p+=q(g,8)),p/i})[0];return d!==void 0&&(a=d),Q(u,["tfhd"]).map(g=>{const f=q(g,4),p=q(g,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,v=(p&8)!==0;let T=0;const x=(p&16)!==0;let S=0;const R=(p&32)!==0;let A=8;f===r&&(y&&(A+=8),E&&(A+=4),v&&(T=q(g,A),A+=4),x&&(S=q(g,A),A+=4),R&&(A+=4),e.type==="video"&&(n=Ys(e.codec)),Q(u,["trun"]).map(I=>{const b=I[0],L=q(I,0)&16777215,C=(L&1)!==0;let w=0;const U=(L&4)!==0,F=(L&256)!==0;let N=0;const k=(L&512)!==0;let $=0;const B=(L&1024)!==0,K=(L&2048)!==0;let W=0;const M=q(I,4);let O=8;C&&(w=q(I,O),O+=4),U&&(O+=4);let X=w+l;for(let te=0;te<M;te++){if(F?(N=q(I,O),O+=4):N=T,k?($=q(I,O),O+=4):$=S,B&&(O+=4),K&&(b===0?W=q(I,O):W=fa(I,O),O+=4),e.type===le.VIDEO){let z=0;for(;z<$;){const Z=q(s,X);if(X+=4,oc(n,s[X])){const ve=s.subarray(X,X+Z);Zi(ve,n?2:1,a+W/i,t)}X+=Z,z+=Z+4}}a+=N/i}}))})})}),t}function Ys(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function oc(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Zi(a,e,t,s){const i=ya(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){re.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=da(i,h);if(h+=2,d===49){const g=q(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const p=i[h++],y=31&p,E=64&p,v=E?2+y*3:0,T=new Uint8Array(v);if(E){T[0]=p;for(let x=1;x<v;x++)T[x]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:T})}}}}}else if(n===5&&o>16){const u=[];for(let f=0;f<16;f++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:$e(g),userDataBytes:g})}}}function ya(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function lc(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;pe(a.subarray(l,l+1))!=="\0";)t+=pe(a.subarray(l,l+1)),l+=1;for(t+=pe(a.subarray(l,l+1)),l+=1;pe(a.subarray(l,l+1))!=="\0";)s+=pe(a.subarray(l,l+1)),l+=1;s+=pe(a.subarray(l,l+1)),l+=1,i=q(a,12),r=q(a,16),o=q(a,20),c=q(a,24),l=28}else if(e===1){l+=4,i=q(a,l),l+=4;const u=q(a,l);l+=4;const d=q(a,l);for(l+=4,n=2**32*u+d,Bl(n)||(n=Number.MAX_SAFE_INTEGER,re.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=q(a,l),l+=4,c=q(a,l),l+=4;pe(a.subarray(l,l+1))!=="\0";)t+=pe(a.subarray(l,l+1)),l+=1;for(t+=pe(a.subarray(l,l+1)),l+=1;pe(a.subarray(l,l+1))!=="\0";)s+=pe(a.subarray(l,l+1)),l+=1;s+=pe(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function cc(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function hc(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),cc([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function uc(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=dc(i);e.push(r),s+=r.size}}return e}function dc(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=Le(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let g=0;g<d;g++)c.push(new Uint8Array(n,t+32+g*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const Ea=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Bt={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 Ji(a,e){const t=Bt[e];return!!t&&!!t[a.slice(0,4)]}function zt(a,e,t=!0){return!a.split(",").some(s=>!er(s,e,t))}function er(a,e,t=!0){var s;const i=Et(t);return(s=i?.isTypeSupported(Qt(a,e)))!=null?s:!1}function Qt(a,e){return`${e}/mp4;codecs=${a}`}function Br(a){if(a){const e=a.substring(0,4);return Bt.video[e]}return 2}function ks(a){const e=Ea();return a.split(",").reduce((t,s)=>{const r=e&&Ys(s)?9:Bt.video[s];return r?(r*2+t)/(t?3:2):(Bt.audio[s]+t)/(t?2:1)},0)}const ri={};function fc(a,e=!0){if(ri[a])return ri[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(er(t[i],"audio",e))return ri[a]=t[i],t[i];if(t[i]==="mp3"&&(s=Et(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const gc=/flac|opus|mp4a\.40\.34/i;function ws(a,e=!0){return a.replace(gc,t=>fc(t.toLowerCase(),e))}function mc(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)Ji(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function As(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Ur(a,"audio")||Ur(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function Ur(a,e){return Ji(a,e)&&er(a,e)}function pc(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function yc(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function $r(a){const e=Et(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Pi(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ec={supported:!0,powerEfficient:!0,smooth:!0},vc={supported:!1,smooth:!1,powerEfficient:!1},va={supported:!0,configurations:[],decodingInfoResults:[Ec]};function Ta(a,e){return{supported:!1,configurations:e,decodingInfoResults:[vc],error:a}}function Tc(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>Ys(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&G(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Sa(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(va);const r=[],n=Sc(a),o=n.length,c=xc(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Ys(u))&&Ea())return Promise.resolve(Ta(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=Ic(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Sc(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=xa(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:Qt(yc(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function xc(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=xa(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(g=>{const f={contentType:Qt(g,"audio"),bitrate:t?Ac(g,r):r};d&&(f.channels=""+d),h.push(f)})}return h},n):n},[]):[]}function Ac(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function xa(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function Ic(a){let e="";const{audio:t,video:s}=a;if(s){const i=Pi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Pi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const ki=["NONE","TYPE-0","TYPE-1",null];function Lc(a){return ki.indexOf(a)>-1}const Os=["SDR","PQ","HLG"];function Rc(a){return!!a&&Os.indexOf(a)>-1}var Is={No:"",Yes:"YES",v2:"v2"};function Gr(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?Is.v2:Is.Yes:Is.No}class Kr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Zt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Vr(this._audioGroups,e)}hasSubtitleGroup(e){return Vr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Vr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function bc(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function _c(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||Os.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&bc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Dc=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ce=(a,e)=>JSON.stringify(a,Dc(e));function Cc(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,g=1/0,f=1/0,p=1/0,y=0,E=[];const{preferHDR:v,allowedVideoRanges:T}=_c(e,i);for(let I=r.length;I--;){const b=a[r[I]];h||(h=b.channels[2]>0),d=Math.min(d,b.minHeight),g=Math.min(g,b.minFramerate),f=Math.min(f,b.minBitrate),T.filter(C=>b.videoRanges[C]>0).length>0&&(u=!0)}d=G(d)?d:0,g=G(g)?g:0;const x=Math.max(1080,d),S=Math.max(30,g);f=G(f)?f:t,t=Math.max(f,t),u||(e=void 0);const R=r.length>1;return{codecSet:r.reduce((I,b)=>{const L=a[b];if(b===I)return I;if(E=u?T.filter(C=>L.videoRanges[C]>0):[],R){if(L.minBitrate>t)return je(b,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),I;if(!L.hasDefaultAudio)return je(b,"no renditions with default or auto-select sound found"),I;if(o&&b.indexOf(o.substring(0,4))%5!==0)return je(b,`audio codec preference "${o}" not found`),I;if(n&&!l){if(!L.channels[n])return je(b,`no renditions with ${n} channel sound found (channels options: ${Object.keys(L.channels)})`),I}else if((!o||l)&&h&&L.channels[2]===0)return je(b,"no renditions with stereo sound found"),I;if(L.minHeight>x)return je(b,`min resolution of ${L.minHeight} > maximum of ${x}`),I;if(L.minFramerate>S)return je(b,`min framerate of ${L.minFramerate} > maximum of ${S}`),I;if(!E.some(C=>L.videoRanges[C]>0))return je(b,`no variants with VIDEO-RANGE of ${ce(E)} found`),I;if(c&&b.indexOf(c.substring(0,4))%5!==0)return je(b,`video codec preference "${c}" not found`),I;if(L.maxScore<y)return je(b,`max score of ${L.maxScore} < selected max of ${y}`),I}return I&&(ks(b)>=ks(I)||L.fragmentError>a[I].fragmentError)?I:(p=L.minIndex,y=L.maxScore,b)},void 0),videoRanges:E,preferHDR:v,minFramerate:g,minBitrate:f,minIndex:p}}function je(a,e){re.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Aa(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pc(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Hr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function Je(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(Lt(a,i,t))return s}return-1}function Lt(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||kc(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||wc(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function kc(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function wc(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function At(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Oc(a,e,t,s,i){const r=e[s],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=Yr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Je(a,f,i)>-1});return u>-1?u:Yr(e,s,d=>{const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return Je(a,f,i)>-1})}function Yr(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function Fs(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Fc extends Ve{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,g=n.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const v=n.mainForwardBufferInfo;if(!E&&v===null)return;const T=this.bwEstimator.getEstimateTTFB(),x=Math.abs(c.playbackRate);if(d<=Math.max(T,1e3*(u/(x*2))))return;const S=v?v.len/x:0,R=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&R>-1,I=this.getBwEstimate(),b=n.levels,L=b[f],C=Math.max(h.loaded,Math.round(u*(i.bitrate||L.averageBitrate)/8));let w=A?d-R:d;w<1&&A&&(w=Math.min(d,h.loaded*8/I));const U=A?h.loaded*1e3/w:0,F=T/1e3,N=U?(C-h.loaded)/U:C*8/I+F;if(N<=S)return;const k=U?U*8:I,$=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,B=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,W;for(W=f-1;W>g;W--){const te=b[W].maxBitrate,z=!b[W].details||$;if(K=this.getTimeToLoadFrag(F,k,u*te,z),K<Math.min(S,u+F))break}if(K>=N||K>u*10)return;A?this.bwEstimator.sample(d-Math.min(T,R),h.loaded):this.bwEstimator.sampleTTFB(d);const M=b[W].maxBitrate;this.getBwEstimate()*B>M&&this.resetEstimator(M);const O=this.findBestLevel(M,g,W,0,S,1,1);O>-1&&(W=O),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly; 2 - Fragment duration: ${i.duration.toFixed(3)} 3 - Time to underbuffer: ${S.toFixed(3)} s 4 - Estimated load time for current fragment: ${N.toFixed(3)} s 5 - Estimated load time for down switch fragment: ${K.toFixed(3)} s 6 - TTFB estimate: ${R|0} ms 7 - Current BW estimate: ${G(I)?I|0:"Unknown"} bps 8 - New BW estimate: ${this.getBwEstimate()|0} bps 9 - Switching to level ${W} @ ${M|0} bps`),n.nextLoadLevel=n.nextAutoLevel=W,this.clearTimer();const X=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===W&&W>0){const te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""} 10 - Fragment duration: ${i.duration.toFixed(3)} s 11 - Time to underbuffer: ${te.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>g){let z=this.findBestLevel(this.hls.levels[g].bitrate,g,W,0,te,1,1);z===-1&&(z=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=z,this.resetEstimator(this.hls.levels[z].bitrate)}}};y||N>K*2?X():this.timer=self.setInterval(X,K*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},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 $l(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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;G(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===V.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==V.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[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:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,n,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const g=this.findBestLevel(c,n,i,l,d,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[n],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(f.length===1)return 0;const v=f[u],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),x=y===-1||h===-1;let S,R="SDR",A=v?.frameRate||0;const{audioPreference:I,videoPreference:b}=E,L=this.audioTracksByGroup||(this.audioTracksByGroup=Aa(p));let C=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;const k=this.codecTiers||(this.codecTiers=Pc(f,L,t,s)),$=Cc(k,R,e,I,b),{codecSet:B,videoRanges:K,minFramerate:W,minBitrate:M,minIndex:O,preferHDR:X}=$;C=O,S=B,R=X?K[K.length-1]:K[0],A=W,e=Math.max(e,M),this.log(`picked start tier ${ce($)}`)}else S=v?.codecSet,R=v?.videoRange;const w=g?g.duration:d?d.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,F=[];for(let k=s;k>=t;k--){var N;const $=f[k],B=k>u;if(!$)continue;if(E.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){const z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&Tc($,L,R,A,e,I)?($.supportedPromise=Sa($,L,z,this.supportedCache),$.supportedPromise.then(Z=>{if(!this.hls)return;$.supportedResult=Z;const ve=this.hls.levels,ge=ve.indexOf($);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${ge} ${ce(Z)}`):Z.supported?Z.decodingInfoResults.some(_e=>_e.smooth===!1||_e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ge} not smooth or powerEfficient: ${ce(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ge} ${ce(Z)}`),ge>-1&&ve.length>1&&(this.log(`Removing unsupported level ${ge}`),this.hls.removeLevel(ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):$.supportedResult=va}if((S&&$.codecSet!==S||R&&$.videoRange!==R||B&&A>$.frameRate||!B&&A>0&&A<$.frameRate||(N=$.supportedResult)!=null&&(N=N.decodingInfoResults)!=null&&N.some(z=>z.smooth===!1))&&(!x||k!==C)){F.push(k);continue}const K=$.details,W=(g?K?.partTarget:K?.averagetargetduration)||w;let M;B?M=o*e:M=n*e;const O=w&&i>=w*2&&r===0?$.averageBitrate:$.maxBitrate,X=this.getTimeToLoadFrag(U,M,O*W,K===void 0);if(M>=O&&(k===h||$.loadError===0&&$.fragmentError===0)&&(X<=U||!G(X)||T&&!this.bitrateTestDelay||X<l)){const z=this.forcedAutoLevel;return k!==y&&(z===-1||z!==y)&&(F.length&&this.trace(`Skipped level(s) ${F.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[F[0]].codecs}" ${f[F[0]].videoRange}; not compatible with "${S}" ${R}`),this.info(`switch candidate:${u}->${k} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-O)} ttfb:${U.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${x} codecSet:${$.codecSet} videoRange:${$.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=k),k}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Ia={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Mc(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!G(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(Bc(e,t,n))return n}return null}function Rt(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&Wr(t,s,r)===0||Nc(r,a,Math.min(i,s))))return r;const n=Ia.search(e,Wr.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Nc(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function Wr(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function Bc(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function La(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return Ia.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function Ms(a){switch(a.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ra(a){return a.details.startsWith("key")}function ba(a){return Ra(a)&&!!a.frag&&!a.frag.decryptdata}function qr(a,e){const t=Ms(e);return a.default[`${t?"timeout":"error"}Retry`]}function tr(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function jr(a){return ie(ie({},a),{errorRetry:null,timeoutRetry:null})}function Ns(a,e,t,s){if(!a)return!1;const i=s?.code,r=e<a.maxNumRetry&&(Uc(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function Uc(a){return wi(a)||!!a&&(a<400||a>499)}function wi(a){return a===0&&navigator.onLine===!1}var Ie={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ne={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class $c extends Ve{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===V.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Ot();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ie.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var n;const c=t.parent===V.MAIN?t.level:i.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===J.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===J.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ie.SendAlternateToPenaltyBox,t.errorAction.flags=Ne.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction=Ot();return}t.type===Y.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Ot())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=qr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ns(i,r,Ms(e),e.response))return{action:Ie.RetryRequest,flags:Ne.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=qr(Ra(e)?n:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==D.FRAG_GAP&&i.fragmentError++,!ba(e)&&Ns(o,c,Ms(e),e.response)))return{action:Ie.RetryRequest,flags:Ne.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===D.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===V.AUDIO&&l===D.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:R})=>i.audioCodec!==R),T=e.sourceBufferName==="video"&&(l===D.BUFFER_ADD_CODEC_ERROR||l===D.BUFFER_APPEND_ERROR)&&u.some(({codecSet:R,audioCodec:A})=>i.codecSet!==R&&i.audioCodec===A),{type:x,groupId:S}=(n=e.context)!=null?n:{};for(let R=u.length;R--;){const A=(R+d)%u.length;if(A!==d&&A>=g&&A<=f&&u[A].loadError===0){var o,c;const I=u[A];if(l===D.FRAG_GAP&&p===V.MAIN&&e.frag){const b=u[A].details;if(b){const L=Rt(e.frag,b.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(x===J.AUDIO_TRACK&&I.hasAudioGroup(S)||x===J.SUBTITLE_TRACK&&I.hasSubtitleGroup(S))continue;if(p===V.AUDIO&&(o=i.audioGroups)!=null&&o.some(b=>I.hasAudioGroup(b))||p===V.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(b=>I.hasSubtitleGroup(b))||E&&i.audioCodec===I.audioCodec||T&&i.codecSet===I.codecSet||!E&&i.codecSet!==I.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ie.SendAlternateToPenaltyBox,flags:Ne.None,nextAutoLevel:h}}return{action:Ie.SendAlternateToPenaltyBox,flags:Ne.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ie.DoNothing:break;case Ie.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.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,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ne.None:this.switchLevel(e,r);break;case Ne.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=ki[ki.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ne.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var n,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(n=l[d].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Le(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==V.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===D.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Pi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Ot(a){const e={action:Ie.DoNothing,flags:Ne.None};return a&&(e.resolved=!0),e}var Ee={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Gc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if(o?.body.type===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=_t(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),hs(r)||this.removeParts(s.sn-1,s.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 s=this.activePartLists[t];s&&(this.activePartLists[t]=Xr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=_t(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<d&&o>u){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&hs(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||hs(t))}getState(e){const t=_t(e),s=this.fragments[t];return s?s.buffered?hs(s)?Ee.PARTIAL:Ee.OK:Ee.APPENDING:Ee.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=_t(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_t(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=_t(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Xr(s,r=>r.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}}function hs(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function _t(a){return`${a.type}_${a.level}_${a.sn}`}function Xr(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var vt={cbc:0,ctr:1};class Kc{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case vt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case vt.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 Vc(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Hc{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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[f]=E,t[E]=f;const v=g[f],T=g[v],x=g[T];let S=g[E]*257^E*16843008;i[f]=S<<24|S>>>8,r[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,o[f]=S,S=x*16843009^T*65537^v*257^f*16843008,l[E]=S<<24|S>>>8,h[E]=S<<16|S>>>16,u[E]=S<<8|S>>>24,d[E]=S,f?(f=v^g[g[g[x^v]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],E=g[3];let v,T;for(o=0;o<n;o++){if(o<r){v=l[o]=t[o];continue}T=v,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),l[o]=v=(l[o-r]^T)>>>0}for(c=0;c<n;c++)o=n-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?h[c]=T:h[c]=f[u[T>>>24]]^p[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],p=d[2],y=d[3];const E=new Int32Array(e),v=new Int32Array(E.length);let T,x,S,R,A,I,b,L,C,w,U,F,N,k;const $=this.networkToHostOrderSwap;for(;t<E.length;){for(C=$(E[t]),w=$(E[t+1]),U=$(E[t+2]),F=$(E[t+3]),A=C^r[0],I=F^r[1],b=U^r[2],L=w^r[3],N=4,k=1;k<i;k++)T=c[A>>>24]^l[I>>16&255]^h[b>>8&255]^u[L&255]^r[N],x=c[I>>>24]^l[b>>16&255]^h[L>>8&255]^u[A&255]^r[N+1],S=c[b>>>24]^l[L>>16&255]^h[A>>8&255]^u[I&255]^r[N+2],R=c[L>>>24]^l[A>>16&255]^h[I>>8&255]^u[b&255]^r[N+3],A=T,I=x,b=S,L=R,N=N+4;T=n[A>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[L&255]^r[N],x=n[I>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[A&255]^r[N+1],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[I&255]^r[N+2],R=n[L>>>24]<<24^n[A>>16&255]<<16^n[I>>8&255]<<8^n[b&255]^r[N+3],v[t]=$(T^g),v[t+1]=$(R^f),v[t+2]=$(S^p),v[t+3]=$(x^y),g=C,f=w,p=U,y=F,t=t+4}return v.buffer}}class Yc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Wc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Wc(a){switch(a){case vt.cbc:return"AES-CBC";case vt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const qc=16;class sr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Vc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==vt.cbc||t.byteLength!==16)return re.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ke(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Hc),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Yc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kc(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(re.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%qc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(re.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const zr=Math.pow(2,17);class jc{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 s=e.url;if(!s)return Promise.reject(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(Zr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Qr(e);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zr};e.stats=l.stats;const g={onSuccess:(f,p,y,E)=>{this.resetLoader(e,l);let v=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:E})},onError:(f,p,y,E)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ie({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:E}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Zr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Qr(e,t);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zr};t.stats=l.stats,l.load(h,d,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:g.data,networkDetails:y};s(E),o(E)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ie({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new ot({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(G(i)&&G(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&Xc((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Zr(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:Y.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new ot(s)}function Xc(a){return a==="AES-128"||a==="AES-256"}class ot extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class _a extends Ve{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 ir{constructor(e,t,s,i=0,r=-1,n=!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=us(),this.buffering={audio:us(),video:us(),audiovideo:us()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function us(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jr={length:0,start:()=>0,end:()=>0};class j{static isBuffered(e,t){if(e){const s=j.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=j.getBuffered(e);return j.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=j.bufferedRanges(e);if(i.length)return j.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,n=l-t;else if(t+s<u){o=u;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Jr}catch(t){return re.log("failed to get media.buffered",t),Jr}}}const Da=/\{\$([a-zA-Z0-9-_]+)\}/g;function en(a){return Da.test(a)}function Oi(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Da,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function tn(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function zc(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Qc=/^(\d+)x(\d+)$/,sn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ue{constructor(e,t){typeof e=="string"&&(e=ue.parseAttrList(e,t)),ne(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Qc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(sn.lastIndex=0;(s=sn.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Oi(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="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":re.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const Zc="com.apple.hls.interstitial";function Jc(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function eh(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Ca{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){re.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=ne(new ue({}),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"]);G(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?(re.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(G(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===Zc}get isValid(){return!!this.id&&!this._badValueForSameId&&G(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 th=10;class sh{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>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 s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||th}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Bs(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function rn(a,e){return!a&&!e?!0:!a||!e?!1:Bs(a,e)}function Ft(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function rr(a){switch(a){case"AES-128":case"AES-256":return vt.cbc;case"AES-256-CTR":return vt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function nr(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Fi(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function ih(a){const e=Fi(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Pa(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function ka(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=nr(n)):t=ih(n)}}return t}const Us=typeof self<"u"?self:void 0;var de={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Re={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ls(a){switch(a){case Re.FAIRPLAY:return de.FAIRPLAY;case Re.PLAYREADY:return de.PLAYREADY;case Re.WIDEVINE:return de.WIDEVINE;case Re.CLEARKEY:return de.CLEARKEY}}function ni(a){switch(a){case de.FAIRPLAY:return Re.FAIRPLAY;case de.PLAYREADY:return Re.PLAYREADY;case de.WIDEVINE:return Re.WIDEVINE;case de.CLEARKEY:return Re.CLEARKEY}}function Wt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[de.FAIRPLAY,de.WIDEVINE,de.PLAYREADY,de.CLEARKEY].filter(i=>!!e[i]):[];return!s[de.WIDEVINE]&&t&&s.push(de.WIDEVINE),s}const wa=(function(a){return Us!=null&&(a=Us.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function rh(a,e,t,s){let i;switch(a){case de.FAIRPLAY:i=["cenc","sinf"];break;case de.WIDEVINE:case de.PLAYREADY:i=["cenc"];break;case de.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return nh(i,e,t,s)}function nh(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ah(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Oa(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=nr(o).subarray(0,16);return Pa(c),c}}return null}let Dt={};class yt{static clearKeyUriToKeyIdMap(){Dt={}}static setKeyIdForUri(e,t){Dt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Dt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Dt[e]=s,s}constructor(e,t,s,i=[1],r=null,n){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=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ft(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(la(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Bs(e.keyFormatVersions,this.keyFormatVersions)&&rn(e.iv,this.iv)&&rn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ft(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Re.FAIRPLAY:case Re.WIDEVINE:case Re.PLAYREADY:case Re.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(Ft(this.method)){let r=this.iv;return r||(typeof e!="number"&&(re.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=lh(e)),new yt(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Dt[this.uri];if(r&&!Bs(this.keyId,r)&&yt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=ka(this.uri);if(s)switch(this.keyFormat){case Re.WIDEVINE:if(this.pssh=s,!this.keyId){const r=uc(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=nn(t));break;case Re.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hc(r,null,s),this.keyId=Oa(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=oh(t),r||(r=nn(t),r||(r=Dt[this.uri])),r&&(this.keyId=r,yt.setKeyIdForUri(this.uri,r))}return this}}function oh(a){const e=a?.[Re.WIDEVINE];return e?e.keyId:null}function nn(a){const e=a?.[Re.PLAYREADY];if(e){const t=ka(e.uri);if(t)return Oa(t)}return null}function lh(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const an=/#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,on=/#EXT-X-MEDIA:(.*)/g,ch=/^#EXT(?:INF|-X-TARGETDURATION):/m,ai=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hh=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 et{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return zi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return ch.test(e)}static parseMasterPlaylist(e,t){const s=en(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(an.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=an.exec(e))!=null;)if(n[1]){var o;const l=new ue(n[1],i),h=Oi(i,n[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:et.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),hn(l.CODECS,u);const g=l["SUPPLEMENTAL-CODECS"];g&&(u.supplemental={},hn(g,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const u=new ue(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=ln(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):re.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new ue(h,i);tn(i,u,t)}break}case"CONTENT-STEERING":{const u=new ue(h,i);i.contentSteering={uri:et.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=cn(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(on.lastIndex=0;(i=on.exec(e))!==null;){const l=new ue(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],v={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?et.resolve(l.URI,t):""};if(f&&(v.assocLang=f),p&&(v.channels=p),y&&(v.characteristics=y),E&&(v.instreamId=E),u!=null&&u.length){const T=et.findGroup(u,v.groupId)||u[0];un(v,T,"audioCodec"),un(v,T,"textCodec")}d.push(v)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new sh(t),h=l.fragments,u=[];let d=null,g=0,f=0,p=0,y=0,E=0,v=null,T=new si(i,c),x,S,R,A=-1,I=!1,b=null,L;if(ai.lastIndex=0,l.m3u8=e,l.hasVariableRefs=en(e),((o=ai.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(x=ai.exec(e))!==null;){I&&(I=!1,T=new si(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),b&&(T.setByteRange(b),b=null)));const F=x[1];if(F){T.duration=parseFloat(F);const N=(" "+x[2]).slice(1);T.title=N||null,T.tagList.push(N?["INF",F,N]:["INF",F])}else if(x[3]){if(G(T.duration)){T.playlistOffset=p,T.setStart(p),R&&fn(T,R,l),T.sn=g,T.level=s,T.cc=y,h.push(T);const N=(" "+x[3]).slice(1);T.relurl=Oi(l,N),Mi(T,v,u),v=T,p+=T.duration,g++,f=0,I=!0}}else{if(x=x[0].match(hh),!x){re.warn("No matches on slow regex match for level playlist!");continue}for(S=1;S<x.length&&x[S]===void 0;S++);const N=(" "+x[S]).slice(1),k=(" "+x[S+1]).slice(1),$=x[S+2]?(" "+x[S+2]).slice(1):null;switch(N){case"BYTERANGE":v?T.setByteRange(k,v):T.setByteRange(k);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=k,T.tagList.push(["PROGRAM-DATE-TIME",k]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&rt(l,N,x),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?rt(l,N,x):h.length>0&&gn(l,N,x),g=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&rt(l,N,x);const B=new ue(k,l),K=B.decimalInteger("SKIPPED-SEGMENTS");if(G(K)){l.skippedSegments+=K;for(let M=K;M--;)h.push(null);g+=K}const W=B.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&rt(l,N,x),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&rt(l,N,x),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||rt(l,N,x),l.live=!1;break;case"#":(k||$)&&T.tagList.push($?[k,$]:[k]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([N]);break;case"BITRATE":T.tagList.push([N,k]),E=parseInt(k)*1e3,G(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const B=new ue(k,l),K=new Ca(B,l.dateRanges[B.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:re.warn(`Ignoring invalid DATERANGE tag: "${k}"`),T.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const B=new ue(k,l);"IMPORT"in B?zc(l,B,n):tn(l,B,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?rt(l,N,x):h.length>0&&gn(l,N,x),l.startCC=y=parseInt(k);break;case"KEY":{const B=ln(k,t,l);if(B.isSupported()){if(B.method==="NONE"){R=void 0;break}R||(R={});const K=R[B.keyFormat];K!=null&&K.matches(B)||(K&&(R=ne({},R)),R[B.keyFormat]=B)}else re.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=cn(k);break;case"MAP":{const B=new ue(k,l);if(T.duration){const K=new si(i,c);dn(K,B,s,R),d=K,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const K=T.byteRangeEndOffset;if(K){const W=T.byteRangeStartOffset;b=`${K-W}@${W}`}else b=null;dn(T,B,s,R),d=T,I=!0}d.cc=y;break}case"SERVER-CONTROL":{L&&rt(l,N,x),L=new ue(k),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&rt(l,N,x);const B=new ue(k);l.partTarget=B.decimalFloatingPoint("PART-TARGET");break}case"PART":{let B=l.partList;B||(B=l.partList=[]);const K=f>0?B[B.length-1]:void 0,W=f++,M=new ue(k,l),O=new zl(M,T,c,W,K);B.push(O),T.duration+=O.duration;break}case"PRELOAD-HINT":{const B=new ue(k,l);l.preloadHint=B;break}case"RENDITION-REPORT":{const B=new ue(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(B);break}default:re.warn(`line parsed but not handled: ${x}`);break}}}v&&!v.relurl?(h.pop(),p-=v.duration,l.partList&&(l.fragmentHint=v)):l.partList&&(Mi(T,v,u),T.cc=y,l.fragmentHint=T,R&&fn(T,R,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,w=h[0],U=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&U){l.averagetargetduration=p/C;const F=U.sn;l.endSN=F!=="initSegment"?F:0,l.live||(U.endList=!0),A>0&&(dh(h,A),w&&u.unshift(w))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&w&&Fa(u,l),l.endCC=y,l}}function Fa(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var n;if(((n=a[h])==null?void 0:n.sn)<e.startSN)break;const u=uh(e,l,a,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function uh(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const h=a.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let g=d;g>l;g--){const f=h[g].programDateTime;if(e>=f&&e<f+h[g].duration*1e3)return g}}return l}}}return-1}function ln(a,e,t){var s,i;const r=new ue(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&re.error(`Invalid IV: ${r.IV}`);const u=o?et.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new yt(n,u,h,d,c,r.KEYID)}function cn(a){const t=new ue(a).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function hn(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>Ji(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function un(a,e,t){const s=e[t];s&&(a[t]=s)}function dh(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Mi(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function dn(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function fn(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function rt(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function gn(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function oi(a,e){const t=e.startPTS;if(G(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function Ma(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(G(h)){const E=Math.abs(h-t);a&&E>a.totalduration?n.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${a.url}`):G(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const g=e.sn;if(!a||g<a.startSN||g>a.endSN)return 0;let f;const p=g-a.startSN,y=a.fragments;for(y[p]=e,f=p;f>0;f--)oi(y[f],y[f-1]);for(f=p;f<y.length-1;f++)oi(y[f],y[f+1]);return a.fragmentHint&&oi(y[y.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,d}function fh(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;ph(a,e,(h,u,d,g)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const f=h.cc-u.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}G(h.startPTS)&&G(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=gh(a.dateRanges,e,t));const h=a.fragments.filter(u=>u.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Mi(o[u],o[u-1],h);Fa(h,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const h=Ua(a,e.startSN-1);e.startCC=(c=h?.cc)!=null?c:n[0].cc}mh(a.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?Ma(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Na(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function gh(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ne({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new Ca(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[c].attr)}"`)}),r):s}function mh(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function ph(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=c[n+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,g=u.relurl;if(d&&yh(d,g)){e.playlistParsingError=mn(`media sequence mismatch ${u.sn}:`,a,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=mn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,a,e,h,u);return}}}}function mn(a,e,t,s,i){return new Error(`${a} ${i.url} 12 - Playlist starting @${e.startSN} 13 - ${e.m3u8} 14 - 15 - Playlist starting @${t.startSN} 16 - ${t.m3u8}`)}function Na(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;Ni(e,n)}function Ni(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Ba(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ua(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function pn(a,e,t){return a?$a(a.partList,e,t):null}function $a(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ga(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function yh(a,e){return a!==e&&e?yn(a)!==yn(e):!1}function yn(a){return a.replace(/\?[^?]*$/,"")}function qt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Eh(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function En(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Ka(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)En(t[s],a);e.fragmentHint&&En(e.fragmentHint,a),e.alignedSliding=!0}function vh(a,e){a&&(Va(e,a),e.alignedSliding||$s(e,a),!e.alignedSliding&&!e.skippedSegments&&Na(a,e,!1))}function Va(a,e){if(!Eh(e,a))return;const t=Math.min(e.endCC,a.endCC),s=qt(e.fragments,t),i=qt(a.fragments,t);if(!s||!i)return;re.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Ka(r,a)}function $s(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=qt(s,n),r=qt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=qt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Ka(l,a)}function Ce(a,e,t){Oe(a,e,t),a.addEventListener(e,t)}function Oe(a,e,t){a.removeEventListener(e,t)}const Th={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ar extends _a{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=j.bufferInfo(l||c,u,n.maxBufferHole),g=!d.len;if(this.log(`Media seeking to ${G(u)?u.toFixed(3):u}, state: ${h}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const f=n.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(u>f&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),g&&this.state===P.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 jc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new sr(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===P.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=P.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 s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=j.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return j.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ce(s,"seeking",this.onMediaSeeking),Ce(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Oe(i,"seeking",this.onMediaSeeking),Oe(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===P.FRAG_LOADING||!this.fragCurrent&&n===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ee.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ee.PARTIAL&&s.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,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Ft(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,rr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,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 s=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:${s?Th.toString(j.getBuffered(s)):"(detached)"})`),me(e)){var i;if(e.type!==V.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new ir(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),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||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(me(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&me(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const g=this.getNextPart(d,e,s);if(g>-1){const f=d[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${d.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(me(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.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} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==V.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const g=d.part;this.hls.trigger(m.FRAG_LOADED,d);const f=pn(s.details,e.sn,u.index+1)||$a(l,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Y.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:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===V.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?pn(c,r,n):null,h=l?l.fragment:Ua(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=Ke(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!j.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=j.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!G(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=j.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return j.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=V.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(d!==-1&&d>=n?d:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ee.OK||s===Ee.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(vn(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(vn(this.config)&&e.type!==V.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Mc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=La(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;d=Rt(r,n,e,p)}else d=n[n.length-1];if(d){const f=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Ee.OK||p===Ee.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[f+1];d.sn<o&&this.fragmentTracker.getState(E)!==Ee.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&G(r);if(n||!o&&!r){vh(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),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 s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&G(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&me(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!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===D.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,g=d&&c===Ie.RetryRequest,f=d&&!o.resolved&&l===Ne.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&me(i)&&!i.endList&&p&&!ba(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&h<u.maxNumRetry){var y;const E=wi((y=t.response)==null?void 0:y.code),v=tr(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${v}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==Ie.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Ie.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!wi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===V.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=j.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.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?"<removed>":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,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:Ma(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.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===V.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 vn(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Ha{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Sh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Sh(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var li={exports:{}},Tn;function xh(){return Tn||(Tn=1,(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,u||c,d),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,g=u.length,f=new Array(g);d<g;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,v,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,g),!0;case 6:return y.fn.call(y.context,h,u,d,g,f),!0}for(T=1,v=new Array(E-1);T<E;T++)v[T-1]=arguments[T];y.fn.apply(y.context,v)}else{var x=y.length,S;for(T=0;T<x;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!v)for(S=1,v=new Array(E-1);S<E;S++)v[S-1]=arguments[S];y[T].fn.apply(y[T].context,v)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var g=t?t+l:l;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&n(this,g);else{for(var p=0,y=[],E=f.length;p<E;p++)(f[p].fn!==h||d&&!f[p].once||u&&f[p].context!==u)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(li)),li.exports}var Ah=xh(),or=jl(Ah);const Jt="1.6.15",Ut={};function Ih(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Lh(){const a=Ut[Jt];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Ut[Jt]=i,i}function Rh(a){const e=Ut[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Ut[a]=i,i}function bh(a){const e=Ut[a||Jt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Ut[a||Jt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Ya(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function lr(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Ws(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function es(a,e){const t=e;let s=0;for(;lr(a,e);){s+=10;const i=Ws(a,e+6);s+=i,Ya(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function _h(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const g=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return re.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Wa(a,e){return a[e]===255&&(a[e+1]&246)===240}function qa(a,e){return a[e+1]&1?7:9}function cr(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Dh(a,e){return e+5<a.length}function Gs(a,e){return e+1<a.length&&Wa(a,e)}function Ch(a,e){return Dh(a,e)&&Wa(a,e)&&cr(a,e)<=a.length-e}function Ph(a,e){if(Gs(a,e)){const t=qa(a,e);if(e+t>=a.length)return!1;const s=cr(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||Gs(a,i)}return!1}function ja(a,e,t,s,i){if(!a.samplerate){const r=_h(e,t,s,i);if(!r)return;ne(a,r)}}function Xa(a){return 1024*9e4/a}function kh(a,e){const t=qa(a,e);if(e+t<=a.length){const s=cr(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function za(a,e,t,s,i){const r=Xa(a.samplerate),n=s+i*r,o=kh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,g=d+u,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+g);const p={unit:c,pts:n};return f||a.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function wh(a,e){return lr(a,e)&&Ws(a,e+6)+10<=a.length-e}function Oh(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function ci(a,e=0,t=1/0){return Fh(a,e,t,Uint8Array)}function Fh(a,e,t,s){const i=Mh(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=Nh(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Mh(a){return a instanceof ArrayBuffer?a:a.buffer}function Nh(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Bh(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=$e(ci(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=$e(ci(a.data,3+s,n));let c;return i==="-->"?c=$e(ci(a.data,4+s+n)):c=Oh(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Uh(a){if(a.size<2)return;const e=$e(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function $h(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=$e(a.data.subarray(t),!0);t+=s.length+1;const i=$e(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=$e(a.data.subarray(1));return{key:a.type,info:"",data:e}}function Gh(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=$e(a.data.subarray(t),!0);t+=s.length+1;const i=$e(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=$e(a.data);return{key:a.type,info:"",data:e}}function Kh(a){return a.type==="PRIV"?Uh(a):a.type[0]==="W"?Gh(a):a.type==="APIC"?Bh(a):$h(a)}function Vh(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ws(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const ds=10,Hh=10;function Qa(a){let e=0;const t=[];for(;lr(a,e);){const s=Ws(a,e+6);a[e+5]>>6&1&&(e+=ds),e+=ds;const i=e+s;for(;e+Hh<i;){const r=Vh(a.subarray(e)),n=Kh(r);n&&t.push(n),e+=r.size+ds}Ya(a,e)&&(e+=ds)}return t}function Za(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Yh(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function hr(a){const e=Qa(a);for(let t=0;t<e.length;t++){const s=e[t];if(Za(s))return Yh(s)}}let Ue=(function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a})({});function Qe(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ur{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Ke(this.cachedData,e),this.cachedData=null);let s=es(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?hr(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&G(c))&&(this.basePTS=Wh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ue.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else wh(e,i)?(s=es(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ue.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=Ke(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Qe(),id3Track:o,textTrack:Qe()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Qe(),id3Track:this._id3Track,textTrack:Qe()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Wh=(a,e,t)=>{if(G(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let fs=null;const qh=[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],jh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zh=[0,1,1,4];function Ja(a,e,t,s,i){if(t+24>e.length)return;const r=eo(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function eo(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=qh[c*14+i-1]*1e3,u=jh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,g=Xh[t][s],f=zh[s],p=g*8*f,y=Math.floor(g*l/u+n)*f;if(fs===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fs=T?parseInt(T[1]):0}return fs&&fs<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function dr(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function to(a,e){return e+1<a.length&&dr(a,e)}function Qh(a,e){return dr(a,e)&&4<=a.length-e}function so(a,e){if(e+1<a.length&&dr(a,e)){const s=eo(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||to(a,r)}return!1}class Zh extends ur{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=es(e,0);let i=s?.length||0;if(so(e,i))return!1;for(let r=e.length;i<r;i++)if(Ph(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ch(e,t)}appendFrame(e,t,s){ja(e,this.observer,t,s,e.manifestCodec);const i=za(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const io=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Jh extends ur{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=ro(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=es(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&hr(t)!==void 0&&io(e,s)<16}}function ro(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+g,y=e[t+5]>>3,E=e[t+5]&7,v=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,x=s+i*T,S=e.subarray(t,t+h);return a.config=v,a.channelCount=p,a.samplerate=o,a.samples.push({unit:S,pts:x}),h}class eu extends ur{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=es(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&hr(t)!==void 0&&io(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(so(e,s))return re.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Qh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Ja(e,t,s,this.basePTS,this.frameIndex)}}const tu=/\/emsg[-/]ID3/i;class su{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Qe("video",1),n=this.audioTrack=Qe("audio",1),o=this.txtTrack=Qe("text",1);if(this.id3Track=Qe("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ga(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=ua.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Jl(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ke(this.remainderData,e));const o=ac(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Nr(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Nr(e,t),{videoTrack:t,audioTrack:Qe(),id3Track:i,textTrack:Qe()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Q(e.samples,["emsg"]);i&&i.forEach(r=>{const n=lc(r);if(tu.test(n.schemeIdUri)){const o=Sn(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ue.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Sn(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Ue.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Sn(a,e){return G(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class iu{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new sr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,vt.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=ya(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class no{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,g=0;for(r===-1&&(d=0,g=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const f={data:t.subarray(d,h),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&c<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=Ke(f.data,t.subarray(0,h)),f.state=0))}c<i?(u=this.getNALuType(t,c),d=c,g=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const f={data:t.subarray(d,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Ke(f.data,t))}return e.naluState=r,o}}class jt{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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.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 s=this.word>>>32-t;if(e>32&&re.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>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 ru extends no{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=p;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,Zi(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let v="avc1.";for(let T=0;T<3;T++){let x=E[T].toString(16);x.length<2&&(x="0"+x),v+=x}e.codec=v}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new jt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new jt(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const v=h();if(u(5),f(3),h(),y(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const I=d();if(I===3&&f(1),y(),y(),f(1),g())for(c=I!==3?8:12,l=0;l<c;l++)g()&&(l<6?E(16,t):E(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(f(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),f(1);const x=d(),S=d(),R=u(1);R===0&&f(1),f(1),g()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(g()&&g())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((x+1)*16-s*2-i*2),height:(2-R)*(S+1)*16-(R?2:4)*(r+n),pixelRatio:A}}}class nu extends no{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,Zi(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ne(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new jt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new jt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),v=[],T=[];for(let ee=0;ee<s;ee++)v.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)v[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[ee]&&t.readUByte();t.readUEG();const x=t.readUEG();x==3&&t.skipBits(1);const S=t.readUEG(),R=t.readUEG(),A=t.readBoolean();let I=0,b=0,L=0,C=0;A&&(I+=t.readUEG(),b+=t.readUEG(),L+=t.readUEG(),C+=t.readUEG());const w=t.readUEG(),U=t.readUEG(),F=t.readUEG(),N=t.readBoolean();for(let ee=N?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Te=0;Te<4;Te++)for(let Pe=0;Pe<(Te===3?2:6);Pe++)if(!t.readBoolean())t.readUEG();else{const ae=Math.min(64,1<<4+(Te<<1));Te>1&&t.readEG();for(let Ae=0;Ae<ae;Ae++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const B=t.readUEG();let K=0;for(let ee=0;ee<B;ee++){let Te=!1;if(ee!==0&&(Te=t.readBoolean()),Te){ee===B&&t.readUEG(),t.readBoolean(),t.readUEG();let Pe=0;for(let it=0;it<=K;it++){const ae=t.readBoolean();let Ae=!1;ae||(Ae=t.readBoolean()),(ae||Ae)&&Pe++}K=Pe}else{const Pe=t.readUEG(),it=t.readUEG();K=Pe+it;for(let ae=0;ae<Pe;ae++)t.readUEG(),t.readBoolean();for(let ae=0;ae<it;ae++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ee=t.readUEG();for(let Te=0;Te<ee;Te++){for(let Pe=0;Pe<F+4;Pe++)t.readBits(1);t.readBits(1)}}let M=0,O=1,X=1,te=!0,z=1,Z=0;t.readBoolean(),t.readBoolean();let ve=!1;if(t.readBoolean()){if(t.readBoolean()){const Ge=t.readUByte(),Tr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],rs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Ge>0&&Ge<16?(O=Tr[Ge-1],X=rs[Ge-1]):Ge===255&&(O=t.readBits(16),X=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(),ve=t.readBoolean(),ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(z=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const rs=t.readBoolean(),Sr=t.readBoolean();let Gt=!1;(rs||Sr)&&(Gt=t.readBoolean(),Gt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Gt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let xr=0;xr<=s;xr++){te=t.readBoolean();const Uo=te||t.readBoolean();let Ar=!1;Uo?t.readEG():Ar=t.readBoolean();const Ir=Ar?1:t.readUEG()+1;if(rs)for(let Kt=0;Kt<Ir;Kt++)t.readUEG(),t.readUEG(),Gt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Sr)for(let Kt=0;Kt<Ir;Kt++)t.readUEG(),t.readUEG(),Gt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let _e=S,He=R;if(A){let ee=1,Te=1;x===1?ee=Te=2:x==2&&(ee=2),_e=S-ee*b-ee*I,He=R-Te*C-Te*L}const De=i?["A","B","C"][i]:"",is=o<<24|c<<16|l<<8|h;let $t=0;for(let ee=0;ee<32;ee++)$t=($t|(is>>ee&1)<<31-ee)>>>0;let Tt=$t.toString(16);return n===1&&Tt==="2"&&(Tt="6"),{codecString:`hvc1.${De}${n}.${Tt}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,g,f,p,y],general_level_idc:E,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:M,chroma_format_idc:x,frame_rate:{fixed:te,fps:Z/z}},width:_e,height:He,pixelRatio:[O,X]}}readPPS(e){const t=new jt(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 i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Se=188;class mt{constructor(e,t,s,i){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=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=mt.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Se*5,t-Se)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=Se)if(e[c]===71&&(t-c===Se||e[c+Se]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+Se*99,e.length-Se)+1)),r||(r=Bi(e,c)===0),r&&o>1&&(n===0&&o>2||c+Se>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ua[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=mt.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=mt.createTrack("audio",i),this._id3Track=mt.createTrack("id3"),this._txtTrack=mt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,v=this._pmtId,T=e.length;if(this.remainderData&&(e=Ke(this.remainderData,e),T=e.length,this.remainderData=null),T<Se&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const x=Math.max(0,mt.syncOffset(e));T-=(T-x)%Se,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let S=0;for(let A=x;A<T;A+=Se)if(e[A]===71){const I=!!(e[A+1]&64),b=Bi(e,A),L=(e[A+3]&48)>>4;let C;if(L>1){if(C=A+5+e[A+4],C===A+Se)continue}else C=A+4;switch(b){case h:I&&(u&&(r=Ct(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+Se)),u.size+=A+Se-C);break;case d:if(I){if(f&&(r=Ct(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(C,A+Se)),f.size+=A+Se-C);break;case g:I&&(p&&(r=Ct(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+Se)),p.size+=A+Se-C);break;case 0:I&&(C+=e[C]+1),v=this._pmtId=au(e,C);break;case v:{I&&(C+=e[C]+1);const w=ou(e,C,this.typeSupported,s,this.observer,this.logger);h=w.videoPid,h>0&&(n.pid=h,n.segmentCodec=w.segmentVideoCodec),d=w.audioPid,d>0&&(o.pid=d,o.segmentCodec=w.segmentAudioCodec),g=w.id3Pid,g>0&&(c.pid=g),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${x} to parse all TS packets.`),y=null,A=x-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=b;break}}else S++;S>0&&Ui(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=f,c.pesData=p;const R={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(R),R}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:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=Ct(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=Ct(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Ct(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new iu(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ru:e==="hevc"&&(this.videoParser=new nu))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(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 s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=Ke(i.sample.unit,r);else{const g=d-u;i.sample.unit.set(r.subarray(0,u),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!Gs(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",Ui(this.observer,new Error(u),d,this.logger),!d)return}ja(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Xa(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=za(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!Gs(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(to(s,n)){const c=Ja(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=ro(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ne({},t,{type:this._videoTrack?Ue.emsg:Ue.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Bi(a,e){return((a[e+1]&31)<<8)+a[e+2]}function au(a,e){return(a[e+10]&31)<<8|a[e+11]}function ou(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=Bi(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){hi("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){hi("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){hi("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,g=u;for(;g>2;){a[d]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3"));const p=a[d+1]+2;d+=p,g-=p}}break;case 194:case 135:return Ui(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function Ui(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function hi(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Ct(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Ke(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class lu{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 dt=Math.pow(2,32)-1;class _{static init(){_.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 _.types)_.types.hasOwnProperty(e)&&(_.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]),s=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]);_.HDLR_TYPES={video:t,audio:s};const i=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]);_.STTS=_.STSC=_.STCO=r,_.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),_.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),_.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);_.FTYP=_.box(_.types.ftyp,n,c,n,o),_.DINF=_.box(_.types.dinf,_.box(_.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return _.box(_.types.hdlr,_.HDLR_TYPES[e])}static mdat(e){return _.box(_.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(dt+1)),i=Math.floor(t%(dt+1));return _.box(_.types.mdhd,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return _.box(_.types.mdia,_.mdhd(e.timescale||0,e.duration||0),_.hdlr(e.type),_.minf(e))}static mfhd(e){return _.box(_.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"?_.box(_.types.minf,_.box(_.types.smhd,_.SMHD),_.DINF,_.stbl(e)):_.box(_.types.minf,_.box(_.types.vmhd,_.VMHD),_.DINF,_.stbl(e))}static moof(e,t,s){return _.box(_.types.moof,_.mfhd(e),_.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=_.trak(e[t]);return _.box.apply(null,[_.types.moov,_.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(_.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=_.trex(e[t]);return _.box.apply(null,[_.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(dt+1)),i=Math.floor(t%(dt+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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 _.box(_.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return _.box(_.types.sdtp,s)}static stbl(e){return _.box(_.types.stbl,_.stsd(e),_.box(_.types.stts,_.STTS),_.box(_.types.stsc,_.STSC),_.box(_.types.stsz,_.STSZ),_.box(_.types.stco,_.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=_.box(_.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return _.box(_.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,l>>8&255,l&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]),o,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&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 _.box(_.types.mp4a,_.audioStsd(e),_.box(_.types.esds,_.esds(e)))}static mp3(e){return _.box(_.types[".mp3"],_.audioStsd(e))}static ac3(e){return _.box(_.types["ac-3"],_.audioStsd(e),_.box(_.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return _.box(_.types.stsd,_.STSD,_.mp4a(e));if(t==="ac3"&&e.config)return _.box(_.types.stsd,_.STSD,_.ac3(e));if(t==="mp3"&&e.codec==="mp3")return _.box(_.types.stsd,_.STSD,_.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return _.box(_.types.stsd,_.STSD,_.avc1(e));if(t==="hevc"&&e.vps)return _.box(_.types.stsd,_.STSD,_.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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(dt+1)),o=Math.floor(s%(dt+1));return _.box(_.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,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=_.sdtp(e),i=e.id,r=Math.floor(t/(dt+1)),n=Math.floor(t%(dt+1));return _.box(_.types.traf,_.box(_.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),_.box(_.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),_.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,_.box(_.types.trak,_.tkhd(e),_.mdia(e))}static trex(e){const t=e.id;return _.box(_.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 s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return _.box(_.types.trun,n)}static initSegment(e){_.types||_.init();const t=_.moov(e);return Ke(_.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let p=0;p<s[f].length;p+=1)n+=2+s[f][p].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),n),n+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),n),n+=2,o.set(s[f][p],n),n+=s[f][p].length}const l=_.box(_.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return _.box(_.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,h>>8&255,h&255,u>>8&255,u&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]),l,_.box(_.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),_.box(_.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}_.types=void 0;_.HDLR_TYPES=void 0;_.STTS=void 0;_.STSC=void 0;_.STCO=void 0;_.STSZ=void 0;_.VMHD=void 0;_.SMHD=void 0;_.STSD=void 0;_.FTYP=void 0;_.DINF=void 0;const ao=9e4;function fr(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function cu(a,e,t=1,s=!1){return fr(a,e,1/t,s)}function Ht(a,e=!1){return fr(a,1e3,1/ao,e)}function hu(a,e=1){return fr(a,ao,1/e)}function xn(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const uu=10*1e3,du=1024,fu=1152,gu=1536;let Pt=null,ui=null;function An(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class Rs extends Ve{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Pt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Pt=n?parseInt(n[1]):0}if(ui===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ui=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&&xn(t)} > ${e&&xn(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 s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=Be(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,g,f,p=r,y=r;const E=e.pid>-1,v=t.pid>-1,T=t.samples.length,x=e.samples.length>0,S=o&&T>0||T>1;if((!E||x)&&(!v||S)||this.ISGenerated||o){if(this.ISGenerated){var A,I,b,L;const F=this.videoTrackConfig;(F&&(t.width!==F.width||t.height!==F.height||((A=t.pixelRatio)==null?void 0:A[0])!==((I=F.pixelRatio)==null?void 0:I[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((L=F.pixelRatio)==null?void 0:L[1]))||!F&&S||this.nextAudioTs===null&&x)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const C=this.isVideoContiguous;let w=-1,U;if(S&&(w=mu(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn(`Dropped ${w} out of ${T} video samples due to a missing keyframe`);const F=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,y+=(t.samples[0].pts-F)/t.inputTimeScale,U=y}else w===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(x&&S){const F=this.getVideoStartPts(t.samples),k=(Be(e.samples[0].pts,F)-F)/t.inputTimeScale;p+=Math.max(0,k),y+=Math.max(0,-k)}if(x){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,v||S||c===V.AUDIO?y:void 0),S){const F=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,y,C,F)}}else S&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=w,l.independent=w!==-1,l.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=oo(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=lo(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Be(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,g,f,p=-1;if(h&&(d=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):_.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?d=g=this.computeInitPts(r[0].pts,f,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:_.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(n),E=Be(n[0].dts,y),v=this.computeInitPts(E,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,v),d=Math.min(d,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:c,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,v=!1;if(!s||u===null){const M=h+t*r,O=n[0].pts-Be(n[0].dts,n[0].pts);Pt&&u!==null&&Math.abs(M-O-(u+h))<15e3?s=!0:u=M-O-h}const T=u+h;for(let M=0;M<c;M++){const O=n[M];O.pts=Be(O.pts,T),O.dts=Be(O.dts,T),O.dts<n[M>0?M-1:M].dts&&(v=!0)}v&&n.sort(function(M,O){const X=M.dts-O.dts,te=M.pts-O.pts;return X||te}),f=n[0].dts,p=n[n.length-1].dts;const x=p-f,S=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){const M=f-T,O=M>S,X=M<-1;if((O||X)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ht(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!X||T>=n[0].pts||Pt)){f=T;const te=n[0].pts-M;if(O)n[0].dts=f,n[0].pts=te;else{let z=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>te&&z);Z++){const ve=n[Z].pts;if(n[Z].dts-=M,n[Z].pts-=M,Z<n.length-1){const ge=n[Z+1].pts,_e=n[Z].pts,He=ge<=_e,De=ge<=ve;z=He==De}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ht(te,!0)}/${Ht(f,!0)}, delta: ${Ht(M,!0)} ms`)}}f=Math.max(0,f);let R=0,A=0,I=f;for(let M=0;M<c;M++){const O=n[M],X=O.units,te=X.length;let z=0;for(let Z=0;Z<te;Z++)z+=X[Z].data.length;A+=z,R+=te,O.length=z,O.dts<I?(O.dts=I,I+=S/4|0||1):I=O.dts,y=Math.min(O.pts,y),E=Math.max(O.pts,E)}p=n[c-1].dts;const b=A+4*R+8;let L;try{L=new Uint8Array(b)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:b,reason:`fail allocating video mdat ${b}`});return}const C=new DataView(L.buffer);C.setUint32(0,b),L.set(_.types.mdat,4);let w=!1,U=Number.POSITIVE_INFINITY,F=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const O=n[M],X=O.units;let te=0;for(let ve=0,ge=X.length;ve<ge;ve++){const _e=X[ve],He=_e.data,De=_e.data.byteLength;C.setUint32(d,De),d+=4,L.set(He,d),d+=De,te+=4+De}let z;if(M<c-1)g=n[M+1].dts-O.dts,z=n[M+1].pts-O.pts;else{const ve=this.config,ge=M>0?O.dts-n[M-1].dts:S;if(z=M>0?O.pts-n[M-1].pts:S,ve.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(ve.maxBufferHole*r),He=(i?y+i*r:this.nextAudioTs+h)-O.pts;He>_e?(g=He-ge,g<0?g=ge:w=!0,this.log(`It is approximately ${He/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ge}else g=ge}const Z=Math.round(O.pts-O.dts);U=Math.min(U,g),N=Math.max(N,g),F=Math.min(F,z),k=Math.max(k,z),o.push(An(O.key,g,te,Z))}if(o.length){if(Pt){if(Pt<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(ui&&k-F<N-U&&S/N<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let O=0,X=o.length;O<X;O++){const te=M+o[O].duration,z=M+o[O].cts;if(O<X-1){const Z=te+o[O+1].cts;o[O].duration=Z-z}else o[O].duration=O?o[O-1].duration:S;o[O].cts=0,M=te}}}g=w||!g?S:g;const $=p+g;this.nextVideoTs=u=$-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const W={data1:_.moof(e.sequenceNumber++,f,ne(e,{samples:o})),data2:L,startPTS:(y-h)/r,endPTS:(E+g-h)/r,startDTS:(f-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return fu;case"ac3":return gu;default:return du}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const v=u.baseTime*n/u.timescale,T=v+t*n;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(T-(E+v))<9e3||Math.abs(Be(p[0].pts,T)-(E+v))<20*h),p.forEach(function(k){k.pts=Be(k.pts,T)}),!s||E<0){const k=p.length;if(p=p.filter($=>$.pts>=0),k!==p.length&&this.warn(`Removed ${p.length-k} of ${k} samples (initPTS ${v} / ${n})`),!p.length)return;r===0?E=0:i&&!f?E=Math.max(0,T-v):E=p[0].pts-v}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let $=0,B=E+v;$<p.length;$++){const K=p[$],W=K.pts,M=W-B,O=Math.abs(1e3*M/n);if(M<=-k*h&&f)$===0&&(this.warn(`Audio frame @ ${(W/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*M/n)} ms.`),this.nextAudioTs=E=W-v,B=W);else if(M>=k*h&&O<uu&&f){let X=Math.round(M/h);for(B=W-X*h;B<0&&X&&h;)X--,B+=h;$===0&&(this.nextAudioTs=E=B-v),this.warn(`Injecting ${X} audio frames @ ${((B-v)/n).toFixed(3)}s due to ${Math.round(1e3*M/n)} ms gap.`);for(let te=0;te<X;te++){let z=lu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),z=K.unit.subarray()),p.splice($,0,{unit:z,pts:B}),B+=h,$++}}K.pts=B,B+=h}}let x=null,S=null,R,A=0,I=p.length;for(;I--;)A+=p[I].unit.byteLength;for(let k=0,$=p.length;k<$;k++){const B=p[k],K=B.unit;let W=B.pts;if(S!==null){const O=g[k-1];O.duration=Math.round((W-S)/c)}else if(s&&e.segmentCodec==="aac"&&(W=E+v),x=W,A>0){A+=y;try{R=new Uint8Array(A)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(R.buffer).setUint32(0,A),R.set(_.types.mdat,4))}else return;R.set(K,y);const M=K.byteLength;y+=M,g.push(An(!0,l,M,0)),S=W}const b=g.length;if(!b)return;const L=g[g.length-1];E=S-v,this.nextAudioTs=E+c*L.duration;const C=d?new Uint8Array(0):_.moof(e.sequenceNumber++,x/c,ne({},e,{samples:g}));e.samples=[];const w=(x-v)/n,U=this.nextAudioTs/n,N={data1:C,data2:R,startPTS:w,endPTS:U,startDTS:w,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,N}}function Be(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function mu(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function oo(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=Be(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Be(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function lo(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Be(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class pu extends Ve{constructor(e,t,s,i){super("passthrough-remuxer",i),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,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=ga(e);if(t)ic(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=In(r,le.AUDIO,this)),n&&(i=In(n,le.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};G(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=nc(d,f,this),y=f.audio?p[f.audio.id]:null,E=f.video?p[f.video.id]:null,v=gs(E,1/0),T=gs(y,1/0),x=gs(E,0,!0),S=gs(y,0,!0);let R=r,A=0;const I=y&&(!E||!l&&T<v||l&&l.trackId===f.audio.id),b=I?y:E;if(b){const B=b.timescale,K=b.start-r*B,W=I?f.audio.id:f.video.id;R=b.start/B,A=I?S-T:x-v,(n||!l)&&(yu(l,R,r,A)||B!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${K/B} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${R-r} (${K}/${B}) trackId: ${W}`),l=null,g.initPTS=K,g.timescale=B,g.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=R,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const L=R-l.baseTime/l.timescale,C=L+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,U=!!f.video;let F="";w&&(F+="audio"),U&&(F+="video");const N=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),k={data1:d,startPTS:L,startDTS:L,endPTS:C,endDTS:C,type:F,hasAudio:w,hasVideo:U,nb:1,dropped:0,encrypted:N};u.audio=w&&!U?k:void 0,u.video=U?k:void 0;const $=E?.sampleCount;if($){const B=E.keyFrameIndex,K=B!==-1;k.nb=$,k.dropped=B===0||this.isVideoContiguous?0:K?B:$,k.independent=K,k.firstKeyFrame=B,K&&E.keyFrameStart&&(k.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${B}/${$} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return u.initSegment=g,u.id3=oo(s,r,l,l),i.samples.length&&(u.text=lo(i,r,l)),u}}function gs(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function yu(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function In(a,e,t){const s=a.codec;return s&&s.length>4?s:e===le.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?ws(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let lt;try{lt=self.performance.now.bind(self.performance)}catch{lt=Date.now}const bs=[{demux:su,remux:pu},{demux:mt,remux:Rs},{demux:Zh,remux:Rs},{demux:eu,remux:Rs}];bs.splice(2,0,{demux:Jh,remux:Rs});class Ln{constructor(e,t,s,i,r,n){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=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=lt();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:v,initSegmentData:T}=c,x=Eu(n,t);if(x&&Ft(x.method)){const I=this.getDecrypter(),b=rr(x.method);if(I.isSync()){let L=I.softwareDecrypt(n,x.key.buffer,x.iv.buffer,b);if(s.part>-1){const w=I.flush();L=w&&w.buffer}if(!L)return r.executeEnd=lt(),di(s);n=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(n,x.key.buffer,x.iv.buffer,b).then(L=>{const C=this.push(L,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const S=this.needsProbing(h,u);if(S){const I=this.configureTransmuxer(n);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=lt(),di(s)}(h||u||f||S)&&this.resetInitSegment(T,p,y,v,t),(h||f||S)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const R=this.transmux(n,x,g,d,s);this.asyncResult=ts(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=lt(),R}flush(e){const t=e.transmuxing;t.executeStart=lt();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=lt();const u=[di(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return ts(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===V.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=lt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=bs.length;u<d;u++){var n;if((n=bs[u].demux)!=null&&n.probe(e,this.logger)){r=bs[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new sr(this.config)),e}}function Eu(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const di=a=>({remuxResult:{},chunkMeta:a});function ts(a){return"then"in a&&a.then instanceof Function}class vu{constructor(e,t,s,i,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=s,this.duration=i,this.defaultInitPts=r||null}}class Tu{constructor(e,t,s,i,r,n){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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Rn=0;class co{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rn++,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 l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=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:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new or,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=$r(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||Ih()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Rh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Lh());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ce(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rn++;const t=this.hls.config,s=$r(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),bh(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,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=n?n.start:r.start,y=r.decryptdata,E=this.frag,v=!(E&&r.cc===E.cc),T=!(E&&l.level===E.level),x=E?l.sn-E.sn:-1,S=this.part?l.part-this.part.index:-1,R=x===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!T&&(x===1||x===0&&(S===1||R&&S<=0)),I=self.performance.now();(T||x||r.stats.parsing.start===0)&&(r.stats.parsing.start=I),n&&(S||!A)&&(n.stats.parsing.start=I);const b=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),L=new Tu(v,A,c,T,p,b);if(!A||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===V.MAIN?"level":"track"}: ${l.level} id: ${l.id} 17 - discontinuity: ${v} 18 - trackSwitch: ${T} 19 - contiguous: ${A} 20 - accurateTimeOffset: ${c} 21 - timeOffset: ${p} 22 - initSegmentChange: ${b}`);const C=new vu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){const C=f.push(e,y,l,L);ts(C)?C.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);ts(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const bn=100;class Su extends ar{constructor(e,t,s){super(e,t,s,"audio-stream-controller",V.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:s,initPTS:i,timescale:r,trackId:n}){if(s===V.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=La(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(bn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=P.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:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,le.AUDIO,V.AUDIO));const h=this.getFwdBufferInfo(l,V.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(u>=d&&!this.switchingTrack&&y<g[g.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,V.MAIN,d)),!E){this.bufferFlushed=!0;return}let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&me(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ee.OK&&(this.mainFragLoading=v=null),v&&me(v))){if(E.start>v.end){const x=this.fragmentTracker.getFragAtPos(y,V.MAIN);x&&x.end>v.end&&(v=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(E.start>v.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Zt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(bn),this.state=P.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Va(r,l),r.alignedSliding||$s(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new co(this.hls,V.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,E=y!==-1,v=new ir(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,f,u,"",s,i,h.totalduration,!1,v,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ha,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===V.MAIN&&me(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==V.AUDIO){!this.audioOnly&&s.type===V.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(me(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,ie({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===J.AUDIO_TRACK&&(this.state=P.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,V.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:g,id3:f,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=d;l&&(l.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),c.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(d,c,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=ne({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=ne({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=V.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===Ee.NOT_LOADED||i===Ee.PARTIAL){var r;if(!me(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=P.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&$s(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;Lt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,At)||(Fs(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,ie({},e))}}class gr extends Ve{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,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Gr(s);return new Kr(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){fh(s,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:x}=t;T.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:x,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,g=(i.edge-d)*1e3,f=Ba(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,T=i.lastPartSn,x=i.endSN,S=i.lastPartIndex,R=S!==-1,A=T===x;R?A?(y=x+1,E=v?0:S):(y=T,E=v?S+1:i.maxPartIndex):y=x+1;const I=i.age,b=I+i.ageHeader;let L=Math.min(b-i.partTarget,i.targetduration*1.5);if(L>0){if(b>i.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&b-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${i.age}`),L=0;else{const C=Math.floor(L/i.targetduration);if(y+=C,E!==void 0){const w=Math.round(L%i.targetduration/i.partTarget);E+=w}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${L} skip sn ${C} to part ${E}`)}i.tuneInGoal=L}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),v||!A){i.requestScheduled=n,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Gr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Is.No),new Kr(s,i,r)}checkRetry(e){const t=e.details,s=Ms(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Ie.RetryRequest||!i.resolved&&r===Ie.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=tr(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function ho(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!ss(a[t].attrs,e[t].attrs))return!1;return!0}function ss(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function $i(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class xu extends gr{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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=Je(c,o,At);if(d>-1)r=o[d];else{const g=Je(c,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var n;const d=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===J.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Lt(e,i,At))return i;const r=Je(e,this.tracksInGroup,At);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=Oc(e,t.levels,s,n,At);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=Je(e,s);if(n>-1)return s[n]}}}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 s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,ie({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Lt(e,i,At)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(Lt({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},h,At))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ss(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ss(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Fs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Au{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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 i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.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?"<destroyed>":` 23 - ${this.list("video")} 24 - ${this.list("audio")} 25 - ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const _n=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,uo="HlsJsTrackRemovedError";class Iu extends Error{constructor(e){super(e),this.name=uo}}class Lu extends Ve{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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,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:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ql(Et(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 s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ne(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ne({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Et(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Dn(s),Ru(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) 26 - required tracks: ${ce(s,(c,l)=>c==="initSegment"?void 0:l)}; 27 - transfer tracks: ${ce(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!oa(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,g=h.id;if(d.hasFragments(g)||d.hasParts(g)){const y=j.getBuffered(u);d.detectEvictedFragments(l,y,g,null,!0)}const f=fi(l),p=[l,u];this.sourceBuffers[f]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&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}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Dn(i),i.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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Au(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:g,levelCodec:f,container:p,metadata:y,supplemental:E}=u;let v=i[c];const T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],x=T!=null&&T.buffer?T:v,S=x?.pendingCodec||x?.codec,R=x?.levelCodec;v||(v=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:E,container:p,levelCodec:f,metadata:y,id:d});const A=As(S,R),I=A?.replace(_n,"$1");let b=As(g,f);const L=(h=b)==null?void 0:h.replace(_n,"$1");b&&A&&I!==L&&(c.slice(0,5)==="audio"&&(b=ws(b,this.appendSource)),this.log(`switching codec ${S} to ${b}`),b!==(v.pendingCodec||v.codec)&&(v.pendingCodec=b),v.container=p,this.appendChangeType(c,p,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,V.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&j.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,V.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:g}=o,f=self.performance.now();u.start=f;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);const E=s.audio;let v=!1;r==="audio"&&E?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,x=T?.buffer;if(x&&d!=="initSegment"){const A=c||o,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const L=A.start+A.duration*.05,C=x.buffered,w=this.currentOp("video");!C.length&&!w?this.blockAudio(A):!w&&!j.isBuffered(x,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(A)}else if(r==="video"){const b=A.end;if(I){const L=I.frag.start;(b>L||b<this.lastVideoAppendEnd||j.isBuffered(x,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}const S=(c||o).start,R={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const I=(A=this.tracks[r])==null?void 0:A.buffer;I&&(v?this.updateTimestampOffset(I,S,.1,r,d,g):h!==void 0&&G(h)&&this.updateTimestampOffset(I,h,1e-6,r,d,g)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const I={};this.sourceBuffers.forEach(([b,L])=>{b&&(I[b]=j.getBuffered(L))}),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:o,part:c,chunkMeta:l,parent:o.type,timeRanges:I})},onError:A=>{var I;const b={type:Y.MEDIA_ERROR,parent:o.type,details:D.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},L=(I=this.media)==null?void 0:I.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)b.details=D.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)b.errorAction=Ot(!0);else if(A.name===uo&&this.sourceBufferCount===0)b.errorAction=Ot(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${L||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||L)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===V.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(R,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[le.AUDIOVIDEO]?r.push("audiovideo"):(n[le.AUDIO]&&r.push("audio"),n[le.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,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 s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.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===D.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;G(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(G(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(G(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=j.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=j.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return G(r)?{duration:r}:null;const n=this.media.duration,o=G(s.duration)?s.duration:0;return i>o&&i>n||!G(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(G(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ce(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.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:Y.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ce(o)}`);try{const h=s.addSourceBuffer(l),u=fi(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&zt(s,"video")&&(i=mc(i,s));const r=As(i,e.levelCodec);return r?t.slice(0,5)==="audio"?ws(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=G(i.duration)?i.duration:1/0,l=G(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Iu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.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:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Dn(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Ru(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function fi(a){return a==="audio"?1:0}class mr{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 s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&G(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,mr.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const bu={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ke=bu,_u={HLS:"h"},Du=_u;class tt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof tt?s:new tt(s))),this.value=e,this.params=t}}const Cu="Dict";function Pu(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function ku(a,e,t,s){return new Error(`failed to ${a} "${Pu(e)}" as ${t}`,{cause:s})}function st(a,e,t){return ku("serialize",a,e,t)}class fo{constructor(e){this.description=e}}const Cn="Bare Item",wu="Boolean";function Ou(a){if(typeof a!="boolean")throw st(a,wu);return a?"?1":"?0"}function Fu(a){return btoa(String.fromCharCode(...a))}const Mu="Byte Sequence";function Nu(a){if(ArrayBuffer.isView(a)===!1)throw st(a,Mu);return`:${Fu(a)}:`}const Bu="Integer";function Uu(a){return a<-999999999999999||999999999999999<a}function go(a){if(Uu(a))throw st(a,Bu);return a.toString()}function $u(a){return`@${go(a.getTime()/1e3)}`}function mo(a,e){if(a<0)return-mo(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const Gu="Decimal";function Ku(a){const e=mo(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw st(a,Gu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Vu="String",Hu=/[\x00-\x1f\x7f]+/;function Yu(a){if(Hu.test(a))throw st(a,Vu);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Wu(a){return a.description||a.toString().slice(7,-1)}const qu="Token";function Pn(a){const e=Wu(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw st(e,qu);return e}function Gi(a){switch(typeof a){case"number":if(!G(a))throw st(a,Cn);return Number.isInteger(a)?go(a):Ku(a);case"string":return Yu(a);case"symbol":return Pn(a);case"boolean":return Ou(a);case"object":if(a instanceof Date)return $u(a);if(a instanceof Uint8Array)return Nu(a);if(a instanceof fo)return Pn(a);default:throw st(a,Cn)}}const ju="Key";function Ki(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw st(a,ju);return a}function pr(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${Ki(e)}`:`;${Ki(e)}=${Gi(t)}`).join("")}function po(a){return a instanceof tt?`${Gi(a.value)}${pr(a.params)}`:Gi(a)}function Xu(a){return`(${a.value.map(po).join(" ")})${pr(a.params)}`}function zu(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw st(a,Cu);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof tt||(r=new tt(r));let n=Ki(i);return r.value===!0?n+=pr(r.params):(n+="=",Array.isArray(r.value)?n+=Xu(r):n+=po(r)),n}).join(`,${s}`)}function yo(a,e){return zu(a,e)}const Xe="CMCD-Object",fe="CMCD-Request",St="CMCD-Session",ft="CMCD-Status",Qu={br:Xe,ab:Xe,d:Xe,ot:Xe,tb:Xe,tpb:Xe,lb:Xe,tab:Xe,lab:Xe,url:Xe,pb:fe,bl:fe,tbl:fe,dl:fe,ltc:fe,mtp:fe,nor:fe,nrr:fe,rc:fe,sn:fe,sta:fe,su:fe,ttfb:fe,ttfbb:fe,ttlb:fe,cmsdd:fe,cmsds:fe,smrt:fe,df:fe,cs:fe,ts:fe,cid:St,pr:St,sf:St,sid:St,st:St,v:St,msd:St,bs:ft,bsd:ft,cdn:ft,rtp:ft,bg:ft,pt:ft,ec:ft,e:ft},Zu={REQUEST:fe};function Ju(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function ed(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?Ju(e):{};return s.reduce((r,n)=>{var o;const c=Qu[n]||i[n]||Zu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function td(a){return["ot","sf","st","e","sta"].includes(a)}function sd(a){return typeof a=="number"?G(a):a!=null&&a!==""&&a!==!1}const Eo="event";function id(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const _s=a=>Math.round(a),Vi=(a,e)=>Array.isArray(a)?a.map(t=>Vi(t,e)):a instanceof tt&&typeof a.value=="string"?new tt(Vi(a.value,e),a.params):(e.baseUrl&&(a=id(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),ms=a=>_s(a/100)*100,rd=(a,e)=>{let t=a;return e.version>=2&&(a instanceof tt&&typeof a.value=="string"?t=new tt([a]):typeof a=="string"&&(t=[a])),Vi(t,e)},nd={br:_s,d:_s,bl:ms,dl:ms,mtp:ms,nor:rd,rtp:ms,tb:_s},vo="request",To="response",yr=["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"],ad=["e"],od=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function qs(a){return od.test(a)}function ld(a){return yr.includes(a)||ad.includes(a)||qs(a)}const So=["d","dl","nor","ot","rtp","su"];function cd(a){return yr.includes(a)||So.includes(a)||qs(a)}const hd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ud(a){return yr.includes(a)||So.includes(a)||hd.includes(a)||qs(a)}const dd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function fd(a){return dd.includes(a)||qs(a)}const gd={[To]:ud,[Eo]:ld,[vo]:cd};function xo(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||vo,r=s===1?fd:gd[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===To||i===Eo;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ne({},nd,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const g=l[u];if(typeof g=="function"&&(d=g(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!G(d)&&(d=Date.now()),sd(d)&&(td(u)&&typeof d=="string"&&(d=new fo(d)),t[u]=d))}),t}function md(a,e={}){const t={};if(!a)return t;const s=xo(a,e),i=ed(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=yo(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function pd(a,e,t){return ne(a,md(e,t))}const yd="CMCD";function Ed(a,e={}){return a?yo(xo(a,e),{whitespace:!1}):""}function vd(a,e={}){if(!a)return"";const t=Ed(a,e);return encodeURIComponent(t)}function Td(a,e={}){if(!a)return"";const t=vd(a,e);return`${yd}=${t}`}const kn=/CMCD=[^&#]+/;function Sd(a,e,t){const s=Td(e,t);if(!s)return a;if(kn.test(a))return a.replace(kn,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class xd{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=i=>{try{this.apply(i,{ot:ke.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===ke.VIDEO||c===ke.AUDIO||c==ke.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.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 s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Du.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ne(t,this.createData());const s=t.ot===ke.INIT||t.ot===ke.VIDEO||t.ot===ke.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),pd(e.headers,t,r)):e.url=Sd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ke.TIMED_TEXT;if(e.sn==="initSegment")return ke.INIT;if(t==="audio")return ke.AUDIO;if(t==="main")return this.hls.audioTracks.length?ke.VIDEO:ke.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ke.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===ke.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:j.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const Ad=3e5;class Id extends Ve{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===Ie.SendAlternateToPenaltyBox&&s.flags===Ne.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===D.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ce(r)} penalized: ${ce(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Ad&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ga(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===J.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===J.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new ue(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=Ao(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Zt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${n}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${n}`);return p});t.push(...l),wn(this.audioTracks,s,c,n),wn(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const v={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,v),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wn(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ne({},n);return o.details=void 0,o.attrs=new ue(o.attrs),o.url=o.attrs.URI=Ao(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Ao(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Mt extends Ve{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=Mt.CDMCleanupPromise?[Mt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Wt(this.config));const o=n.map(ni).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=Ls(n);if(s!=="sinf"||o!==de.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=pe(new Uint8Array(i)),f=nr(JSON.parse(g).sinf),p=pa(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}const l=Le(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let g=0;g<u.length;g++){const f=u[g],p=f.decryptdata;if(!p.keyId)continue;const y=Le(p.keyId);if(Bs(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},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:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===de.WIDEVINE&&s)return s}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,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Me?o(u):o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return wa===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=rh(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ce(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Le(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=ps(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Le(e.decryptdata.keyId||[])} 28 - } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ni(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=ni(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Wt(this.config),s=e.map(Ls).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Ld(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=ps(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=On(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Me){const c=ie({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Me(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Me){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Le(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ps(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ls(e.keyFormat),r=i?[i]:Wt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Wt(this.config)),e.length===0)throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const f=n.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=ps(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new or,h=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(v=>{l.eventNames().length?l.emit("error",v):this.handleError(v)}):y==="license-release"?e.keySystem===de.FAIRPLAY&&this.updateKeySession(e,Fi("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${y}"`)},u=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=On(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(x=>y[x]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ce(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let v=y[o];if(v)u(v,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const S=this.getKeyStatus(e.decryptdata);if(S&&S!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${S} from other session.`),u(S,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",u(v,e)},1e3)),this.log(`No status for keyId ${o} (${ce(y)}).`)}};Ce(e.mediaKeysSession,"message",h),Ce(e.mediaKeysSession,"keystatuseschange",d);const g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===de.PLAYREADY&&r.length===16){const o=Le(r);t[o]=s,Pa(r)}const n=Le(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{n(d.data)},onError:(d,g,f,p)=>{o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ie({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Fi(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Me({type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==de.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ce(s,"encrypted",this.onMediaEncrypted),Ce(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Oe(e,"encrypted",this.onMediaEncrypted),Oe(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 s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,yt.clearKeyUriToKeyIdMap();const r=i.length;Mt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).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 s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Le(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(ah(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Mt.CDMCleanupPromise=void 0;function ps(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return Le(a.keyId)}function Ld(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Me 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 On(a,e){const t=a==="output-restricted",s=t?D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Me({type:Y.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class Rd{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 s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,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 Io(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Lo(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){re.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){re.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function wt(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function Hi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=_d(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function bd(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function _d(a,e,t){const s=[],i=bd(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Ds(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Dd extends gr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=Ds(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-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 s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;Ds(s.textTracks).forEach(n=>{wt(n)})}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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Je(o,n);if(h>-1)r=n[h];else{const u=Je(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||Lt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(ss(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(ss(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if($i(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===J.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Lt(e,s))return s;const i=Je(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Je(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 s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Ds(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>$i(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function Cd(){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,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Xt(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Nt=.025;let Ks=(function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a})({});function Pd(a,e,t){return`${a.identifier}-${t+1}-${Xt(e)}`}class kd{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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 gi(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,s=gi(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=G(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 gi(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)<Nt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Ks.Range:Ks.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return wd(this)}}function gi(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Nt)?e.start:e.start+e.duration}function Ro(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function mi(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function wd(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function kt(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Od{constructor(e,t,s,i){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=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,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=Ro(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 s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=j.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=j.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 s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${kt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fn=.033;class Fd extends Ve{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,g=h.cue.pre,f=h.cue.post;if(u&&!g)return-1;if(g&&!u||d&&!f)return 1;if(f&&!d)return-1;if(!u&&!g&&!d&&!f){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new kd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,g=h.cue.post,f=e[u-1]||null,p=h.appendInPlace,y=g?r:h.startOffset,E=h.duration,v=h.timelineOccupancy===Ks.Range?E:0,T=h.resumptionOffset,x=f?.startTime===y,S=y+h.cumulativeDuration;let R=p?S+E:y+T;if(d||!g&&y<=0){const I=l;l+=v,h.timelineStart=S;const b=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:b,end:n},integrated:{start:I,end:l}})}else if(y<=r){if(!x){const L=y-c;if(L>Fn){const C=c,w=l;l+=L;const U=n;n+=L;const F={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+L,playout:{start:U,end:n},integrated:{start:w,end:l}};s.push(F)}else L>0&&f&&(f.cumulativeDuration+=L,s[s.length-1].end=y)}g&&(R=S),h.timelineStart=S;const I=l;l+=v;const b=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:b,end:n},integrated:{start:I,end:l}})}else return;const A=h.resumeTime;g||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const g=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:g,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Rt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Fn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=G(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Nt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=Rt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Nt+h||Math.abs(l.end-s)<Nt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ye(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class Md{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ro(s,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){const v=this.assignAssetListError(e,D.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,v);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,g,f,p)=>{const y=this.assignAssetListError(e,D.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,D.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:Y.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Mn(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function ys(a,e){return`[${a}] Advancing timeline position to ${e}`}class Nd extends Ve{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} 29 - Schedule: ${c.map(p=>Ye(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,g=null;n&&(d=this.updateItem(n,this.timelinePos),this.itemsMatch(n,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(v){Math.abs(E)>Nt&&this.warn(`${v} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(d,n),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Md(e),this.schedule=new Fd(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){Oe(e,"play",this.onPlay),Oe(e,"pause",this.onPause),Oe(e,"seeking",this.onSeeking),Oe(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ce(s,"seeking",this.onSeeking),Ce(s,"timeupdate",this.onTimeupdate),Ce(s,"play",this.onPlay),Ce(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),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,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,g,f,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Ks.Point){const v=s(g);v?.interstitial===E&&(y+=v.assetItem.startOffset+v[p])}}else{const v=f==="bufferedPos"?n():e[f];y+=v-u.start}return y}return 0},r=(u,d)=>{var g;if(u!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(u),y=(f=e.schedule.items)==null?void 0:f[p];if(y){const E=y[d].start-y.start;return u+E}}return u},n=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[u])||0},c=(u,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),v=(f=e.schedule.items)==null?void 0:f[E],T=e.getBufferingPlayer(),x=T?.interstitial,S=x?.appendInPlace,R=y&&e.itemsMatch(y,v);if(y&&(S||R)){const A=s(e.playingAsset),I=A?.media||e.primaryMedia;if(I){const b=d==="primary"?I.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),L=u-b,C=(S?b:I.currentTime)+L;if(C>=0&&(!A||S||C<=A.duration)){I.currentTime=C;return}}}if(v){let A=u;if(d!=="primary"){const b=v[d].start,L=u-b;A=v.start+L}const I=!e.isInterstitial(v);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(I||v.event.appendInPlace)){const b=e.media||(S?T?.media:null);b&&(b.currentTime=A)}else if(y){const b=e.findItemIndex(y);if(E>b){const C=e.schedule.findJumpRestrictedIndex(b+1,E);if(C>b){e.setSchedulePosition(C);return}}let L=0;if(I)e.timelinePos=A,e.checkBuffer();else{const C=v.event.assetList,w=u-(v[d]||v).start;for(let U=C.length;U--;){const F=C[U];if(F.duration&&w>=F.startOffset&&w<F.startOffset+F.duration){L=U;break}}}e.setSchedulePosition(E,L)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var g;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),g=e.effectivePlayingItem;g&&g===d&&c(u+g.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return n()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(u);if(d.appendInPlace){const f=u.playout.start+u.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!G(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ce(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),h=`${f}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ce(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(d===r&&g){const f=o&&e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}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 s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(ys("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=mi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=mi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(ys("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ye(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,u=this.playingAsset,d=u?.identifier,g=d?this.getAssetPlayer(d):null;if(g&&d&&(!this.eventItemsMatch(n,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const f=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${h.assetList.length} ${kt(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:f,event:h,schedule:i.slice(0),scheduleIndex:e,player:g}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(d,r),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ye(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const p=this.findItemIndex(r);this.advanceSchedule(p,f,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=n.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const f=mi(h,s-1);if(h.isAssetPastPlayoutLimit(f)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=f}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ye(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=h.assetList[s];if(!g){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=h.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${h}`),d=this.createAssetPlayer(h,g,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Mn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Mn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.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,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ye(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(ys("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ye(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:j.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(ys("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.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 s=this.hls.levels[t.level];if(!s.details)return;const i=ie(ie({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ie(ie({},this.altSelection),{},{audio:s});return}const r=ie(ie({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ie(ie({},this.altSelection),{},{subtitles:s});return}const r=ie(ie({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=j.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ye(e)} (was ${Ye(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=j.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const g=r.event;if(u-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ye(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:Pd(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ne({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const x=this.timelinePos-t.timelineStart;if(x>1){const S=t.duration;S&&x<S&&(h=x)}}const u=t.identifier,d=ie(ie({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=ne({},g,{contentId:Xt(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const f=new Od(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0;const y=x=>{if(x.live){var S;const I=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},L=((S=this.schedule)==null?void 0:S.findEventIndex(e.identifier))||-1;this.handleAssetItemError(b,e,L,s,I.message);return}const R=x.edge-x.fragmentStart,A=t.duration;(p||A===null||R>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${R}`),t.duration=R,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(x,{details:S})=>y(S)),f.on(m.LEVEL_PTS_UPDATED,(x,{details:S})=>y(S)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(x,S)=>{const R=this.getAssetPlayer(u);if(R&&S.tracks){R.off(m.BUFFER_CODECS,E),R.tracks=S.tracks;const A=this.primaryMedia;this.bufferingAsset===R.assetItem&&A&&!R.media&&this.bufferAssetPlayer(R,A)}};f.on(m.BUFFER_CODECS,E);const v=()=>{var x;const S=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const R=this.schedule.findEventIndex(e.identifier),A=(x=this.schedule.items)==null?void 0:x[R];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};f.on(m.BUFFERED_TO_END,v);const T=x=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,x)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(x,S)=>{if(!this.schedule)return;const R=this.getAssetPlayer(u);if(S.details===D.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${S.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const S=new Error(`Asset player destroyed unexpectedly ${u}`),R={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),s,S.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${kt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ye(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${kt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const u=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!oa(u,e.tracks)){const d=new Error(`Asset ${kt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),g={fatal:!0,type:Y.OTHER_ERROR,details:D.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===D.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&kt(n)} ${e.error}`),!this.schedule)return;const o=n?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=ne({},e,{fatal:!1,errorAction:Ot(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Ye(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===n;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(d){var f;const p=this.schedule.findEventIndex(n),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.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(y)}this.setSchedulePosition(p)}else if(g?.identifier===n){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case D.ASSET_LIST_PARSING_ERROR:case D.ASSET_LIST_LOAD_ERROR:case D.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case D.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Nn=500;class Bd extends ar{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",V.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=P.IDLE,this.setInterval(Nn),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:s,success:i}=t;if(this.fragContextChanged(s)||(me(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,V.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===V.SUBTITLE&&(t.details===D.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ho(this.levels,t)){this.levels=t.map(s=>new Zt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Zt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Nn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)n.hasProgramDateTime&&u.hasProgramDateTime?($s(n,u),l=n.fragmentStart):d&&(l=d.start,Ni(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,Ni(n,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(Rt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Ft(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,rr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=j.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const v=i.maxFragLookUpTolerance,T=o>g-v?0:v;f=Rt(p,u,Math.max(u[0].start,o),T),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,E=u[y-1];if(E&&E.cc===f.cc&&this.fragmentTracker.getState(E)===Ee.NOT_LOADED&&(f=E),this.fragmentTracker.getState(f)===Ee.NOT_LOADED){const v=this.mapToInitFragWhenRequired(f);v&&this.loadFragment(v,s,o)}}}loadFragment(e,t,s){me(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ud(this.tracksBuffered[this.currentTrackId]||[])}}class Ud{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const $d={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},bo=a=>String.fromCharCode($d[a]||a),We=15,nt=100,Gd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Kd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Yd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Wd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;re.log(`${this.time} [${e}] ${s}`)}}}const xt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class _o{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class qd{constructor(){this.uchar=" ",this.penState=new _o}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class jd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new _o,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<nt;t++)this.chars.push(new qd);this.logger=e}equals(e){for(let t=0;t<nt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<nt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<nt;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>nt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=nt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=bo(e);if(this.pos>=nt){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<nt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<nt;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class pi{constructor(e){this.rows=[],this.currRow=We-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<We;t++)this.rows.push(new jd(e));this.logger=e}reset(){for(let e=0;e<We;e++)this.rows[e].clear();this.currRow=We-1}equals(e){let t=!0;for(let s=0;s<We;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<We;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<We;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ce(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<We;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ce(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 s="",i=-1;for(let r=0;r<We;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(` 30 - `)),s}getTextAndFormat(){return this.rows}}class Bn{constructor(e,t,s){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 pi(s),this.nonDisplayedMemory=new pi(s),this.lastOutputScreen=new pi(s),this.currRollUpRow=this.displayedMemory.rows[We-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[We-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ce(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 Un{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=zd(),this.logger=void 0;const i=this.logger=new Wd;this.channels=[null,new Bn(e,t,i),new Bn(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+xt([t[s],t[s+1]])+"] -> ("+xt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Xd(i,r,c)){Es(null,null,c),this.logger.log(3,()=>"Repeated command ("+xt([i,r])+") is dropped");continue}Es(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Es(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+xt([i,r])+" orig: "+xt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+xt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?Gd[e]:Vd[e]:s=n===1?Kd[e]:Hd[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+bo(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+xt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Yd[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Es(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Es(a,e,t){t.a=a,t.b=e}function Xd(a,e,t){return t.a===a&&t.b===e}function zd(){return{a:null,b:null}}var Er=(function(){if(Us!=null&&Us.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function n(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",g=!1,f=o,p=c,y=l,E=null,v="",T=!0,x="auto",S="start",R=50,A="middle",I=50,b="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return g},set:function(L){g=!!L}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");f=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(L){E=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return v},set:function(L){const C=s(L);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");v=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return x},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");x=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return S},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");S=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return R},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");R=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return b},set:function(L){const C=i(L);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");b=C,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n})();class Qd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Do(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.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 Zd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Co(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const Yi=new Er(0,0,""),vs=Yi.align==="middle"?"middle":"center";function Jd(a,e,t){const s=a;function i(){const o=Do(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new Zd;Co(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(d,f[0]),l.percent(d,f[0])&&l.set("snapToLines",!1),l.alt(d,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",vs,"end"]);break;case"position":f=g.split(","),l.percent(d,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",vs,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,g);break;case"align":l.alt(d,g,["start",vs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Yi.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",vs);let u=l.get("position","auto");u==="auto"&&Yi.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function Po(a){return a.replace(/<br(?: \/)?>/gi,` 31 - `)}class ef{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Qd,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 s(){let r=t.buffer,n=0;for(r=Po(r);n<r.length&&r[n]!=="\r"&&r[n]!==` 32 - `;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===` 33 - `&&++n,t.buffer=r.slice(n),o}function i(r){Co(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Er(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Jd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!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+=` 34 - `),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+=` 35 - 36 - `,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 tf=/\r\n|\n\r|\n|\r/g,yi=function(e,t,s=0){return e.slice(s,s+t.length)===t},sf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(s)||!G(i)||!G(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function vr(a,e,t){return Xt(a.toString())+Xt(e.toString())+Xt(t)}const rf=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function nf(a,e,t,s,i,r,n){const o=new ef,c=$e(new Uint8Array(a)).trim().replace(tf,` 37 - `).split(` 38 - `),l=[],h=e?hu(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,p=!0;o.oncue=function(y){const E=t[s];let v=t.ccOffset;const T=(d-h)/9e4;if(E!=null&&E.new&&(g!==void 0?v=t.ccOffset=E.start:rf(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}v=T-t.presentationOffset}const x=y.endTime-y.startTime,S=Be((y.startTime+v-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(S,0),y.endTime=Math.max(S+x,0);const R=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(R)),y.id||(y.id=vr(y.startTime,y.endTime,R)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){n(f);return}r(l)},c.forEach(y=>{if(p)if(yi(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{yi(E,"LOCAL:")?u=E.slice(6):yi(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=sf(u)/1e3}catch(E){f=E}return}else y===""&&(p=!1);o.parse(y+` 39 - `)}),o.flush()}const Ei="stpp.ttml.im1t",ko=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,af={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(a,e,t,s){const i=Q(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>$e(o)),n=cu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(of(o,n)))}catch(o){s(o)}}function of(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Gn(vi(i,"styling","style")),l=Gn(vi(i,"layout","region")),h=vi(i,"body","[begin]");return[].map.call(h,u=>{const d=Oo(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=Si(u.getAttribute("begin"),n),f=Si(u.getAttribute("dur"),n);let p=Si(u.getAttribute("end"),n);if(g===null)throw Kn(u);if(p===null){if(f===null)throw Kn(u);p=g+f}const y=new Er(g-e,p-e,d);y.id=vr(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],v=c[u.getAttribute("style")],T=lf(E,v,c),{textAlign:x}=T;if(x){const S=af[x];S&&(y.lineAlign=S),y.align=x}return ne(y,T),y}).filter(u=>u!==null)}function vi(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gn(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Oo(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+` 40 - `:(r=s.childNodes)!=null&&r.length?Oo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function lf(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=Ti(e,s,c)||Ti(a,s,c)||Ti(i,s,c);return l&&(o[c]=l),o},{})}function Ti(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Kn(a){return new Error(`Could not parse ttml timestamp ${a}`)}function Si(a,e){if(!a)return null;let t=Do(a);return t===null&&(ko.test(a)?t=cf(a,e):wo.test(a)&&(t=hf(a,e))),t}function cf(a,e){const t=ko.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function hf(a,e){const t=wo.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class Ts{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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class uf{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=Hn(),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 Ts(this,"textTrack1"),t=new Ts(this,"textTrack2"),s=new Ts(this,"textTrack3"),i=new Ts(this,"textTrack4");this.cea608Parser1=new Un(1,e,t),this.cea608Parser2=new Un(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=df(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===V.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.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:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Vn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,wt(s[e]),Io(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{wt(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hn(),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 s=0;s<t.length;s++)wt(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ei);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ho(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?Ds(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Vn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)wt(h);else{const u=Fo(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.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 n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===V.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===V.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ei?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;$n(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?Ke(s.initSegment.data,new Uint8Array(i)).buffer:i;nf(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||$n(t,this.initPTS[e.cc],()=>{s.textCodec=Ei,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>Lo(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===V.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===V.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Hi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Hi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function Fo(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Vn(a,e){return!!a&&a.kind===Fo(e)&&$i(e,a)}function df(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Hn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const ff=/\s/,gf={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)ff.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=Po(l.trim()),f=vr(e,t,g);a!=null&&(u=a.cues)!=null&&u.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=d+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>Lo(a,d))),i}};function mf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const pf=/(\d+)-(\d+)\/(\d+)/;class Yn{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||Tf,this.controller=new self.AbortController,this.stats=new Qi}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,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=yf(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&G(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(ts(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new Sf(y||"fetch, bad network response",p,u)}i.loading.first=g,i.total=vf(u.headers)||i.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&G(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,f):n?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:u,code:f.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!G(t.highWaterMark)&&E(i,e,u,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=u&&u.code||0,f=u?u.message:null;(d=this.callbacks)==null||d.onError({code:g,text:f},e,u?u.details:null,i)})}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,s,i=0,r){const n=new Ha,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function yf(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ne({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Ef(a){const e=pf.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function vf(a){const e=a.get("Content-Range");if(e){const s=Ef(e);if(G(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function Tf(a,e){return new self.Request(a.url,e)}class Sf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xf=/^age:\s*[\d.]+\s*$/im;class Mo{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 Qi,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,s){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=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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),s.timeout=r&&G(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=h??t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(n=this.callbacks)==null?void 0:n.onProgress;y&&y(s,e,f,t);const E={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,g={url:e.url,data:void 0,code:l};if(Ns(u,d,!1,g))this.retry(u);else{var c;re.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ns(e,t,!0))this.retry(e);else{var s;re.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=tr(e,s.retry),s.retry++,re.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.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&&xf.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 Af={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},If=ie(ie({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:Mo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fc,bufferController:Lu,capLevelController:mr,errorController:$c,fpsController:Rd,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:wa,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:Af},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},Lf()),{},{subtitleStreamController:Bd,subtitleTrackController:Dd,timelineController:uf,audioStreamController:Su,audioTrackController:xu,emeController:Mt,cmcdController:xd,contentSteeringController:Id,interstitialsController:Nd});function Lf(){return{cueHandler:gf,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 Rf(a,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 s=Wi(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${n}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const g=s[o].default;switch(e[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ce(e[o])}`)}),ie(ie({},s),e)}function Wi(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Wi):Object.keys(a).reduce((e,t)=>(e[t]=Wi(a[t]),e),{}):a}function bf(a,e){const t=a.loader;t!==Yn&&t!==Mo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):mf()&&(a.loader=Yn,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Cs=2,_f=.1,Df=.05,Cf=100;class Pf extends _a{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.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(Cf),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ce(s,"playing",this.onMediaPlaying),Ce(s,"waiting",this.onMediaWaiting),Ce(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Oe(s,"playing",this.onMediaPlaying),Oe(s,"waiting",this.onMediaWaiting),Oe(s,"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 s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!j.getBuffered(n).length){this.nudgeRetry=0;return}const u=j.bufferInfo(n,e,0),d=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const R=Wn(this.hls.inFlightFragments,e),A=u.len>Cs,I=!d||R||d-e>Cs&&!g.getPartialFragment(e);if(A||I)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,b=!!(f!=null&&f.live)?f.targetduration*2:Cs,L=Ss(e,g);if(A>0&&(A<=b||L)){n.paused||this._trySkipBufferHole(L);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let v=this.stalled;if(v===null)if(E>0&&y-E<p)v=this.stalled=E;else{this.stalled=y;return}const T=y-v;if(!o&&(T>=p||E)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const S=j.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=j.bufferedInfo(j.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=j.timeRangesToArray(i),o=j.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=j.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Ss(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=j.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Ss(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,V.MAIN),n=s.getFragAtPos(i,V.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ce(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=j.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-n;if(d>0&&(h||u)){if(d>r.maxBufferHole){let f=!1;if(n===0){const p=s.getAppendedFrag(0,V.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Wn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const v=Ss(E,s);if(v)E+=v.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(c+Df,n+_f);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${g}`),p={type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wn(a,e){const t=qn(a.main);if(t&&t.start<=e)return t;const s=qn(a.audio);return s&&s.start<=e?s:null}function qn(a){if(!a)return null;switch(a.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return a.frag}function Ss(a,e){return e.getAppendedFrag(a,V.MAIN)||e.getPartialFragment(a)}const kf=.25;function qi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function xi(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ce(i?ie({type:i},s):s))}return r}const xs=(()=>{const a=qi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class wf{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 s;this.media=t.media,((s=t.overrides)==null?void 0:s.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&&wt(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;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Io(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=qi();if(n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===Ue.emsg&&!s||!i)continue;const l=Qa(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>xs&&(u=xs),u-h<=0&&(u=h+kf);for(let g=0;g<l.length;g++){const f=l[g];if(!Za(f)){this.updateId3CueEnds(h,c);const p=xi(n,h,u,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===xs&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===Ue.audioId3&&c:i==="video"?l=h=>h.type===Ue.emsg&&o:l=h=>h.type===Ue.audioId3&&c||h.type===Ue.emsg&&o,Hi(r,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=qi();if(s&&i&&!n){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=xi(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var g;const E=p[y],v=(g=u[E])==null?void 0:g.cues;delete u[E],v&&Object.keys(v).forEach(T=>{const x=v[T];if(x){x.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(x)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(h.length===0||!G(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],v=E.startTime,T=u[y],x=T?.cues||{};let S=T?.durationKnown||!1,R=xs;const{duration:A,endDate:I}=E;if(I&&A!==null)R=v+A,S=!0;else if(E.endOnNext&&!S){const L=h.reduce((C,w)=>{if(w!==E.id){const U=l[w];if(U.class===E.class&&U.startDate>E.startDate&&(!C||E.startDate<C.startDate))return U}return C},null);L&&(R=L.startTime,S=!0)}const b=Object.keys(E.attr);for(let L=0;L<b.length;L++){const C=b[L];if(!Jc(C))continue;const w=x[C];if(w)S&&!(T!=null&&T.durationKnown)?w.endTime=R:Math.abs(w.startTime-v)>.01&&(w.startTime=v,w.endTime=R);else if(o){let U=E.attr[C];eh(C)&&(U=la(U));const N=xi(o,v,R,{key:C,data:U},Ue.dateRange);N&&(N.id=y,this.id3Track.addCue(N),x[C]=N,n&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&N.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:x,dateRange:E,durationKnown:S}}}}}class Of{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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,g)}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:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}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 s=e.buffered.length;return(s?e.buffered.end(s-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 s;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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 Ff extends gr{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 s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:g}=h;d&&(h.audioCodec=d=ws(d,s)||void 0),g&&(g=h.videoCodec=pc(g));const{width:f,height:p,unknownCodecs:y}=h,E=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!d),E||d&&!this.isAudioSupported(d)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":T,"HDCP-LEVEL":x,"PATHWAY-ID":S,RESOLUTION:R,"VIDEO-RANGE":A}=u,b=`${`${S||"."}-`}${h.bitrate}-${R}-${T}-${v}-${A}-${x}`;if(r[b])if(r[b].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const L=n[b]+=1;h.attrs["PATHWAY-ID"]=new Array(L+1).join(".");const C=this.createLevel(h);r[b]=C,i.push(C)}else r[b].addGroupId("audio",u.AUDIO),r[b].addGroupId("text",u.SUBTITLES);else{const L=this.createLevel(h);r[b]=L,n[b]=1,i.push(L)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Zt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Ta(i,[])}return t}isAudioSupported(e){return zt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return zt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:v,videoRange:T,width:x,height:S})=>(!!v||!!(x&&S))&&Rc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ce(t.levels.map(S=>S.attrs.CODECS).filter((S,R,A)=>A.indexOf(S)===R))}`,this.warn(T),v+=` (${T})`);const x=new Error(v);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),jn(o)),t.subtitles&&(c=t.subtitles,jn(c));const u=l.slice(0);l.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return Os.indexOf(v.videoRange)-Os.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){const x=Br(v.videoCodec),S=Br(T.videoCodec);if(x!==S)return S-x}if(v.uri===T.uri&&v.codecSet!==T.codecSet){const x=ks(v.codecSet),S=ks(T.codecSet);if(x!==S)return S-x}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let v=0;v<u.length;v++)if(u[v].pathwayId===l[0].pathwayId){d=u[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===d){var g;this._firstLevel=v;const T=d.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const S=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);S>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}const f=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!f&&o.some(v=>!!v.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i?.details,l);this.loadPlaylist(h)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===J.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===V.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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 s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ga(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}}function jn(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function No(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bo(){if(!Et())return!1;const e=No();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Mf(){if(!Bo())return!1;const a=Et();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Qt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Qt(e,"audio"))))}function Nf(){var a;const e=No();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const Bf=100;class Uf extends ar{constructor(e,t,s){super(e,t,s,"stream-controller",V.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 i=this.media,r=i?i.currentTime:null;if(r===null||!G(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,V.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.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:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Bf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.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 l=n.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&me(g)&&this.fragmentTracker.getState(g)!==Ee.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,E=l.fragments[y-1];E&&g.cc===E.cc&&(g=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,E=(y===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,V.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,V.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ee.NOT_LOADED||i===Ee.PARTIAL?me(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,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,V.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 s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Ce(s,"playing",this.onMediaPlaying),Ce(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Oe(s,"playing",this.onMediaPlaying),Oe(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=j.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:g}=j.bufferedInfo(u.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new co(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new ir(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,p),E=this.initPTS[s.cc];g.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Fs(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Fs(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===V.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),me(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&j.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===J.LEVEL&&(this.state=P.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case D.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 D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==le.AUDIO||!this.altAudio){const s=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,V.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 s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=j.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:h,text:u,id3:d,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){const y=g.tracks;if(y){const x=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,x,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:t,tracks:y})}const E=g.initPTS,v=g.timescale,T=this.initPTS[o.cc];if(G(E)&&(!T||T.baseTime!==E||T.timescale!==v)){const x=g.trackId;this.initPTS[o.cc]={baseTime:E,timescale:v,trackId:x},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:v,trackId:x})}}if(h&&f){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],E=o.sn===f.startSN,v=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:x,startDTS:S,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:x,startDTS:S,endDTS:R};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&I<b-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,x,o.start,R,!0)}else E&&T-(f.appliedTimelineOffset||0)>Cs&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,x,S,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||v)}else if(E||v)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=p;c&&(c.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),o.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(p,o,c,r)}if(f&&d!=null&&d.samples.length){const y={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&u){const y={id:t,frag:o,details:f,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${me(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=As(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=V.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=V.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.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(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,V.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(j.isBuffered(e,s)?t=this.getAppendedFrag(s):j.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.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 G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Rt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}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 $f extends Ve{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.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=D.KEY_LOAD_ERROR,s,i,r){return new ot({type:Y.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!me(e)||!me(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=Ls(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Wt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}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 s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=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,D.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=Ai(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Le(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={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,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=rc(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Le(o)}`),yt.setKeyIdForUri(e.decryptdata.uri,o)):(o=yt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Le(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!me(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const{frag:y,keyInfo:E}=f,v=Ai(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(y,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,n({frag:y,keyInfo:E})},onError:(d,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,ie({url:c.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ai(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Ai(a){if(a.keyFormat!==Re.FAIRPLAY){const e=a.keyId;if(e)return Le(e)}return a.uri}function Xn(a){const{type:e}=a;switch(e){case J.AUDIO_TRACK:return V.AUDIO;case J.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Ii(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Gf{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,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:J.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:J.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:J.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:J.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[J.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[J.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===J.MANIFEST?r=s.manifestLoadPolicy.default:r=ne({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===J.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===J.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===J.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ne({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=l.data;h.parsing.start=performance.now(),et.isMediaPlaylist(f)||u.type!==J.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,g):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Ii(e,s),c=et.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f}=c;this.variableList=f,h.forEach(v=>{const{unknownCodecs:T}=v;if(T){const{preferManagedMediaSource:x}=this.hls.config;let{audioCodec:S,videoCodec:R}=v;for(let A=T.length;A--;){const I=T[A];zt(I,"audio",x)?(v.audioCodec=S=S?`${S},${I}`:I,Bt.audio[S.substring(0,4)]=2,T.splice(A,1)):zt(I,"video",x)&&(v.videoCodec=R=R?`${R},${I}`:I,Bt.video[R.substring(0,4)]=2,T.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=et.parseMasterPlaylistMedia(n,o,c);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ue({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,h=Ii(e,s),u=G(c)?c:G(o)?o:0,d=Xn(s),g=et.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===J.MANIFEST){const f={attrs:new ue({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=t.loading.start+Ba(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===J.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===J.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===J.AUDIO_TRACK||e.type===J.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=D.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case J.MANIFEST:c=s?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,l=!0;break;case J.LEVEL:c=s?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,l=!1;break;case J.AUDIO_TRACK:c=s?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case J.SUBTITLE_TRACK:c=s?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:Y.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=t?.url||e.url;u.response=ie({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:g}=i,f=Ii(t,i),p=Xn(i);let y=typeof i.level=="number"&&p===V.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case J.MANIFEST:case J.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const v=o.levels.indexOf(h);v>-1&&(y=v)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:g,withoutMultiVariant:c===J.MANIFEST});break;case J.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break;case J.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break}}}class be{static get version(){return Jt}static isMSESupported(){return Bo()}static isSupported(){return Mf()}static getMediaSource(){return Et()}static get Events(){return m}static get MetadataSchema(){return Ue}static get ErrorTypes(){return Y}static get ErrorDetails(){return D}static get DefaultConfig(){return be.defaultConfig?be.defaultConfig:If}static set DefaultConfig(e){be.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 or,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=Wl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Rf(be.DefaultConfig,e,t);this.userConfig=e,s.progressive&&bf(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new Gc(this),d=s.interstitialsController,g=d?this.interstitialsController=new d(this,be):null,f=this.bufferController=new r(this,u),p=this.capLevelController=new n(this),y=new c(this),E=new Gf(this),v=s.contentSteeringController,T=v?new v(this):null,x=this.levelController=new Ff(this,T),S=new wf(this),R=new $f(this.config,this.logger),A=this.streamController=new Uf(this,u,R),I=this.gapController=new Pf(this,u);p.setStreamController(A),y.setStreamController(A);const b=[E,x,A];g&&b.splice(1,0,g),T&&b.splice(1,0,T),this.networkControllers=b;const L=[h,f,I,p,y,S,u];this.audioTrackController=this.createController(s.audioTrackController,b);const C=s.audioStreamController;C&&b.push(this.audioStreamController=new C(this,u,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const w=s.subtitleStreamController;w&&b.push(this.subtititleStreamController=new w(this,u,R)),this.createController(s.timelineController,L),R.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(Of,L),this.coreComponents=L,b.push(l);const U=l.onErrorOut;typeof U=="function"&&this.on(m.ERROR,U,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),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:Y.OTHER_ERROR,details:D.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,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}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,s=this._url,i=this._url=zi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||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?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[V.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[V.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[V.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=Cd()),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){Lc(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}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 s=Aa(t);return Sa(e,s,navigator.mediaCapabilities)}}be.defaultConfig=void 0;function pt(a,e=0){let t=0;const s=a+String(e);for(let i=0;i<s.length;i++){const r=s.charCodeAt(i);t=(t<<5)-t+r|0}return(t%65536+65536)%65536/65536}function Kf(a){const e=pt(a,0),t=pt(a,1),s=pt(a,2);return{rotation:(e-.5)*4,translateX:(t-.5)*12,translateY:(s-.5)*8}}var Vf=Fe('<div class="wavy-container svelte-7frlgw"><svg class="wavy-svg svelte-7frlgw" viewBox="0 0 100 100" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg"><defs><filter x="-5%" y="-5%" width="110%" height="110%"><feTurbulence type="turbulence" baseFrequency="0.03" numOctaves="4" result="turb"></feTurbulence><feDisplacementMap in="SourceGraphic" in2="turb" scale="3" xChannelSelector="R" yChannelSelector="G"></feDisplacementMap></filter></defs><path stroke-linejoin="round"></path></svg> <div class="wavy-content svelte-7frlgw"><!></div></div>');function ji(a,e){Vs(e,!0);let t=as(e,"fill",3,"#39FF44"),s=as(e,"strokeColor",3,"#0A182B"),i=as(e,"strokeWidth",3,3),r=as(e,"padding",3,16);const n=l(e.seed),o=`turb-${e.seed.replace(/[^a-zA-Z0-9]/g,"").slice(0,12)}`,c=Math.floor(pt(e.seed,99)*999);function l(v){const R=[];for(let I=0;I<=10;I++){const b=I/10,L=pt(v,I);R.push([6+b*88,6+(L-.5)*5*2])}for(let I=1;I<=10;I++){const b=I/10,L=pt(v,10+I+50);R.push([94+(L-.5)*5*2,6+b*88])}for(let I=1;I<=10;I++){const b=I/10,L=pt(v,20+I+100);R.push([94-b*88,94+(L-.5)*5*2])}for(let I=1;I<10;I++){const b=I/10,L=pt(v,30+I+150);R.push([6+(L-.5)*5*2,94-b*88])}if(R.length<3)return"";let A=`M ${R[0][0]} ${R[0][1]}`;for(let I=0;I<R.length;I++){const b=R[(I-1+R.length)%R.length],L=R[I],C=R[(I+1)%R.length],w=R[(I+2)%R.length],U=.35,F=L[0]+(C[0]-b[0])*U,N=L[1]+(C[1]-b[1])*U,k=C[0]-(w[0]-L[0])*U,$=C[1]-(w[1]-L[1])*U;A+=` C ${F.toFixed(1)} ${N.toFixed(1)}, ${k.toFixed(1)} ${$.toFixed(1)}, ${C[0].toFixed(1)} ${C[1].toFixed(1)}`}return A+=" Z",A}var h=Vf(),u=he(h),d=he(u),g=he(d),f=he(g);Jn(),oe(g),oe(d);var p=ye(d);oe(u);var y=ye(u,2),E=he(y);vl(E,()=>e.children),oe(y),oe(h),Ze(()=>{_i(h,`--padding: ${r()??""}px;`),at(g,"id",o),at(f,"seed",c),at(p,"d",n),at(p,"fill",t()),at(p,"stroke",s()),at(p,"stroke-width",i()),at(p,"filter",`url(#${o})`)}),we(a,h),Hs()}var Hf=Fe('<div class="error-overlay svelte-zbxgh1"> </div>'),Yf=Fe('<div class="player-wrapper svelte-zbxgh1"><video controls="" playsinline="" class="svelte-zbxgh1"><track kind="captions"/></video> <!></div>',2);function Wf(a,e){Vs(e,!0);let t=xe(void 0),s=null,i=xe("");function r(){s&&(s.destroy(),s=null)}function n(){!H(t)||!e.src||(r(),se(i,""),be.isSupported()?(s=new be({enableWorker:!0,lowLatencyMode:!1}),s.loadSource(e.src),s.attachMedia(H(t)),s.on(be.Events.MANIFEST_PARSED,()=>{H(t)?.play().catch(()=>{})}),s.on(be.Events.ERROR,(o,c)=>{if(console.error("HLS error:",c),c.fatal)switch(c.type){case be.ErrorTypes.NETWORK_ERROR:se(i,`Network error loading video: ${c.details}`),s?.startLoad();break;case be.ErrorTypes.MEDIA_ERROR:se(i,`Media error: ${c.details}`),s?.recoverMediaError();break;default:se(i,`Fatal error: ${c.details}`),r();break}})):H(t).canPlayType("application/vnd.apple.mpegurl")?(H(t).src=e.src,H(t).addEventListener("loadedmetadata",()=>{H(t)?.play().catch(()=>{})})):se(i,"HLS playback is not supported in this browser."))}gl(()=>(e.src,H(t)&&n(),r)),ji(a,{seed:"player-main",children:(o,c)=>{var l=Yf(),h=he(l);Ri(h,g=>se(t,g),()=>H(t));var u=ye(h,2);{var d=g=>{var f=Hf(),p=he(f,!0);oe(f),Ze(()=>qe(p,H(i))),we(g,f)};It(u,g=>{H(i)&&g(d)})}oe(l),we(o,l)},$$slots:{default:!0}}),Hs()}var qf=Fe("<img/>"),jf=Fe('<div class="loading-spinner svelte-1nxalmg"><div class="spinner svelte-1nxalmg"></div></div>'),Xf=Fe('<div class="scrub-bar svelte-1nxalmg"><div class="scrub-bar-fill svelte-1nxalmg"></div></div>'),zf=Fe('<div class="thumbnail svelte-1nxalmg" role="img"><!> <canvas></canvas> <!> <!> <div class="thumb-shadow svelte-1nxalmg"></div></div>'),Qf=Fe('<span class="duration-badge svelte-1nxalmg"> </span> <div class="thumb-wrapper svelte-1nxalmg"><!></div> <div class="info svelte-1nxalmg"><h3 class="title svelte-1nxalmg"> </h3> <p class="creator svelte-1nxalmg"> </p> <p class="date svelte-1nxalmg"> </p></div>',1),Zf=Fe('<button class="card svelte-1nxalmg"><!></button>');function Jf(a,e){Vs(e,!0);let t=xe(ea(e.video.value.creator)),s=xe(null);const i=e.video.uri.split("/").pop()||e.video.uri,r=Kf(e.video.value.creator),n=`transform: rotate(${r.rotation}deg) translate(${r.translateX}px, ${r.translateY}px);`;let o=xe(void 0),c=xe(void 0),l=xe(!1),h=xe(0),u=xe(!1),d=xe(!1),g=xe(!1),f=null,p=null,y=0,E=!1,v=null;zn(()=>{aa(e.video.value.creator).then(F=>se(t,F,!0)),Nl(e.video).then(F=>se(s,F,!0))}),$o(x);function T(){if(f)return;se(d,!0),f=document.createElement("video"),f.muted=!0,f.playsInline=!0,f.preload="auto",f.style.cssText="position:fixed;top:-9999px;left:-9999px;width:320px;height:180px;pointer-events:none;",document.body.appendChild(f),f.addEventListener("seeked",S);const F=ia(e.video.uri);be.isSupported()?(p=new be({enableWorker:!1,lowLatencyMode:!1,startLevel:0}),p.loadSource(F),p.attachMedia(f),p.on(be.Events.LEVEL_LOADED,(N,k)=>{y=k.details.totalduration,se(u,!0),A(H(h))}),p.on(be.Events.ERROR,(N,k)=>{k.fatal&&se(d,!1)})):f.canPlayType("application/vnd.apple.mpegurl")&&(f.src=F,f.addEventListener("loadedmetadata",()=>{f&&(y=f.duration,se(u,!0),A(H(h)))}))}function x(){p&&(p.destroy(),p=null),f&&(f.removeEventListener("seeked",S),f.remove(),f=null),se(u,!1),se(d,!1),se(g,!1),E=!1,v=null,y=0}function S(){if(E=!1,se(d,!1),I(),v!==null){const F=v;v=null,R(F)}}function R(F){!f||!H(u)||(E=!0,f.currentTime=F)}function A(F){if(!H(u)||!y)return;const N=F*y;E?v=N:R(N)}function I(){if(!f||!H(c))return;const F=f.videoWidth,N=f.videoHeight;if(!F||!N)return;const k=H(c).getBoundingClientRect(),$=window.devicePixelRatio||1;H(c).width=k.width*$,H(c).height=k.height*$;const B=H(c).getContext("2d");B&&(B.drawImage(f,0,0,H(c).width,H(c).height),se(g,!0))}function b(){se(l,!0),T()}function L(F){if(!H(o))return;const N=H(o).getBoundingClientRect();se(h,Math.max(0,Math.min(1,(F.clientX-N.left)/N.width)),!0),A(H(h))}function C(){se(l,!1)}var w=Zf(),U=he(w);ji(U,{get seed(){return i},fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:3.5,padding:20,children:(F,N)=>{var k=Qf(),$=ml(k),B=he($,!0);oe($);var K=ye($,2),W=he(K);{let ge=ta(()=>i+"-thumb");ji(W,{get seed(){return H(ge)},fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:2,padding:0,children:(_e,He)=>{var De=zf(),is=he(De);{var $t=ae=>{var Ae=qf();let Ge;Ze(()=>{at(Ae,"src",H(s)),at(Ae,"alt",e.video.value.title),Ge=Dr(Ae,1,"thumb-img svelte-1nxalmg",null,Ge,{hidden:H(l)&&H(g)})}),we(ae,Ae)};It(is,ae=>{H(s)&&ae($t)})}var Tt=ye(is,2);let js;Ri(Tt,ae=>se(c,ae),()=>H(c));var ee=ye(Tt,2);{var Te=ae=>{var Ae=jf();we(ae,Ae)};It(ee,ae=>{H(l)&&H(d)&&!H(g)&&ae(Te)})}var Pe=ye(ee,2);{var it=ae=>{var Ae=Xf(),Ge=he(Ae);oe(Ae),Ze(()=>_i(Ge,`width: ${H(h)*100}%`)),we(ae,Ae)};It(Pe,ae=>{H(l)&&H(u)&&ae(it)})}Jn(2),oe(De),Ri(De,ae=>se(o,ae),()=>H(o)),Ze(()=>js=Dr(Tt,1,"scrub-canvas svelte-1nxalmg",null,js,{visible:H(l)&&H(g)})),_r("mouseenter",De,b),Ps("mousemove",De,L),_r("mouseleave",De,C),we(_e,De)},$$slots:{default:!0}})}oe(K);var M=ye(K,2),O=he(M),X=he(O,!0);oe(O);var te=ye(O,2),z=he(te,!0);oe(te);var Z=ye(te,2),ve=he(Z,!0);oe(Z),oe(M),Ze((ge,_e)=>{qe(B,ge),qe(X,e.video.value.title),qe(z,H(t)),qe(ve,_e)},[()=>ra(e.video.value.duration),()=>na(e.video.value.createdAt)]),we(F,k)},$$slots:{default:!0}}),oe(w),Ze(()=>_i(w,n)),Ps("click",w,()=>e.onSelect(e.video)),we(a,w),Hs()}sa(["click","mousemove"]);var eg=Fe('<header class="frog-header svelte-1kxia9k"><div class="title-row svelte-1kxia9k"><h1 class="logo-text svelte-1kxia9k">vod frog</h1> <img src="/frogcursor.png" alt="A cute frog" class="header-frog svelte-1kxia9k"/></div> <div class="subtitle-lines svelte-1kxia9k"><p class="subtitle svelte-1kxia9k">an exploration by</p> <p class="subtitle svelte-1kxia9k">@goose.art using @stream.place</p></div></header>');function tg(a){var e=eg();we(a,e)}var sg=Fe('<section class="player-section svelte-1uha8ag"><!> <div class="player-info svelte-1uha8ag"><div class="player-info-left"><h2 class="player-title svelte-1uha8ag"> </h2> <p class="player-meta svelte-1uha8ag"><span class="creator-tag svelte-1uha8ag"> </span> <span class="dot svelte-1uha8ag">·</span> <span class="dot svelte-1uha8ag">·</span> </p></div> <button class="close-btn svelte-1uha8ag" title="Close player">✕</button></div></section>'),ig=Fe('<div class="error svelte-1uha8ag"> </div>'),rg=Fe('<div class="load-more svelte-1uha8ag"><button class="svelte-1uha8ag"> </button></div>'),ng=Fe('<div class="app svelte-1uha8ag"><!> <!> <!> <section class="grid svelte-1uha8ag"></section> <!></div>');function pg(a,e){Vs(e,!0);let t=xe(ea([])),s=xe(void 0),i=xe(!1),r=xe(!0),n=xe(null),o=xe(""),c=xe("");async function l(){if(!(H(i)||!H(r))){se(i,!0),se(c,"");try{const S=await Ol(H(s),24);se(t,[...H(t),...S.records],!0),se(s,S.cursor,!0),se(r,!!S.cursor&&S.records.length>0,!0)}catch(S){se(c,S.message,!0)}se(i,!1)}}function h(S){se(n,S,!0),aa(S.value.creator).then(R=>se(o,R,!0)),window.scrollTo({top:0,behavior:"smooth"})}function u(){se(n,null)}zn(l);var d=ng();Tl("1uha8ag",S=>{pl(()=>{yl.title="vod frog 🐸"})});var g=he(d);tg(g);var f=ye(g,2);{var p=S=>{var R=sg(),A=he(R);{let B=ta(()=>ia(H(n).uri));Wf(A,{get src(){return H(B)}})}var I=ye(A,2),b=he(I),L=he(b),C=he(L,!0);oe(L);var w=ye(L,2),U=he(w),F=he(U,!0);oe(U);var N=ye(U,3),k=ye(N,2);oe(w),oe(b);var $=ye(b,2);oe(I),oe(R),Ze((B,K)=>{qe(C,H(n).value.title),qe(F,H(o)||H(n).value.creator),qe(N,` ${B??""} `),qe(k,` ${K??""}`)},[()=>na(H(n).value.createdAt),()=>ra(H(n).value.duration)]),Ps("click",$,u),we(S,R)};It(f,S=>{H(n)&&S(p)})}var y=ye(f,2);{var E=S=>{var R=ig(),A=he(R,!0);oe(R),Ze(()=>qe(A,H(c))),we(S,R)};It(y,S=>{H(c)&&S(E)})}var v=ye(y,2);xl(v,21,()=>H(t),S=>S.uri,(S,R)=>{Jf(S,{get video(){return H(R)},onSelect:h})}),oe(v);var T=ye(v,2);{var x=S=>{var R=rg(),A=he(R),I=he(A,!0);oe(A),oe(R),Ze(()=>{A.disabled=H(i),qe(I,H(i)?"loading...":"load more 🐸")}),Ps("click",A,l),we(S,R)};It(T,S=>{H(r)&&S(x)})}oe(d),we(a,d),Hs()}sa(["click"]);export{pg as component};
+40
build/_app/immutable/nodes/2.DCJPxWEg.js
··· 1 + import{a as ke,f as Oe}from"../chunks/DGbOEUpF.js";import{o as zn,a as Mo}from"../chunks/DxGD2b0U.js";import{g as Js,l as No,j as vt,t as ei,v as Bo,F as Uo,A as F,G as $o,aq as Go,I as br,q as ti,k as hs,C as Ko,aL as Vo,az as _r,i as Ho,aP as gt,h as _i,aQ as Yo,s as Wo,V as qo,aR as jo,aK as Qi,aS as Xo,aT as zo,z as Qo,am as Dr,aU as Zo,N as Jo,d as Qn,p as Zn,aV as si,aW as el,aI as tl,m as sl,f as il,o as rl,a1 as Zi,Z as ii,B as q,a5 as de,a7 as ve,a6 as ue,a3 as Ge,a4 as Ji,ab as ie,L as Di,a2 as Jn,aa as nl,ac as ea,a as al,aX as ol,a9 as ll,aY as Cr}from"../chunks/CkzjbUDB.js";import{d as er,a as ft,e as xt,s as Xe}from"../chunks/BsDbD4Ku.js";import{i as mt}from"../chunks/XE2G8ySY.js";import{h as cl}from"../chunks/DmyE0d-6.js";import{t as hl,W as Fs,s as dt,a as Rs,b as ul,r as Ci,c as dl,f as ta,d as sa,e as ia,F as fl,l as gl}from"../chunks/D_t83wNY.js";import{b as Ms}from"../chunks/Dr80VTgO.js";function ml(a,e,t){for(var s=[],i=e.length,r,n=e.length,o=0;o<i;o++){let u=e[o];Zn(u,()=>{if(r){if(r.pending.delete(u),r.done.add(u),r.pending.size===0){var d=a.outrogroups;Pi(a,Qi(r.done)),d.delete(r),d.size===0&&(a.outrogroups=null)}}else n-=1},!1)}if(n===0){var c=s.length===0&&t!==null;if(c){var l=t,h=l.parentNode;tl(h),h.append(l),a.items.clear()}Pi(a,e,!c)}else r={pending:new Set(e),done:new Set},(a.outrogroups??=new Set).add(r)}function Pi(a,e,t=!0){var s;if(a.pending.size>0){s=new Set;for(const n of a.pending.values())for(const o of n)s.add(a.items.get(o).e)}for(var i=0;i<e.length;i++){var r=e[i];if(s?.has(r)){r.f|=gt;const n=document.createDocumentFragment();sl(r,n)}else il(e[i],t)}}var Pr;function pl(a,e,t,s,i,r=null){var n=a,o=new Map;{var c=a;n=vt?ei(Bo(c)):c.appendChild(Js())}vt&&Uo();var l=null,h=qo(()=>{var v=t();return jo(v)?v:v==null?[]:Qi(v)}),u,d=new Map,g=!0;function f(v){(E.effect.f&Jo)===0&&(E.pending.delete(v),E.fallback=l,yl(E,u,n,e,s),l!==null&&(u.length===0?(l.f&gt)===0?Qn(l):(l.f^=gt,zt(l,null,n)):Zn(l,()=>{l=null})))}function p(v){E.pending.delete(v)}var y=No(()=>{u=F(h);var v=u.length;let T=!1;if(vt){var S=$o(n)===Go;S!==(v===0)&&(n=br(),ei(n),ti(!1),T=!0)}for(var x=new Set,D=Ho,A=Wo(),L=0;L<v;L+=1){vt&&hs.nodeType===Ko&&hs.data===Vo&&(n=hs,T=!0,ti(!1));var R=u[L],I=s(R,L),C=g?null:o.get(I);C?(C.v&&_r(C.v,R),C.i&&_r(C.i,L),A&&D.unskip_effect(C.e)):(C=El(o,g?n:Pr??=Js(),R,I,L,i,e,t),g||(C.e.f|=gt),o.set(I,C)),x.add(I)}if(v===0&&r&&!l&&(g?l=_i(()=>r(n)):(l=_i(()=>r(Pr??=Js())),l.f|=gt)),v>x.size&&Yo(),vt&&v>0&&ei(br()),!g)if(d.set(D,x),A){for(const[$,K]of o)x.has($)||D.skip_effect(K.e);D.oncommit(f),D.ondiscard(p)}else f(D);T&&ti(!0),F(h)}),E={effect:y,items:o,pending:d,outrogroups:null,fallback:l};g=!1,vt&&(n=hs)}function jt(a){for(;a!==null&&(a.f&el)===0;)a=a.next;return a}function yl(a,e,t,s,i){var r=e.length,n=a.items,o=jt(a.effect.first),c,l=null,h=[],u=[],d,g,f,p;for(p=0;p<r;p+=1){if(d=e[p],g=i(d,p),f=n.get(g).e,a.outrogroups!==null)for(const L of a.outrogroups)L.pending.delete(f),L.done.delete(f);if((f.f&si)!==0&&Qn(f),(f.f&gt)!==0)if(f.f^=gt,f===o)zt(f,null,t);else{var y=l?l.next:o;f===a.effect.last&&(a.effect.last=f.prev),f.prev&&(f.prev.next=f.next),f.next&&(f.next.prev=f.prev),pt(a,l,f),pt(a,f,y),zt(f,y,t),l=f,h=[],u=[],o=jt(l.next);continue}if(f!==o){if(c!==void 0&&c.has(f)){if(h.length<u.length){var E=u[0],v;l=E.prev;var T=h[0],S=h[h.length-1];for(v=0;v<h.length;v+=1)zt(h[v],E,t);for(v=0;v<u.length;v+=1)c.delete(u[v]);pt(a,T.prev,S.next),pt(a,l,T),pt(a,S,E),o=E,l=S,p-=1,h=[],u=[]}else c.delete(f),zt(f,o,t),pt(a,f.prev,f.next),pt(a,f,l===null?a.effect.first:l.next),pt(a,l,f),l=f;continue}for(h=[],u=[];o!==null&&o!==f;)(c??=new Set).add(o),u.push(o),o=jt(o.next);if(o===null)continue}(f.f&gt)===0&&h.push(f),l=f,o=jt(f.next)}if(a.outrogroups!==null){for(const L of a.outrogroups)L.pending.size===0&&(Pi(a,Qi(L.done)),a.outrogroups?.delete(L));a.outrogroups.size===0&&(a.outrogroups=null)}if(o!==null||c!==void 0){var x=[];if(c!==void 0)for(f of c)(f.f&si)===0&&x.push(f);for(;o!==null;)(o.f&si)===0&&o!==a.fallback&&x.push(o),o=jt(o.next);var D=x.length;if(D>0){var A=r===0?t:null;ml(a,x,A)}}}function El(a,e,t,s,i,r,n,o){var c=(n&Xo)!==0?(n&zo)===0?Qo(t,!1,!1):Dr(t):null,l=(n&Zo)!==0?Dr(i):null;return{v:c,i:l,e:_i(()=>(r(e,c??t,l??i,o),()=>{a.delete(s)}))}}function zt(a,e,t){if(a.nodes)for(var s=a.nodes.start,i=a.nodes.end,r=e&&(e.f&gt)===0?e.nodes.start:t;s!==null;){var n=rl(s);if(r.before(s),s===i)return;s=n}}function pt(a,e,t){e===null?a.effect.first=t:e.next=t,t===null?a.effect.last=e:t.prev=e}function Zt(a,e,t,s,i,r){var n=a.__className;if(vt||n!==t||n===void 0){var o=hl(t,s,r);(!vt||o!==a.getAttribute("class"))&&(o==null?a.removeAttribute("class"):a.className=o),a.__className=t}else if(r&&i!==r)for(var c in r){var l=!!r[c];(i==null||l!==!!i[c])&&a.classList.toggle(c,l)}return r}const V=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},vl=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Tl},Tl=Number.MAX_SAFE_INTEGER||9007199254740991;let W=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),_=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a})({}),m=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a})({});var te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Y={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ot{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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 Sl{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ot(e),this.fast_=new Ot(t),this.defaultTTFB_=i,this.ttfb_=new Ot(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ot(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ot(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ot(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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 xl(a,e,t){return(e=Il(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ae(){return ae=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ae.apply(null,arguments)}function kr(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function re(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?kr(Object(t),!0).forEach(function(s){xl(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):kr(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Al(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Il(a){var e=Al(a,"string");return typeof e=="symbol"?e:e+""}class Ye{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Tt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Tt=function(){},Ll={trace:Tt,debug:Tt,log:Tt,warn:Tt,info:Tt,error:Tt};function ki(){return ae({},Ll)}function Rl(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):Tt}function wr(a,e,t){return e[a]?e[a].bind(e):Rl(a,t)}const wi=ki();function bl(a,e,t){const s=ki();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=wr(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return ki()}i.forEach(r=>{wi[r]=wr(r,a)})}else ae(wi,s);return s}const ne=wi;function It(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _l(a){return typeof self<"u"&&a===self.ManagedMediaSource}function ra(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function Ve(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function be(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function na(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Dl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ri={exports:{}},Or;function Cl(){return Or||(Or=1,(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var y=g.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()})(ri)),ri.exports}var tr=Cl();class sr{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class aa{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,kl(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[le.AUDIO]:null,[le.VIDEO]:null,[le.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new sr),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=tr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}}function Te(a){return a.sn!=="initSegment"}class ni extends aa{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(V(e)&&V(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=V(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[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(!V(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Te(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 s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class Pl extends aa{constructor(e,t,s,i,r){super(s),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=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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 oa(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||oa(t,e)}}function kl(a,e){const t=oa(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Fr=Math.pow(2,32)-1,wl=[].push,la={video:1,audio:2,id3:3,text:4};function Ae(a){return String.fromCharCode.apply(null,a)}function ca(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function z(a,e){const t=ha(a,e);return t<0?4294967296+t:t}function Mr(a,e){let t=z(a,e);return t*=Math.pow(2,32),t+=z(a,e+4),t}function ha(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Ol(a){const e=a.byteLength;for(let t=0;t<e;){const s=z(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function ee(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=z(a,i),n=Ae(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=ee(a.subarray(i+8,o),e.slice(1));c.length&&wl.apply(t,c)}i=o}return t}function Fl(a){const e=[],t=a[0];let s=8;const i=z(a,s);s+=4;let r=0,n=0;t===0?(r=z(a,s),n=z(a,s+4),s+=8):(r=Mr(a,s),n=Mr(a,s+8),s+=16),s+=2;let o=a.length+n;const c=ca(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=z(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return ne.warn("SIDX has hierarchical references (not supported)"),null;const f=z(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function ua(a){const e=[],t=ee(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=ee(r,["tkhd"])[0];if(n){let o=n[0];const c=z(n,o===0?12:20),l=ee(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=z(l,o===0?12:20),u=ee(r,["mdia","hdlr"])[0];if(u){const d=Ae(u.subarray(8,12)),g={soun:le.AUDIO,vide:le.VIDEO}[d],f=ee(r,["mdia","minf","stbl","stsd"])[0],p=Ml(f);g?(e[c]={timescale:h,type:g,stsd:p},e[g]=re({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return ee(a,["moov","mvex","trex"]).forEach(i=>{const r=z(i,4),n=e[r];n&&(n.default={duration:z(i,12),flags:z(i,20)})}),e}function Ml(a){const e=a.subarray(8),t=e.subarray(86),s=Ae(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=ee(e,[s])[0].subarray(s==="enca"?28:78);ee(l,["sinf"]).forEach(u=>{const d=ee(u,["schm"])[0];if(d){const g=Ae(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=ee(u,["frma"])[0];f&&(i=Ae(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=ee(t,["avcC"])[0];c&&c.length>3&&(i+="."+ds(c[1])+ds(c[2])+ds(c[3]),r=us(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=ee(e,[s])[0],l=ee(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=ai(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=ai(l,h);const d=l[h++];if(d===64)i+="."+ds(d);else break;if(h+=12,l[h++]!==5)break;h=ai(l,h);const g=l[h++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[h]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=ee(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=z(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+Nl(d).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let E=p.length;E--;){const v=p[E];(v||y)&&(y="."+v.toString(16).toUpperCase()+y)}i+=y}r=us(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=us(i,t)||i;break}case"vp09":{const c=ee(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Je(l)+"."+Je(h)+"."+Je(u)}break}case"av01":{const c=ee(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&d?g?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,v=c[2]&3;i+="."+l+"."+Je(h)+u+"."+Je(f)+"."+p+"."+y+E+v+"."+Je(1)+"."+Je(1)+"."+Je(1)+"."+0,r=us("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function us(a,e){const t=ee(e,["dvvC"]),s=t.length?t[0]:ee(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Je(i)+"."+Je(r)}}function Nl(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function ai(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function ds(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Je(a){return(a<10?"0":"")+a}function Bl(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&da(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(ne.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${be(r)} -> ${be(t)}`),s.set(t,8))})}function Ul(a){const e=[];return da(a,t=>e.push(t.subarray(8,24))),e}function da(a,e){ee(a,["moov","trak"]).forEach(s=>{const i=ee(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=ee(r,["enca"]);const o=n.length>0;o||(n=ee(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);ee(l,["sinf"]).forEach(u=>{const d=fa(u);d&&e(d,o)})})})}function fa(a){const e=ee(a,["schm"])[0];if(e){const t=Ae(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=ee(a,["schi","tenc"])[0];if(s)return s}}}function $l(a,e,t){const s={},i=ee(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=ee(n,["tfhd"])[0],c=z(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=ee(n,["tfdt"])[0];if(u){const T=u[0];let S=z(u,4);T===1&&(S===Fr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Fr+1,S+=z(u,8))),V(S)&&(!V(h.start)||S<h.start)&&(h.start=S)}const d=l.default,g=z(o,0)|d?.flags;let f=d?.duration||0;g&8&&(g&2?f=z(o,12):f=z(o,8));const p=ee(n,["trun"]);let y=h.start||0,E=0,v=f;for(let T=0;T<p.length;T++){const S=p[T],x=z(S,4),D=h.sampleCount;h.sampleCount+=x;const A=S[3]&1,L=S[3]&4,R=S[2]&1,I=S[2]&2,C=S[2]&4,$=S[2]&8;let K=8,H=x;for(A&&(K+=4),L&&x&&(!(S[K+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),K+=4,R?(v=z(S,K),K+=4):v=f,I&&(K+=4),$&&(K+=4),y+=v,E+=v,H--);H--;)R?(v=z(S,K),K+=4):v=f,I&&(K+=4),C&&(S[K+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(H+1),h.keyFrameStart=y),K+=4),$&&(K+=4),y+=v,E+=v;!E&&f&&(E+=f*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=ee(a,["sidx"]);for(let c=0;c<o.length;c++){const l=Fl(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&V(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function Gl(a){const e={valid:null,remainder:null},t=ee(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function He(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Nr(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return ee(s,["moof"]).map(c=>{const l=c.byteOffset-8;ee(c,["traf"]).map(u=>{const d=ee(u,["tfdt"]).map(g=>{const f=g[0];let p=z(g,4);return f===1&&(p*=Math.pow(2,32),p+=z(g,8)),p/i})[0];return d!==void 0&&(a=d),ee(u,["tfhd"]).map(g=>{const f=z(g,4),p=z(g,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,v=(p&8)!==0;let T=0;const S=(p&16)!==0;let x=0;const D=(p&32)!==0;let A=8;f===r&&(y&&(A+=8),E&&(A+=4),v&&(T=z(g,A),A+=4),S&&(x=z(g,A),A+=4),D&&(A+=4),e.type==="video"&&(n=js(e.codec)),ee(u,["trun"]).map(L=>{const R=L[0],I=z(L,0)&16777215,C=(I&1)!==0;let $=0;const K=(I&4)!==0,H=(I&256)!==0;let O=0;const w=(I&512)!==0;let k=0;const M=(I&1024)!==0,N=(I&2048)!==0;let G=0;const B=z(L,4);let U=8;C&&($=z(L,U),U+=4),K&&(U+=4);let j=$+l;for(let J=0;J<B;J++){if(H?(O=z(L,U),U+=4):O=T,w?(k=z(L,U),U+=4):k=x,M&&(U+=4),N&&(R===0?G=z(L,U):G=ha(L,U),U+=4),e.type===le.VIDEO){let X=0;for(;X<k;){const Z=z(s,j);if(j+=4,Kl(n,s[j])){const oe=s.subarray(j,j+Z);ir(oe,n?2:1,a+G/i,t)}j+=Z,X+=Z+4}}a+=O/i}}))})})}),t}function js(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Kl(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ir(a,e,t,s){const i=ga(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){ne.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=ca(i,h);if(h+=2,d===49){const g=z(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const p=i[h++],y=31&p,E=64&p,v=E?2+y*3:0,T=new Uint8Array(v);if(E){T[0]=p;for(let S=1;S<v;S++)T[S]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:T})}}}}}else if(n===5&&o>16){const u=[];for(let f=0;f<16;f++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:Ve(g),userDataBytes:g})}}}function ga(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function Vl(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;Ae(a.subarray(l,l+1))!=="\0";)t+=Ae(a.subarray(l,l+1)),l+=1;for(t+=Ae(a.subarray(l,l+1)),l+=1;Ae(a.subarray(l,l+1))!=="\0";)s+=Ae(a.subarray(l,l+1)),l+=1;s+=Ae(a.subarray(l,l+1)),l+=1,i=z(a,12),r=z(a,16),o=z(a,20),c=z(a,24),l=28}else if(e===1){l+=4,i=z(a,l),l+=4;const u=z(a,l);l+=4;const d=z(a,l);for(l+=4,n=2**32*u+d,vl(n)||(n=Number.MAX_SAFE_INTEGER,ne.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=z(a,l),l+=4,c=z(a,l),l+=4;Ae(a.subarray(l,l+1))!=="\0";)t+=Ae(a.subarray(l,l+1)),l+=1;for(t+=Ae(a.subarray(l,l+1)),l+=1;Ae(a.subarray(l,l+1))!=="\0";)s+=Ae(a.subarray(l,l+1)),l+=1;s+=Ae(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function Hl(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function Yl(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),Hl([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function Wl(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=ql(i);e.push(r),s+=r.size}}return e}function ql(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=be(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let g=0;g<d;g++)c.push(new Uint8Array(n,t+32+g*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const ma=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Yt={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 rr(a,e){const t=Yt[e];return!!t&&!!t[a.slice(0,4)]}function ss(a,e,t=!0){return!a.split(",").some(s=>!nr(s,e,t))}function nr(a,e,t=!0){var s;const i=It(t);return(s=i?.isTypeSupported(is(a,e)))!=null?s:!1}function is(a,e){return`${e}/mp4;codecs=${a}`}function Br(a){if(a){const e=a.substring(0,4);return Yt.video[e]}return 2}function Ns(a){const e=ma();return a.split(",").reduce((t,s)=>{const r=e&&js(s)?9:Yt.video[s];return r?(r*2+t)/(t?3:2):(Yt.audio[s]+t)/(t?2:1)},0)}const oi={};function jl(a,e=!0){if(oi[a])return oi[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(nr(t[i],"audio",e))return oi[a]=t[i],t[i];if(t[i]==="mp3"&&(s=It(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const Xl=/flac|opus|mp4a\.40\.34/i;function Bs(a,e=!0){return a.replace(Xl,t=>jl(t.toLowerCase(),e))}function zl(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)rr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function bs(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Ur(a,"audio")||Ur(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function Ur(a,e){return rr(a,e)&&nr(a,e)}function Ql(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Zl(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function $r(a){const e=It(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Oi(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Jl={supported:!0,powerEfficient:!0,smooth:!0},ec={supported:!1,smooth:!1,powerEfficient:!1},pa={supported:!0,configurations:[],decodingInfoResults:[Jl]};function ya(a,e){return{supported:!1,configurations:e,decodingInfoResults:[ec],error:a}}function tc(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>js(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&V(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Ea(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(pa);const r=[],n=sc(a),o=n.length,c=ic(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>js(u))&&ma())return Promise.resolve(ya(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=nc(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function sc(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=va(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:is(Zl(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function ic(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=va(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(g=>{const f={contentType:is(g,"audio"),bitrate:t?rc(g,r):r};d&&(f.channels=""+d),h.push(f)})}return h},n):n},[]):[]}function rc(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function va(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function nc(a){let e="";const{audio:t,video:s}=a;if(s){const i=Oi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Oi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Fi=["NONE","TYPE-0","TYPE-1",null];function ac(a){return Fi.indexOf(a)>-1}const Us=["SDR","PQ","HLG"];function oc(a){return!!a&&Us.indexOf(a)>-1}var _s={No:"",Yes:"YES",v2:"v2"};function Gr(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?_s.v2:_s.Yes:_s.No}class Kr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class rs{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Vr(this._audioGroups,e)}hasSubtitleGroup(e){return Vr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Vr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function lc(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function cc(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||Us.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&lc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const hc=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ce=(a,e)=>JSON.stringify(a,hc(e));function uc(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,g=1/0,f=1/0,p=1/0,y=0,E=[];const{preferHDR:v,allowedVideoRanges:T}=cc(e,i);for(let L=r.length;L--;){const R=a[r[L]];h||(h=R.channels[2]>0),d=Math.min(d,R.minHeight),g=Math.min(g,R.minFramerate),f=Math.min(f,R.minBitrate),T.filter(C=>R.videoRanges[C]>0).length>0&&(u=!0)}d=V(d)?d:0,g=V(g)?g:0;const S=Math.max(1080,d),x=Math.max(30,g);f=V(f)?f:t,t=Math.max(f,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((L,R)=>{const I=a[R];if(R===L)return L;if(E=u?T.filter(C=>I.videoRanges[C]>0):[],D){if(I.minBitrate>t)return Qe(R,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),L;if(!I.hasDefaultAudio)return Qe(R,"no renditions with default or auto-select sound found"),L;if(o&&R.indexOf(o.substring(0,4))%5!==0)return Qe(R,`audio codec preference "${o}" not found`),L;if(n&&!l){if(!I.channels[n])return Qe(R,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),L}else if((!o||l)&&h&&I.channels[2]===0)return Qe(R,"no renditions with stereo sound found"),L;if(I.minHeight>S)return Qe(R,`min resolution of ${I.minHeight} > maximum of ${S}`),L;if(I.minFramerate>x)return Qe(R,`min framerate of ${I.minFramerate} > maximum of ${x}`),L;if(!E.some(C=>I.videoRanges[C]>0))return Qe(R,`no variants with VIDEO-RANGE of ${ce(E)} found`),L;if(c&&R.indexOf(c.substring(0,4))%5!==0)return Qe(R,`video codec preference "${c}" not found`),L;if(I.maxScore<y)return Qe(R,`max score of ${I.maxScore} < selected max of ${y}`),L}return L&&(Ns(R)>=Ns(L)||I.fragmentError>a[L].fragmentError)?L:(p=I.minIndex,y=I.maxScore,R)},void 0),videoRanges:E,preferHDR:v,minFramerate:g,minBitrate:f,minIndex:p}}function Qe(a,e){ne.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Ta(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function dc(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Hr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function tt(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(Ct(a,i,t))return s}return-1}function Ct(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||fc(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||gc(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function fc(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function gc(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Dt(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function mc(a,e,t,s,i){const r=e[s],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=Yr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return tt(a,f,i)>-1});return u>-1?u:Yr(e,s,d=>{const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return tt(a,f,i)>-1})}function Yr(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function $s(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class pc extends Ye{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,g=n.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const v=n.mainForwardBufferInfo;if(!E&&v===null)return;const T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(d<=Math.max(T,1e3*(u/(S*2))))return;const x=v?v.len/S:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,L=this.getBwEstimate(),R=n.levels,I=R[f],C=Math.max(h.loaded,Math.round(u*(i.bitrate||I.averageBitrate)/8));let $=A?d-D:d;$<1&&A&&($=Math.min(d,h.loaded*8/L));const K=A?h.loaded*1e3/$:0,H=T/1e3,O=K?(C-h.loaded)/K:C*8/L+H;if(O<=x)return;const w=K?K*8:L,k=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,M=this.hls.config.abrBandWidthUpFactor;let N=Number.POSITIVE_INFINITY,G;for(G=f-1;G>g;G--){const J=R[G].maxBitrate,X=!R[G].details||k;if(N=this.getTimeToLoadFrag(H,w,u*J,X),N<Math.min(x,u+H))break}if(N>=O||N>u*10)return;A?this.bwEstimator.sample(d-Math.min(T,D),h.loaded):this.bwEstimator.sampleTTFB(d);const B=R[G].maxBitrate;this.getBwEstimate()*M>B&&this.resetEstimator(B);const U=this.findBestLevel(B,g,G,0,x,1,1);U>-1&&(G=U),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly; 2 + Fragment duration: ${i.duration.toFixed(3)} 3 + Time to underbuffer: ${x.toFixed(3)} s 4 + Estimated load time for current fragment: ${O.toFixed(3)} s 5 + Estimated load time for down switch fragment: ${N.toFixed(3)} s 6 + TTFB estimate: ${D|0} ms 7 + Current BW estimate: ${V(L)?L|0:"Unknown"} bps 8 + New BW estimate: ${this.getBwEstimate()|0} bps 9 + Switching to level ${G} @ ${B|0} bps`),n.nextLoadLevel=n.nextAutoLevel=G,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===G&&G>0){const J=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${G>0?"and switching down":""} 10 + Fragment duration: ${i.duration.toFixed(3)} s 11 + Time to underbuffer: ${J.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,G>g){let X=this.findBestLevel(this.hls.levels[g].bitrate,g,G,0,J,1,1);X===-1&&(X=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||O>N*2?j():this.timer=self.setInterval(j,N*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},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 Sl(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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;V(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===Y.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Y.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[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:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,n,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const g=this.findBestLevel(c,n,i,l,d,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[n],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(f.length===1)return 0;const v=f[u],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||h===-1;let x,D="SDR",A=v?.frameRate||0;const{audioPreference:L,videoPreference:R}=E,I=this.audioTracksByGroup||(this.audioTracksByGroup=Ta(p));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=dc(f,I,t,s)),k=uc(w,D,e,L,R),{codecSet:M,videoRanges:N,minFramerate:G,minBitrate:B,minIndex:U,preferHDR:j}=k;C=U,x=M,D=j?N[N.length-1]:N[0],A=G,e=Math.max(e,B),this.log(`picked start tier ${ce(k)}`)}else x=v?.codecSet,D=v?.videoRange;const $=g?g.duration:d?d.duration:0,K=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let w=s;w>=t;w--){var O;const k=f[w],M=w>u;if(!k)continue;if(E.useMediaCapabilities&&!k.supportedResult&&!k.supportedPromise){const X=navigator.mediaCapabilities;typeof X?.decodingInfo=="function"&&tc(k,I,D,A,e,L)?(k.supportedPromise=Ea(k,I,X,this.supportedCache),k.supportedPromise.then(Z=>{if(!this.hls)return;k.supportedResult=Z;const oe=this.hls.levels,he=oe.indexOf(k);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${he} ${ce(Z)}`):Z.supported?Z.decodingInfoResults.some(xe=>xe.smooth===!1||xe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${he} not smooth or powerEfficient: ${ce(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${he} ${ce(Z)}`),he>-1&&oe.length>1&&(this.log(`Removing unsupported level ${he}`),this.hls.removeLevel(he),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):k.supportedResult=pa}if((x&&k.codecSet!==x||D&&k.videoRange!==D||M&&A>k.frameRate||!M&&A>0&&A<k.frameRate||(O=k.supportedResult)!=null&&(O=O.decodingInfoResults)!=null&&O.some(X=>X.smooth===!1))&&(!S||w!==C)){H.push(w);continue}const N=k.details,G=(g?N?.partTarget:N?.averagetargetduration)||$;let B;M?B=o*e:B=n*e;const U=$&&i>=$*2&&r===0?k.averageBitrate:k.maxBitrate,j=this.getTimeToLoadFrag(K,B,U*G,N===void 0);if(B>=U&&(w===h||k.loadError===0&&k.fragmentError===0)&&(j<=K||!V(j)||T&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return w!==y&&(X===-1||X!==y)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[H[0]].codecs}" ${f[H[0]].videoRange}; not compatible with "${x}" ${D}`),this.info(`switch candidate:${u}->${w} adjustedbw(${Math.round(B)})-bitrate=${Math.round(B-U)} ttfb:${K.toFixed(1)} avgDuration:${G.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${S} codecSet:${k.codecSet} videoRange:${k.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Sa={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function yc(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!V(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(vc(e,t,n))return n}return null}function Pt(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&Wr(t,s,r)===0||Ec(r,a,Math.min(i,s))))return r;const n=Sa.search(e,Wr.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Ec(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function Wr(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function vc(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function xa(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return Sa.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function Gs(a){switch(a.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Aa(a){return a.details.startsWith("key")}function Ia(a){return Aa(a)&&!!a.frag&&!a.frag.decryptdata}function qr(a,e){const t=Gs(e);return a.default[`${t?"timeout":"error"}Retry`]}function ar(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function jr(a){return re(re({},a),{errorRetry:null,timeoutRetry:null})}function Ks(a,e,t,s){if(!a)return!1;const i=s?.code,r=e<a.maxNumRetry&&(Tc(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function Tc(a){return Mi(a)||!!a&&(a<400||a>499)}function Mi(a){return a===0&&navigator.onLine===!1}var Re={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ue={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Sc extends Ye{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===Y.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Gt();return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var n;const c=t.parent===Y.MAIN?t.level:i.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===te.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===te.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Ue.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingHDCP};return;case _.KEY_SYSTEM_SESSION_UPDATE_FAILED:case _.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case _.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingKey};return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction=Gt();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Gt())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=qr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Ks(i,r,Gs(e),e.response))return{action:Re.RetryRequest,flags:Ue.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=qr(Aa(e)?n:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==_.FRAG_GAP&&i.fragmentError++,!Ia(e)&&Ks(o,c,Gs(e),e.response)))return{action:Re.RetryRequest,flags:Ue.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===_.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===Y.AUDIO&&l===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>i.audioCodec!==D),T=e.sourceBufferName==="video"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:A})=>i.codecSet!==D&&i.audioCodec===A),{type:S,groupId:x}=(n=e.context)!=null?n:{};for(let D=u.length;D--;){const A=(D+d)%u.length;if(A!==d&&A>=g&&A<=f&&u[A].loadError===0){var o,c;const L=u[A];if(l===_.FRAG_GAP&&p===Y.MAIN&&e.frag){const R=u[A].details;if(R){const I=Pt(e.frag,R.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(S===te.AUDIO_TRACK&&L.hasAudioGroup(x)||S===te.SUBTITLE_TRACK&&L.hasSubtitleGroup(x))continue;if(p===Y.AUDIO&&(o=i.audioGroups)!=null&&o.some(R=>L.hasAudioGroup(R))||p===Y.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(R=>L.hasSubtitleGroup(R))||E&&i.audioCodec===L.audioCodec||T&&i.codecSet===L.codecSet||!E&&i.codecSet!==L.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Ue.None,nextAutoLevel:h}}return{action:Re.SendAlternateToPenaltyBox,flags:Ue.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.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,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ue.None:this.switchLevel(e,r);break;case Ue.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=Fi[Fi.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ue.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var n,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(n=l[d].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${be(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==Y.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===_.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Oi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Gt(a){const e={action:Re.DoNothing,flags:Ue.None};return a&&(e.resolved=!0),e}var Ie={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class xc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if(o?.body.type===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=Ft(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),fs(r)||this.removeParts(s.sn-1,s.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 s=this.activePartLists[t];s&&(this.activePartLists[t]=Xr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ft(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<d&&o>u){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&fs(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||fs(t))}getState(e){const t=Ft(e),s=this.fragments[t];return s?s.buffered?fs(s)?Ie.PARTIAL:Ie.OK:Ie.APPENDING:Ie.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Ft(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ft(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Ft(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Xr(s,r=>r.fragment.sn!==i)}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(s=>s.clearElementaryStreamInfo())}}function fs(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function Ft(a){return`${a.type}_${a.level}_${a.sn}`}function Xr(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Lt={cbc:0,ctr:1};class Ac{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Lt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Lt.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 Ic(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class Lc{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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[f]=E,t[E]=f;const v=g[f],T=g[v],S=g[T];let x=g[E]*257^E*16843008;i[f]=x<<24|x>>>8,r[f]=x<<16|x>>>16,n[f]=x<<8|x>>>24,o[f]=x,x=S*16843009^T*65537^v*257^f*16843008,l[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,f?(f=v^g[g[g[S^v]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],E=g[3];let v,T;for(o=0;o<n;o++){if(o<r){v=l[o]=t[o];continue}T=v,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),l[o]=v=(l[o-r]^T)>>>0}for(c=0;c<n;c++)o=n-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?h[c]=T:h[c]=f[u[T>>>24]]^p[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],p=d[2],y=d[3];const E=new Int32Array(e),v=new Int32Array(E.length);let T,S,x,D,A,L,R,I,C,$,K,H,O,w;const k=this.networkToHostOrderSwap;for(;t<E.length;){for(C=k(E[t]),$=k(E[t+1]),K=k(E[t+2]),H=k(E[t+3]),A=C^r[0],L=H^r[1],R=K^r[2],I=$^r[3],O=4,w=1;w<i;w++)T=c[A>>>24]^l[L>>16&255]^h[R>>8&255]^u[I&255]^r[O],S=c[L>>>24]^l[R>>16&255]^h[I>>8&255]^u[A&255]^r[O+1],x=c[R>>>24]^l[I>>16&255]^h[A>>8&255]^u[L&255]^r[O+2],D=c[I>>>24]^l[A>>16&255]^h[L>>8&255]^u[R&255]^r[O+3],A=T,L=S,R=x,I=D,O=O+4;T=n[A>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[I&255]^r[O],S=n[L>>>24]<<24^n[R>>16&255]<<16^n[I>>8&255]<<8^n[A&255]^r[O+1],x=n[R>>>24]<<24^n[I>>16&255]<<16^n[A>>8&255]<<8^n[L&255]^r[O+2],D=n[I>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[R&255]^r[O+3],v[t]=k(T^g),v[t+1]=k(D^f),v[t+2]=k(x^p),v[t+3]=k(S^y),g=C,f=$,p=K,y=H,t=t+4}return v.buffer}}class Rc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=bc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function bc(a){switch(a){case Lt.cbc:return"AES-CBC";case Lt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const _c=16;class or{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Ic(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==Lt.cbc||t.byteLength!==16)return ne.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=He(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Lc),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Rc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ac(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ne.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%_c;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ne.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const zr=Math.pow(2,17);class Dc{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 s=e.url;if(!s)return Promise.reject(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(Zr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Qr(e);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:zr};e.stats=l.stats;const g={onSuccess:(f,p,y,E)=>{this.resetLoader(e,l);let v=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:E})},onError:(f,p,y,E)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:E}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Zr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Qr(e,t);e.loader=l;const u=jr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:zr};t.stats=l.stats,l.load(h,d,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:g.data,networkDetails:y};s(E),o(E)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new ht({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qr(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(V(i)&&V(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&Cc((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Zr(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new ht(s)}function Cc(a){return a==="AES-128"||a==="AES-256"}class ht extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class La extends Ye{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 lr{constructor(e,t,s,i=0,r=-1,n=!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=gs(),this.buffering={audio:gs(),video:gs(),audiovideo:gs()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function gs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Jr={length:0,start:()=>0,end:()=>0};class Q{static isBuffered(e,t){if(e){const s=Q.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=Q.getBuffered(e);return Q.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=Q.bufferedRanges(e);if(i.length)return Q.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,n=l-t;else if(t+s<u){o=u;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Jr}catch(t){return ne.log("failed to get media.buffered",t),Jr}}}const Ra=/\{\$([a-zA-Z0-9-_]+)\}/g;function en(a){return Ra.test(a)}function Ni(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Ra,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function tn(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Pc(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const kc=/^(\d+)x(\d+)$/,sn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class fe{constructor(e,t){typeof e=="string"&&(e=fe.parseAttrList(e,t)),ae(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 s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=kc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(sn.lastIndex=0;(s=sn.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Ni(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="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":ne.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const wc="com.apple.hls.interstitial";function Oc(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Fc(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class ba{constructor(e,t,s=0){var i;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=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){ne.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=ae(new fe({}),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"]);V(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?(ne.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(V(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===wc}get isValid(){return!!this.id&&!this._badValueForSameId&&V(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 Mc=10;class Nc{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>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 s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?V(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Mc}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 Vs(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function rn(a,e){return!a&&!e?!0:!a||!e?!1:Vs(a,e)}function Kt(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function cr(a){switch(a){case"AES-128":case"AES-256":return Lt.cbc;case"AES-256-CTR":return Lt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function hr(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Bi(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function Bc(a){const e=Bi(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function _a(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function Da(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=hr(n)):t=Bc(n)}}return t}const Hs=typeof self<"u"?self:void 0;var ge={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},_e={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ds(a){switch(a){case _e.FAIRPLAY:return ge.FAIRPLAY;case _e.PLAYREADY:return ge.PLAYREADY;case _e.WIDEVINE:return ge.WIDEVINE;case _e.CLEARKEY:return ge.CLEARKEY}}function li(a){switch(a){case ge.FAIRPLAY:return _e.FAIRPLAY;case ge.PLAYREADY:return _e.PLAYREADY;case ge.WIDEVINE:return _e.WIDEVINE;case ge.CLEARKEY:return _e.CLEARKEY}}function Qt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[ge.FAIRPLAY,ge.WIDEVINE,ge.PLAYREADY,ge.CLEARKEY].filter(i=>!!e[i]):[];return!s[ge.WIDEVINE]&&t&&s.push(ge.WIDEVINE),s}const Ca=(function(a){return Hs!=null&&(a=Hs.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Uc(a,e,t,s){let i;switch(a){case ge.FAIRPLAY:i=["cenc","sinf"];break;case ge.WIDEVINE:case ge.PLAYREADY:i=["cenc"];break;case ge.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return $c(i,e,t,s)}function $c(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Gc(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Pa(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=hr(o).subarray(0,16);return _a(c),c}}return null}let Mt={};class At{static clearKeyUriToKeyIdMap(){Mt={}}static setKeyIdForUri(e,t){Mt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Mt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Mt[e]=s,s}constructor(e,t,s,i=[1],r=null,n){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=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Kt(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(na(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Vs(e.keyFormatVersions,this.keyFormatVersions)&&rn(e.iv,this.iv)&&rn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Kt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case _e.FAIRPLAY:case _e.WIDEVINE:case _e.PLAYREADY:case _e.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(Kt(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ne.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Vc(e)),new At(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Mt[this.uri];if(r&&!Vs(this.keyId,r)&&At.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Da(this.uri);if(s)switch(this.keyFormat){case _e.WIDEVINE:if(this.pssh=s,!this.keyId){const r=Wl(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=nn(t));break;case _e.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Yl(r,null,s),this.keyId=Pa(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Kc(t),r||(r=nn(t),r||(r=Mt[this.uri])),r&&(this.keyId=r,At.setKeyIdForUri(this.uri,r))}return this}}function Kc(a){const e=a?.[_e.WIDEVINE];return e?e.keyId:null}function nn(a){const e=a?.[_e.PLAYREADY];if(e){const t=Da(e.uri);if(t)return Pa(t)}return null}function Vc(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const an=/#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,on=/#EXT-X-MEDIA:(.*)/g,Hc=/^#EXT(?:INF|-X-TARGETDURATION):/m,ci=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Yc=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 st{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return tr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Hc.test(e)}static parseMasterPlaylist(e,t){const s=en(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(an.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=an.exec(e))!=null;)if(n[1]){var o;const l=new fe(n[1],i),h=Ni(i,n[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:st.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),hn(l.CODECS,u);const g=l["SUPPLEMENTAL-CODECS"];g&&(u.supplemental={},hn(g,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const u=new fe(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=ln(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):ne.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new fe(h,i);tn(i,u,t)}break}case"CONTENT-STEERING":{const u=new fe(h,i);i.contentSteering={uri:st.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=cn(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(on.lastIndex=0;(i=on.exec(e))!==null;){const l=new fe(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],v={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?st.resolve(l.URI,t):""};if(f&&(v.assocLang=f),p&&(v.channels=p),y&&(v.characteristics=y),E&&(v.instreamId=E),u!=null&&u.length){const T=st.findGroup(u,v.groupId)||u[0];un(v,T,"audioCodec"),un(v,T,"textCodec")}d.push(v)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new Nc(t),h=l.fragments,u=[];let d=null,g=0,f=0,p=0,y=0,E=0,v=null,T=new ni(i,c),S,x,D,A=-1,L=!1,R=null,I;if(ci.lastIndex=0,l.m3u8=e,l.hasVariableRefs=en(e),((o=ci.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=ci.exec(e))!==null;){L&&(L=!1,T=new ni(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),R&&(T.setByteRange(R),R=null)));const H=S[1];if(H){T.duration=parseFloat(H);const O=(" "+S[2]).slice(1);T.title=O||null,T.tagList.push(O?["INF",H,O]:["INF",H])}else if(S[3]){if(V(T.duration)){T.playlistOffset=p,T.setStart(p),D&&fn(T,D,l),T.sn=g,T.level=s,T.cc=y,h.push(T);const O=(" "+S[3]).slice(1);T.relurl=Ni(l,O),Ui(T,v,u),v=T,p+=T.duration,g++,f=0,L=!0}}else{if(S=S[0].match(Yc),!S){ne.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<S.length&&S[x]===void 0;x++);const O=(" "+S[x]).slice(1),w=(" "+S[x+1]).slice(1),k=S[x+2]?(" "+S[x+2]).slice(1):null;switch(O){case"BYTERANGE":v?T.setByteRange(w,v):T.setByteRange(w);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=w,T.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&lt(l,O,S),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?lt(l,O,S):h.length>0&&gn(l,O,S),g=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&lt(l,O,S);const M=new fe(w,l),N=M.decimalInteger("SKIPPED-SEGMENTS");if(V(N)){l.skippedSegments+=N;for(let B=N;B--;)h.push(null);g+=N}const G=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(G.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&lt(l,O,S),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&lt(l,O,S),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||lt(l,O,S),l.live=!1;break;case"#":(w||k)&&T.tagList.push(k?[w,k]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([O]);break;case"BITRATE":T.tagList.push([O,w]),E=parseInt(w)*1e3,V(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const M=new fe(w,l),N=new ba(M,l.dateRanges[M.ID],l.dateRangeTagCount);l.dateRangeTagCount++,N.isValid||l.skippedSegments?l.dateRanges[N.id]=N:ne.warn(`Ignoring invalid DATERANGE tag: "${w}"`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const M=new fe(w,l);"IMPORT"in M?Pc(l,M,n):tn(l,M,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?lt(l,O,S):h.length>0&&gn(l,O,S),l.startCC=y=parseInt(w);break;case"KEY":{const M=ln(w,t,l);if(M.isSupported()){if(M.method==="NONE"){D=void 0;break}D||(D={});const N=D[M.keyFormat];N!=null&&N.matches(M)||(N&&(D=ae({},D)),D[M.keyFormat]=M)}else ne.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=cn(w);break;case"MAP":{const M=new fe(w,l);if(T.duration){const N=new ni(i,c);dn(N,M,s,D),d=N,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const N=T.byteRangeEndOffset;if(N){const G=T.byteRangeStartOffset;R=`${N-G}@${G}`}else R=null;dn(T,M,s,D),d=T,L=!0}d.cc=y;break}case"SERVER-CONTROL":{I&&lt(l,O,S),I=new fe(w),l.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),l.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&lt(l,O,S);const M=new fe(w);l.partTarget=M.decimalFloatingPoint("PART-TARGET");break}case"PART":{let M=l.partList;M||(M=l.partList=[]);const N=f>0?M[M.length-1]:void 0,G=f++,B=new fe(w,l),U=new Pl(B,T,c,G,N);M.push(U),T.duration+=U.duration;break}case"PRELOAD-HINT":{const M=new fe(w,l);l.preloadHint=M;break}case"RENDITION-REPORT":{const M=new fe(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(M);break}default:ne.warn(`line parsed but not handled: ${S}`);break}}}v&&!v.relurl?(h.pop(),p-=v.duration,l.partList&&(l.fragmentHint=v)):l.partList&&(Ui(T,v,u),T.cc=y,l.fragmentHint=T,D&&fn(T,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,$=h[0],K=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&K){l.averagetargetduration=p/C;const H=K.sn;l.endSN=H!=="initSegment"?H:0,l.live||(K.endList=!0),A>0&&(qc(h,A),$&&u.unshift($))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&$&&ka(u,l),l.endCC=y,l}}function ka(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var n;if(((n=a[h])==null?void 0:n.sn)<e.startSN)break;const u=Wc(e,l,a,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function Wc(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const h=a.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let g=d;g>l;g--){const f=h[g].programDateTime;if(e>=f&&e<f+h[g].duration*1e3)return g}}return l}}}return-1}function ln(a,e,t){var s,i;const r=new fe(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&ne.error(`Invalid IV: ${r.IV}`);const u=o?st.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new At(n,u,h,d,c,r.KEYID)}function cn(a){const t=new fe(a).decimalFloatingPoint("TIME-OFFSET");return V(t)?t:null}function hn(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>rr(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function un(a,e,t){const s=e[t];s&&(a[t]=s)}function qc(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ui(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function dn(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function fn(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function lt(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function gn(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function hi(a,e){const t=e.startPTS;if(V(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function wa(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(V(h)){const E=Math.abs(h-t);a&&E>a.totalduration?n.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${a.url}`):V(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const g=e.sn;if(!a||g<a.startSN||g>a.endSN)return 0;let f;const p=g-a.startSN,y=a.fragments;for(y[p]=e,f=p;f>0;f--)hi(y[f],y[f-1]);for(f=p;f<y.length-1;f++)hi(y[f],y[f+1]);return a.fragmentHint&&hi(y[y.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,d}function jc(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;Qc(a,e,(h,u,d,g)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const f=h.cc-u.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}V(h.startPTS)&&V(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Xc(a.dateRanges,e,t));const h=a.fragments.filter(u=>u.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ui(o[u],o[u-1],h);ka(h,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const h=Ma(a,e.startSN-1);e.startCC=(c=h?.cc)!=null?c:n[0].cc}zc(a.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?wa(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Oa(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function Xc(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ae({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new ba(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ce(s[c].attr)}"`)}),r):s}function zc(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function Qc(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=c[n+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,g=u.relurl;if(d&&Zc(d,g)){e.playlistParsingError=mn(`media sequence mismatch ${u.sn}:`,a,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=mn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,a,e,h,u);return}}}}function mn(a,e,t,s,i){return new Error(`${a} ${i.url} 12 + Playlist starting @${e.startSN} 13 + ${e.m3u8} 14 + 15 + Playlist starting @${t.startSN} 16 + ${t.m3u8}`)}function Oa(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;$i(e,n)}function $i(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Fa(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ma(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function pn(a,e,t){return a?Na(a.partList,e,t):null}function Na(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ba(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Zc(a,e){return a!==e&&e?yn(a)!==yn(e):!1}function yn(a){return a.replace(/\?[^?]*$/,"")}function Jt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Jc(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function En(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Ua(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)En(t[s],a);e.fragmentHint&&En(e.fragmentHint,a),e.alignedSliding=!0}function eh(a,e){a&&($a(e,a),e.alignedSliding||Ys(e,a),!e.alignedSliding&&!e.skippedSegments&&Oa(a,e,!1))}function $a(a,e){if(!Jc(e,a))return;const t=Math.min(e.endCC,a.endCC),s=Jt(e.fragments,t),i=Jt(a.fragments,t);if(!s||!i)return;ne.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Ua(r,a)}function Ys(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=Jt(s,n),r=Jt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Jt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Ua(l,a)}function we(a,e,t){Me(a,e,t),a.addEventListener(e,t)}function Me(a,e,t){a.removeEventListener(e,t)}const th={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ur extends La{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=Q.bufferInfo(l||c,u,n.maxBufferHole),g=!d.len;if(this.log(`Media seeking to ${V(u)?u.toFixed(3):u}, state: ${h}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const f=n.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(u>f&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),g&&this.state===P.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 Dc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new or(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===P.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=P.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 s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Q.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return Q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;we(s,"seeking",this.onMediaSeeking),we(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Me(i,"seeking",this.onMediaSeeking),Me(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===P.FRAG_LOADING||!this.fragCurrent&&n===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ie.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ie.PARTIAL&&s.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,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Kt(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,cr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,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 s=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:${s?th.toString(Q.getBuffered(s)):"(detached)"})`),Te(e)){var i;if(e.type!==Y.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new lr(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),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||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Te(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&Te(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const g=this.getNextPart(d,e,s);if(g>-1){const f=d[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${d.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(Te(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.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} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),V(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==Y.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const g=d.part;this.hls.trigger(m.FRAG_LOADED,d);const f=pn(s.details,e.sn,u.index+1)||Na(l,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.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:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===Y.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?pn(c,r,n):null,h=l?l.fragment:Ma(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=He(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=Q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!V(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=Q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return Q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=Y.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(d!==-1&&d>=n?d:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Ie.OK||s===Ie.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(vn(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(vn(this.config)&&e.type!==Y.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=yc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=xa(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;d=Pt(r,n,e,p)}else d=n[n.length-1];if(d){const f=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Ie.OK||p===Ie.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[f+1];d.sn<o&&this.fragmentTracker.getState(E)!==Ie.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&V(r);if(n||!o&&!r){eh(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),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 s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&V(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Te(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!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===_.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,g=d&&c===Re.RetryRequest,f=d&&!o.resolved&&l===Ue.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&Te(i)&&!i.endList&&p&&!Ia(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&h<u.maxNumRetry){var y;const E=Mi((y=t.response)==null?void 0:y.code),v=ar(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${v}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Re.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Mi(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Y.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=Q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.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?"<removed>":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,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:wa(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.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===Y.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 vn(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class Ga{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=sh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function sh(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var ui={exports:{}},Tn;function ih(){return Tn||(Tn=1,(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,u||c,d),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,g=u.length,f=new Array(g);d<g;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,v,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,g),!0;case 6:return y.fn.call(y.context,h,u,d,g,f),!0}for(T=1,v=new Array(E-1);T<E;T++)v[T-1]=arguments[T];y.fn.apply(y.context,v)}else{var S=y.length,x;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!v)for(x=1,v=new Array(E-1);x<E;x++)v[x-1]=arguments[x];y[T].fn.apply(y[T].context,v)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var g=t?t+l:l;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&n(this,g);else{for(var p=0,y=[],E=f.length;p<E;p++)(f[p].fn!==h||d&&!f[p].once||u&&f[p].context!==u)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(ui)),ui.exports}var rh=ih(),dr=Dl(rh);const ns="1.6.15",Wt={};function nh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ah(){const a=Wt[ns];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Wt[ns]=i,i}function oh(a){const e=Wt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wt[a]=i,i}function lh(a){const e=Wt[a||ns];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Wt[a||ns],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Ka(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function fr(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Xs(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function as(a,e){const t=e;let s=0;for(;fr(a,e);){s+=10;const i=Xs(a,e+6);s+=i,Ka(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function ch(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const g=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return ne.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Va(a,e){return a[e]===255&&(a[e+1]&246)===240}function Ha(a,e){return a[e+1]&1?7:9}function gr(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function hh(a,e){return e+5<a.length}function Ws(a,e){return e+1<a.length&&Va(a,e)}function uh(a,e){return hh(a,e)&&Va(a,e)&&gr(a,e)<=a.length-e}function dh(a,e){if(Ws(a,e)){const t=Ha(a,e);if(e+t>=a.length)return!1;const s=gr(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||Ws(a,i)}return!1}function Ya(a,e,t,s,i){if(!a.samplerate){const r=ch(e,t,s,i);if(!r)return;ae(a,r)}}function Wa(a){return 1024*9e4/a}function fh(a,e){const t=Ha(a,e);if(e+t<=a.length){const s=gr(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function qa(a,e,t,s,i){const r=Wa(a.samplerate),n=s+i*r,o=fh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,g=d+u,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+g);const p={unit:c,pts:n};return f||a.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function gh(a,e){return fr(a,e)&&Xs(a,e+6)+10<=a.length-e}function mh(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function di(a,e=0,t=1/0){return ph(a,e,t,Uint8Array)}function ph(a,e,t,s){const i=yh(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=Eh(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function yh(a){return a instanceof ArrayBuffer?a:a.buffer}function Eh(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function vh(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ve(di(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=Ve(di(a.data,3+s,n));let c;return i==="-->"?c=Ve(di(a.data,4+s+n)):c=mh(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Th(a){if(a.size<2)return;const e=Ve(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Sh(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Ve(a.data.subarray(t),!0);t+=s.length+1;const i=Ve(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Ve(a.data.subarray(1));return{key:a.type,info:"",data:e}}function xh(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Ve(a.data.subarray(t),!0);t+=s.length+1;const i=Ve(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Ve(a.data);return{key:a.type,info:"",data:e}}function Ah(a){return a.type==="PRIV"?Th(a):a.type[0]==="W"?xh(a):a.type==="APIC"?vh(a):Sh(a)}function Ih(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Xs(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const ms=10,Lh=10;function ja(a){let e=0;const t=[];for(;fr(a,e);){const s=Xs(a,e+6);a[e+5]>>6&1&&(e+=ms),e+=ms;const i=e+s;for(;e+Lh<i;){const r=Ih(a.subarray(e)),n=Ah(r);n&&t.push(n),e+=r.size+ms}Ka(a,e)&&(e+=ms)}return t}function Xa(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Rh(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function mr(a){const e=ja(a);for(let t=0;t<e.length;t++){const s=e[t];if(Xa(s))return Rh(s)}}let Ke=(function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a})({});function et(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class pr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=He(this.cachedData,e),this.cachedData=null);let s=as(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?mr(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&V(c))&&(this.basePTS=bh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ke.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else gh(e,i)?(s=as(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ke.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=He(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:et(),id3Track:o,textTrack:et()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:et(),id3Track:this._id3Track,textTrack:et()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const bh=(a,e,t)=>{if(V(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let ps=null;const _h=[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],Dh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ch=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ph=[0,1,1,4];function za(a,e,t,s,i){if(t+24>e.length)return;const r=Qa(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function Qa(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=_h[c*14+i-1]*1e3,u=Dh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,g=Ch[t][s],f=Ph[s],p=g*8*f,y=Math.floor(g*l/u+n)*f;if(ps===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ps=T?parseInt(T[1]):0}return ps&&ps<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function yr(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function Za(a,e){return e+1<a.length&&yr(a,e)}function kh(a,e){return yr(a,e)&&4<=a.length-e}function Ja(a,e){if(e+1<a.length&&yr(a,e)){const s=Qa(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||Za(a,r)}return!1}class wh extends pr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=as(e,0);let i=s?.length||0;if(Ja(e,i))return!1;for(let r=e.length;i<r;i++)if(dh(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return uh(e,t)}appendFrame(e,t,s){Ya(e,this.observer,t,s,e.manifestCodec);const i=qa(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const eo=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Oh extends pr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=to(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=as(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&mr(t)!==void 0&&eo(e,s)<16}}function to(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+g,y=e[t+5]>>3,E=e[t+5]&7,v=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,x=e.subarray(t,t+h);return a.config=v,a.channelCount=p,a.samplerate=o,a.samples.push({unit:x,pts:S}),h}class Fh extends pr{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=as(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&mr(t)!==void 0&&eo(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Ja(e,s))return ne.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return kh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return za(e,t,s,this.basePTS,this.frameIndex)}}const Mh=/\/emsg[-/]ID3/i;class Nh{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=et("video",1),n=this.audioTrack=et("audio",1),o=this.txtTrack=et("text",1);if(this.id3Track=et("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ua(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=la.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Ol(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=He(this.remainderData,e));const o=Gl(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Nr(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Nr(e,t),{videoTrack:t,audioTrack:et(),id3Track:i,textTrack:et()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=ee(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Vl(r);if(Mh.test(n.schemeIdUri)){const o=Sn(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Ke.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Sn(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Ke.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Sn(a,e){return V(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class Bh{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new or(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Lt.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=ga(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class so{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,g=0;for(r===-1&&(d=0,g=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const f={data:t.subarray(d,h),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&c<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=He(f.data,t.subarray(0,h)),f.state=0))}c<i?(u=this.getNALuType(t,c),d=c,g=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const f={data:t.subarray(d,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=He(f.data,t))}return e.naluState=r,o}}class es{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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.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 s=this.word>>>32-t;if(e>32&&ne.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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>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 Uh extends so{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=p;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,ir(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let v="avc1.";for(let T=0;T<3;T++){let S=E[T].toString(16);S.length<2&&(S="0"+S),v+=S}e.codec=v}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new es(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new es(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const v=h();if(u(5),f(3),h(),y(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const L=d();if(L===3&&f(1),y(),y(),f(1),g())for(c=L!==3?8:12,l=0;l<c;l++)g()&&(l<6?E(16,t):E(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(f(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),f(1);const S=d(),x=d(),D=u(1);D===0&&f(1),f(1),g()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(g()&&g())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+n),pixelRatio:A}}}class $h extends so{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,ir(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ae(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new es(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new es(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),v=[],T=[];for(let se=0;se<s;se++)v.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let se=s;se<8;se++)t.readBits(2);for(let se=0;se<s;se++)v[se]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[se]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let L=0,R=0,I=0,C=0;A&&(L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG(),C+=t.readUEG());const $=t.readUEG(),K=t.readUEG(),H=t.readUEG(),O=t.readBoolean();for(let se=O?0:s;se<=s;se++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Se=0;Se<4;Se++)for(let Pe=0;Pe<(Se===3?2:6);Pe++)if(!t.readBoolean())t.readUEG();else{const Ne=Math.min(64,1<<4+(Se<<1));Se>1&&t.readEG();for(let at=0;at<Ne;at++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const M=t.readUEG();let N=0;for(let se=0;se<M;se++){let Se=!1;if(se!==0&&(Se=t.readBoolean()),Se){se===M&&t.readUEG(),t.readBoolean(),t.readUEG();let Pe=0;for(let ze=0;ze<=N;ze++){const Ne=t.readBoolean();let at=!1;Ne||(at=t.readBoolean()),(Ne||at)&&Pe++}N=Pe}else{const Pe=t.readUEG(),ze=t.readUEG();N=Pe+ze;for(let Ne=0;Ne<Pe;Ne++)t.readUEG(),t.readBoolean();for(let Ne=0;Ne<ze;Ne++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const se=t.readUEG();for(let Se=0;Se<se;Se++){for(let Pe=0;Pe<H+4;Pe++)t.readBits(1);t.readBits(1)}}let B=0,U=1,j=1,J=!0,X=1,Z=0;t.readBoolean(),t.readBoolean();let oe=!1;if(t.readBoolean()){if(t.readBoolean()){const ot=t.readUByte(),cs=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],wt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ot>0&&ot<16?(U=cs[ot-1],j=wt[ot-1]):ot===255&&(U=t.readBits(16),j=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(),oe=t.readBoolean(),oe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const wt=t.readBoolean(),me=t.readBoolean();let Ee=!1;(wt||me)&&(Ee=t.readBoolean(),Ee&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ee&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Rt=0;Rt<=s;Rt++){J=t.readBoolean();const Zs=J||t.readBoolean();let Lr=!1;Zs?t.readEG():Lr=t.readBoolean();const Rr=Lr?1:t.readUEG()+1;if(wt)for(let qt=0;qt<Rr;qt++)t.readUEG(),t.readUEG(),Ee&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(me)for(let qt=0;qt<Rr;qt++)t.readUEG(),t.readUEG(),Ee&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),B=t.readUEG())}let xe=x,Ce=D;if(A){let se=1,Se=1;S===1?se=Se=2:S==2&&(se=2),xe=x-se*R-se*L,Ce=D-Se*C-Se*I}const ye=i?["A","B","C"][i]:"",nt=o<<24|c<<16|l<<8|h;let kt=0;for(let se=0;se<32;se++)kt=(kt|(nt>>se&1)<<31-se)>>>0;let We=kt.toString(16);return n===1&&We==="2"&&(We="6"),{codecString:`hvc1.${ye}${n}.${We}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,g,f,p,y],general_level_idc:E,bit_depth:$+8,bit_depth_luma_minus8:$,bit_depth_chroma_minus8:K,min_spatial_segmentation_idc:B,chroma_format_idc:S,frame_rate:{fixed:J,fps:Z/X}},width:xe,height:Ce,pixelRatio:[U,j]}}readPPS(e){const t=new es(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 i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Le=188;class St{constructor(e,t,s,i){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=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=St.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Le*5,t-Le)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=Le)if(e[c]===71&&(t-c===Le||e[c+Le]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+Le*99,e.length-Le)+1)),r||(r=Gi(e,c)===0),r&&o>1&&(n===0&&o>2||c+Le>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:la[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=St.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=St.createTrack("audio",i),this._id3Track=St.createTrack("id3"),this._txtTrack=St.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,v=this._pmtId,T=e.length;if(this.remainderData&&(e=He(this.remainderData,e),T=e.length,this.remainderData=null),T<Le&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const S=Math.max(0,St.syncOffset(e));T-=(T-S)%Le,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let x=0;for(let A=S;A<T;A+=Le)if(e[A]===71){const L=!!(e[A+1]&64),R=Gi(e,A),I=(e[A+3]&48)>>4;let C;if(I>1){if(C=A+5+e[A+4],C===A+Le)continue}else C=A+4;switch(R){case h:L&&(u&&(r=Nt(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+Le)),u.size+=A+Le-C);break;case d:if(L){if(f&&(r=Nt(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(C,A+Le)),f.size+=A+Le-C);break;case g:L&&(p&&(r=Nt(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+Le)),p.size+=A+Le-C);break;case 0:L&&(C+=e[C]+1),v=this._pmtId=Gh(e,C);break;case v:{L&&(C+=e[C]+1);const $=Kh(e,C,this.typeSupported,s,this.observer,this.logger);h=$.videoPid,h>0&&(n.pid=h,n.segmentCodec=$.segmentVideoCodec),d=$.audioPid,d>0&&(o.pid=d,o.segmentCodec=$.segmentAudioCodec),g=$.id3Pid,g>0&&(c.pid=g),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,A=S-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=R;break}}else x++;x>0&&Ki(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=f,c.pesData=p;const D={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}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:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=Nt(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=Nt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Nt(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new Bh(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Uh:e==="hevc"&&(this.videoParser=new $h))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(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 s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=He(i.sample.unit,r);else{const g=d-u;i.sample.unit.set(r.subarray(0,u),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!Ws(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",Ki(this.observer,new Error(u),d,this.logger),!d)return}Ya(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Wa(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=qa(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!Ws(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(Za(s,n)){const c=za(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=to(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ae({},t,{type:this._videoTrack?Ke.emsg:Ke.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Gi(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Gh(a,e){return(a[e+10]&31)<<8|a[e+11]}function Kh(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=Gi(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){fi("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){fi("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){fi("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,g=u;for(;g>2;){a[d]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3"));const p=a[d+1]+2;d+=p,g-=p}}break;case 194:case 135:return Ki(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function Ki(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function fi(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Nt(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=He(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class Vh{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 yt=Math.pow(2,32)-1;class b{static init(){b.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 b.types)b.types.hasOwnProperty(e)&&(b.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]),s=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]);b.HDLR_TYPES={video:t,audio:s};const i=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]);b.STTS=b.STSC=b.STCO=r,b.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),b.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),b.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),b.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);b.FTYP=b.box(b.types.ftyp,n,c,n,o),b.DINF=b.box(b.types.dinf,b.box(b.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return b.box(b.types.hdlr,b.HDLR_TYPES[e])}static mdat(e){return b.box(b.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(yt+1)),i=Math.floor(t%(yt+1));return b.box(b.types.mdhd,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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return b.box(b.types.mdia,b.mdhd(e.timescale||0,e.duration||0),b.hdlr(e.type),b.minf(e))}static mfhd(e){return b.box(b.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"?b.box(b.types.minf,b.box(b.types.smhd,b.SMHD),b.DINF,b.stbl(e)):b.box(b.types.minf,b.box(b.types.vmhd,b.VMHD),b.DINF,b.stbl(e))}static moof(e,t,s){return b.box(b.types.moof,b.mfhd(e),b.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=b.trak(e[t]);return b.box.apply(null,[b.types.moov,b.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(b.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=b.trex(e[t]);return b.box.apply(null,[b.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(yt+1)),i=Math.floor(t%(yt+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,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&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 b.box(b.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return b.box(b.types.sdtp,s)}static stbl(e){return b.box(b.types.stbl,b.stsd(e),b.box(b.types.stts,b.STTS),b.box(b.types.stsc,b.STSC),b.box(b.types.stsz,b.STSZ),b.box(b.types.stco,b.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=b.box(b.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return b.box(b.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,l>>8&255,l&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]),o,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&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 b.box(b.types.mp4a,b.audioStsd(e),b.box(b.types.esds,b.esds(e)))}static mp3(e){return b.box(b.types[".mp3"],b.audioStsd(e))}static ac3(e){return b.box(b.types["ac-3"],b.audioStsd(e),b.box(b.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return b.box(b.types.stsd,b.STSD,b.mp4a(e));if(t==="ac3"&&e.config)return b.box(b.types.stsd,b.STSD,b.ac3(e));if(t==="mp3"&&e.codec==="mp3")return b.box(b.types.stsd,b.STSD,b.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return b.box(b.types.stsd,b.STSD,b.avc1(e));if(t==="hevc"&&e.vps)return b.box(b.types.stsd,b.STSD,b.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,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(yt+1)),o=Math.floor(s%(yt+1));return b.box(b.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,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&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,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=b.sdtp(e),i=e.id,r=Math.floor(t/(yt+1)),n=Math.floor(t%(yt+1));return b.box(b.types.traf,b.box(b.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),b.box(b.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),b.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,b.box(b.types.trak,b.tkhd(e),b.mdia(e))}static trex(e){const t=e.id;return b.box(b.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 s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return b.box(b.types.trun,n)}static initSegment(e){b.types||b.init();const t=b.moov(e);return He(b.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let p=0;p<s[f].length;p+=1)n+=2+s[f][p].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),n),n+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),n),n+=2,o.set(s[f][p],n),n+=s[f][p].length}const l=b.box(b.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return b.box(b.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,h>>8&255,h&255,u>>8&255,u&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]),l,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}b.types=void 0;b.HDLR_TYPES=void 0;b.STTS=void 0;b.STSC=void 0;b.STCO=void 0;b.STSZ=void 0;b.VMHD=void 0;b.SMHD=void 0;b.STSD=void 0;b.FTYP=void 0;b.DINF=void 0;const io=9e4;function Er(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Hh(a,e,t=1,s=!1){return Er(a,e,1/t,s)}function Xt(a,e=!1){return Er(a,1e3,1/io,e)}function Yh(a,e=1){return Er(a,io,1/e)}function xn(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const Wh=10*1e3,qh=1024,jh=1152,Xh=1536;let Bt=null,gi=null;function An(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class Cs extends Ye{constructor(e,t,s,i){if(super("mp4-remuxer",i),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=s,this.ISGenerated=!1,Bt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bt=n?parseInt(n[1]):0}if(gi===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);gi=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&&xn(t)} > ${e&&xn(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 s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=$e(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,g,f,p=r,y=r;const E=e.pid>-1,v=t.pid>-1,T=t.samples.length,S=e.samples.length>0,x=o&&T>0||T>1;if((!E||S)&&(!v||x)||this.ISGenerated||o){if(this.ISGenerated){var A,L,R,I;const H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((A=t.pixelRatio)==null?void 0:A[0])!==((L=H.pixelRatio)==null?void 0:L[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((I=H.pixelRatio)==null?void 0:I[1]))||!H&&x||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const C=this.isVideoContiguous;let $=-1,K;if(x&&($=zh(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,$>0){this.warn(`Dropped ${$} out of ${T} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice($),t.dropped+=$,y+=(t.samples[0].pts-H)/t.inputTimeScale,K=y}else $===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(S&&x){const H=this.getVideoStartPts(t.samples),w=($e(e.samples[0].pts,H)-H)/t.inputTimeScale;p+=Math.max(0,w),y+=Math.max(0,-w)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,v||x||c===Y.AUDIO?y:void 0),x){const H=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,y,C,H)}}else x&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=$,l.independent=$!==-1,l.firstKeyFramePTS=K)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=ro(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=no(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=$e(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,g,f,p=-1;if(h&&(d=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):b.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?d=g=this.computeInitPts(r[0].pts,f,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:b.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(n),E=$e(n[0].dts,y),v=this.computeInitPts(E,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,v),d=Math.min(d,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:c,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,v=!1;if(!s||u===null){const B=h+t*r,U=n[0].pts-$e(n[0].dts,n[0].pts);Bt&&u!==null&&Math.abs(B-U-(u+h))<15e3?s=!0:u=B-U-h}const T=u+h;for(let B=0;B<c;B++){const U=n[B];U.pts=$e(U.pts,T),U.dts=$e(U.dts,T),U.dts<n[B>0?B-1:B].dts&&(v=!0)}v&&n.sort(function(B,U){const j=B.dts-U.dts,J=B.pts-U.pts;return j||J}),f=n[0].dts,p=n[n.length-1].dts;const S=p-f,x=S?Math.round(S/(c-1)):g||e.inputTimeScale/30;if(s){const B=f-T,U=B>x,j=B<-1;if((U||j)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Xt(B,!0)} ms (${B}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Xt(-B,!0)} ms (${B}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||T>=n[0].pts||Bt)){f=T;const J=n[0].pts-B;if(U)n[0].dts=f,n[0].pts=J;else{let X=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>J&&X);Z++){const oe=n[Z].pts;if(n[Z].dts-=B,n[Z].pts-=B,Z<n.length-1){const he=n[Z+1].pts,xe=n[Z].pts,Ce=he<=xe,ye=he<=oe;X=Ce==ye}}}this.log(`Video: Initial PTS/DTS adjusted: ${Xt(J,!0)}/${Xt(f,!0)}, delta: ${Xt(B,!0)} ms`)}}f=Math.max(0,f);let D=0,A=0,L=f;for(let B=0;B<c;B++){const U=n[B],j=U.units,J=j.length;let X=0;for(let Z=0;Z<J;Z++)X+=j[Z].data.length;A+=X,D+=J,U.length=X,U.dts<L?(U.dts=L,L+=x/4|0||1):L=U.dts,y=Math.min(U.pts,y),E=Math.max(U.pts,E)}p=n[c-1].dts;const R=A+4*D+8;let I;try{I=new Uint8Array(R)}catch(B){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:B,bytes:R,reason:`fail allocating video mdat ${R}`});return}const C=new DataView(I.buffer);C.setUint32(0,R),I.set(b.types.mdat,4);let $=!1,K=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let B=0;B<c;B++){const U=n[B],j=U.units;let J=0;for(let oe=0,he=j.length;oe<he;oe++){const xe=j[oe],Ce=xe.data,ye=xe.data.byteLength;C.setUint32(d,ye),d+=4,I.set(Ce,d),d+=ye,J+=4+ye}let X;if(B<c-1)g=n[B+1].dts-U.dts,X=n[B+1].pts-U.pts;else{const oe=this.config,he=B>0?U.dts-n[B-1].dts:x;if(X=B>0?U.pts-n[B-1].pts:x,oe.stretchShortVideoTrack&&this.nextAudioTs!==null){const xe=Math.floor(oe.maxBufferHole*r),Ce=(i?y+i*r:this.nextAudioTs+h)-U.pts;Ce>xe?(g=Ce-he,g<0?g=he:$=!0,this.log(`It is approximately ${Ce/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=he}else g=he}const Z=Math.round(U.pts-U.dts);K=Math.min(K,g),O=Math.max(O,g),H=Math.min(H,X),w=Math.max(w,X),o.push(An(U.key,g,J,Z))}if(o.length){if(Bt){if(Bt<70){const B=o[0].flags;B.dependsOn=2,B.isNonSync=0}}else if(gi&&w-H<O-K&&x/O<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let B=f;for(let U=0,j=o.length;U<j;U++){const J=B+o[U].duration,X=B+o[U].cts;if(U<j-1){const Z=J+o[U+1].cts;o[U].duration=Z-X}else o[U].duration=U?o[U-1].duration:x;o[U].cts=0,B=J}}}g=$||!g?x:g;const k=p+g;this.nextVideoTs=u=k-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const G={data1:b.moof(e.sequenceNumber++,f,ae(e,{samples:o})),data2:I,startPTS:(y-h)/r,endPTS:(E+g-h)/r,startDTS:(f-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,G}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return jh;case"ac3":return Xh;default:return qh}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const v=u.baseTime*n/u.timescale,T=v+t*n;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(T-(E+v))<9e3||Math.abs($e(p[0].pts,T)-(E+v))<20*h),p.forEach(function(w){w.pts=$e(w.pts,T)}),!s||E<0){const w=p.length;if(p=p.filter(k=>k.pts>=0),w!==p.length&&this.warn(`Removed ${p.length-w} of ${w} samples (initPTS ${v} / ${n})`),!p.length)return;r===0?E=0:i&&!f?E=Math.max(0,T-v):E=p[0].pts-v}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let k=0,M=E+v;k<p.length;k++){const N=p[k],G=N.pts,B=G-M,U=Math.abs(1e3*B/n);if(B<=-w*h&&f)k===0&&(this.warn(`Audio frame @ ${(G/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*B/n)} ms.`),this.nextAudioTs=E=G-v,M=G);else if(B>=w*h&&U<Wh&&f){let j=Math.round(B/h);for(M=G-j*h;M<0&&j&&h;)j--,M+=h;k===0&&(this.nextAudioTs=E=M-v),this.warn(`Injecting ${j} audio frames @ ${((M-v)/n).toFixed(3)}s due to ${Math.round(1e3*B/n)} ms gap.`);for(let J=0;J<j;J++){let X=Vh.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=N.unit.subarray()),p.splice(k,0,{unit:X,pts:M}),M+=h,k++}}N.pts=M,M+=h}}let S=null,x=null,D,A=0,L=p.length;for(;L--;)A+=p[L].unit.byteLength;for(let w=0,k=p.length;w<k;w++){const M=p[w],N=M.unit;let G=M.pts;if(x!==null){const U=g[w-1];U.duration=Math.round((G-x)/c)}else if(s&&e.segmentCodec==="aac"&&(G=E+v),S=G,A>0){A+=y;try{D=new Uint8Array(A)}catch(U){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(b.types.mdat,4))}else return;D.set(N,y);const B=N.byteLength;y+=B,g.push(An(!0,l,B,0)),x=G}const R=g.length;if(!R)return;const I=g[g.length-1];E=x-v,this.nextAudioTs=E+c*I.duration;const C=d?new Uint8Array(0):b.moof(e.sequenceNumber++,S/c,ae({},e,{samples:g}));e.samples=[];const $=(S-v)/n,K=this.nextAudioTs/n,O={data1:C,data2:D,startPTS:$,endPTS:K,startDTS:$,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:R};return this.isAudioContiguous=!0,O}}function $e(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function zh(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function ro(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=$e(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=$e(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function no(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=$e(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class Qh extends Ye{constructor(e,t,s,i){super("passthrough-remuxer",i),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,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=ua(e);if(t)Bl(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=In(r,le.AUDIO,this)),n&&(i=In(n,le.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};V(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=$l(d,f,this),y=f.audio?p[f.audio.id]:null,E=f.video?p[f.video.id]:null,v=ys(E,1/0),T=ys(y,1/0),S=ys(E,0,!0),x=ys(y,0,!0);let D=r,A=0;const L=y&&(!E||!l&&T<v||l&&l.trackId===f.audio.id),R=L?y:E;if(R){const M=R.timescale,N=R.start-r*M,G=L?f.audio.id:f.video.id;D=R.start/M,A=L?x-T:S-v,(n||!l)&&(Zh(l,D,r,A)||M!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${N/M} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${N}/${M}) trackId: ${G}`),l=null,g.initPTS=N,g.timescale=M,g.trackId=G)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=D,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const I=D-l.baseTime/l.timescale,C=I+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const $=!!f.audio,K=!!f.video;let H="";$&&(H+="audio"),K&&(H+="video");const O=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),w={data1:d,startPTS:I,startDTS:I,endPTS:C,endDTS:C,type:H,hasAudio:$,hasVideo:K,nb:1,dropped:0,encrypted:O};u.audio=$&&!K?w:void 0,u.video=K?w:void 0;const k=E?.sampleCount;if(k){const M=E.keyFrameIndex,N=M!==-1;w.nb=k,w.dropped=M===0||this.isVideoContiguous?0:N?M:k,w.independent=N,w.firstKeyFrame=M,N&&E.keyFrameStart&&(w.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${M}/${k} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return u.initSegment=g,u.id3=ro(s,r,l,l),i.samples.length&&(u.text=no(i,r,l)),u}}function ys(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function Zh(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function In(a,e,t){const s=a.codec;return s&&s.length>4?s:e===le.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Bs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let ut;try{ut=self.performance.now.bind(self.performance)}catch{ut=Date.now}const Ps=[{demux:Nh,remux:Qh},{demux:St,remux:Cs},{demux:wh,remux:Cs},{demux:Fh,remux:Cs}];Ps.splice(2,0,{demux:Oh,remux:Cs});class Ln{constructor(e,t,s,i,r,n){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=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=ut();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:v,initSegmentData:T}=c,S=Jh(n,t);if(S&&Kt(S.method)){const L=this.getDecrypter(),R=cr(S.method);if(L.isSync()){let I=L.softwareDecrypt(n,S.key.buffer,S.iv.buffer,R);if(s.part>-1){const $=L.flush();I=$&&$.buffer}if(!I)return r.executeEnd=ut(),mi(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(n,S.key.buffer,S.iv.buffer,R).then(I=>{const C=this.push(I,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const L=this.configureTransmuxer(n);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),r.executeEnd=ut(),mi(s)}(h||u||f||x)&&this.resetInitSegment(T,p,y,v,t),(h||f||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(n,S,g,d,s);this.asyncResult=os(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=ut(),D}flush(e){const t=e.transmuxing;t.executeStart=ut();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=ut();const u=[mi(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return os(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===Y.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=ut()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=Ps.length;u<d;u++){var n;if((n=Ps[u].demux)!=null&&n.probe(e,this.logger)){r=Ps[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new or(this.config)),e}}function Jh(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const mi=a=>({remuxResult:{},chunkMeta:a});function os(a){return"then"in a&&a.then instanceof Function}class eu{constructor(e,t,s,i,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=s,this.duration=i,this.defaultInitPts=r||null}}class tu{constructor(e,t,s,i,r,n){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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Rn=0;class ao{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Rn++,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 l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=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:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new dr,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=$r(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||nh()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=oh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=ah());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ce(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ln(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Rn++;const t=this.hls.config,s=$r(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ce(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),lh(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,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=n?n.start:r.start,y=r.decryptdata,E=this.frag,v=!(E&&r.cc===E.cc),T=!(E&&l.level===E.level),S=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=S===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!T&&(S===1||S===0&&(x===1||D&&x<=0)),L=self.performance.now();(T||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=L),n&&(x||!A)&&(n.stats.parsing.start=L);const R=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),I=new tu(v,A,c,T,p,R);if(!A||v||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Y.MAIN?"level":"track"}: ${l.level} id: ${l.id} 17 + discontinuity: ${v} 18 + trackSwitch: ${T} 19 + contiguous: ${A} 20 + accurateTimeOffset: ${c} 21 + timeOffset: ${p} 22 + initSegmentChange: ${R}`);const C=new eu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(f){const C=f.push(e,y,l,I);os(C)?C.then($=>{this.handleTransmuxComplete($)}).catch($=>{this.transmuxerError($,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);os(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const bn=100;class su extends ur{constructor(e,t,s){super(e,t,s,"audio-stream-controller",Y.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:s,initPTS:i,timescale:r,trackId:n}){if(s===Y.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=xa(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(bn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=P.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:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,le.AUDIO,Y.AUDIO));const h=this.getFwdBufferInfo(l,Y.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(u>=d&&!this.switchingTrack&&y<g[g.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,Y.MAIN,d)),!E){this.bufferFlushed=!0;return}let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Te(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ie.OK&&(this.mainFragLoading=v=null),v&&Te(v))){if(E.start>v.end){const S=this.fragmentTracker.getFragAtPos(y,Y.MAIN);S&&S.end>v.end&&(v=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(E.start>v.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new rs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(bn),this.state=P.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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||($a(r,l),r.alignedSliding||Ys(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new ao(this.hls,Y.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,E=y!==-1,v=new lr(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,f,u,"",s,i,h.totalduration,!1,v,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ga,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Y.MAIN&&Te(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==Y.AUDIO){!this.audioOnly&&s.type===Y.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Te(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,re({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===te.AUDIO_TRACK&&(this.state=P.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,Y.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:g,id3:f,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=d;l&&(l.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),c.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(d,c,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=ae({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=ae({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=Y.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===Ie.NOT_LOADED||i===Ie.PARTIAL){var r;if(!Te(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=P.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Ys(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;Ct({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,Dt)||($s(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,re({},e))}}class vr extends Ye{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,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Gr(s);return new Kr(o,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){jc(s,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=t;T.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,g=(i.edge-d)*1e3,f=Fa(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,D=x!==-1,A=T===S;D?A?(y=S+1,E=v?0:x):(y=T,E=v?x+1:i.maxPartIndex):y=S+1;const L=i.age,R=L+i.ageHeader;let I=Math.min(R-i.partTarget,i.targetduration*1.5);if(I>0){if(R>i.targetduration*3)this.log(`Playlist last advanced ${L.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&R-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;else{const C=Math.floor(I/i.targetduration);if(y+=C,E!==void 0){const $=Math.round(I%i.targetduration/i.partTarget);E+=$}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${I} skip sn ${C} to part ${E}`)}i.tuneInGoal=I}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),v||!A){i.requestScheduled=n,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Gr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=_s.No),new Kr(s,i,r)}checkRetry(e){const t=e.details,s=Gs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Re.RetryRequest||!i.resolved&&r===Re.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=ar(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function oo(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!ls(a[t].attrs,e[t].attrs))return!1;return!0}function ls(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function Vi(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class iu extends vr{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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=tt(c,o,Dt);if(d>-1)r=o[d];else{const g=tt(c,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var n;const d=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===te.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Ct(e,i,Dt))return i;const r=tt(e,this.tracksInGroup,Dt);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=mc(e,t.levels,s,n,Dt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=tt(e,s);if(n>-1)return s[n]}}}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 s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,re({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Ct(e,i,Dt)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(Ct({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},h,Dt))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(ls(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&$s(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class ru{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="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 i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.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?"<destroyed>":` 23 + ${this.list("video")} 24 + ${this.list("audio")} 25 + ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const _n=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,lo="HlsJsTrackRemovedError";class nu extends Error{constructor(e){super(e),this.name=lo}}class au extends Ye{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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,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:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=_l(It(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 s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ae(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ae({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=It(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Dn(s),ou(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) 26 + required tracks: ${ce(s,(c,l)=>c==="initSegment"?void 0:l)}; 27 + transfer tracks: ${ce(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!ra(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,g=h.id;if(d.hasFragments(g)||d.hasParts(g)){const y=Q.getBuffered(u);d.detectEvictedFragments(l,y,g,null,!0)}const f=pi(l),p=[l,u];this.sourceBuffers[f]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&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}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Dn(i),i.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 s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[pi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ru(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:g,levelCodec:f,container:p,metadata:y,supplemental:E}=u;let v=i[c];const T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],S=T!=null&&T.buffer?T:v,x=S?.pendingCodec||S?.codec,D=S?.levelCodec;v||(v=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:E,container:p,levelCodec:f,metadata:y,id:d});const A=bs(x,D),L=A?.replace(_n,"$1");let R=bs(g,f);const I=(h=R)==null?void 0:h.replace(_n,"$1");R&&A&&L!==I&&(c.slice(0,5)==="audio"&&(R=Bs(R,this.appendSource)),this.log(`switching codec ${x} to ${R}`),R!==(v.pendingCodec||v.codec)&&(v.pendingCodec=R),v.container=p,this.appendChangeType(c,p,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,Y.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&Q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,Y.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:g}=o,f=self.performance.now();u.start=f;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);const E=s.audio;let v=!1;r==="audio"&&E?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,S=T?.buffer;if(S&&d!=="initSegment"){const A=c||o,L=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const I=A.start+A.duration*.05,C=S.buffered,$=this.currentOp("video");!C.length&&!$?this.blockAudio(A):!$&&!Q.isBuffered(S,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(A)}else if(r==="video"){const R=A.end;if(L){const I=L.frag.start;(R>I||R<this.lastVideoAppendEnd||Q.isBuffered(S,I))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const L=(A=this.tracks[r])==null?void 0:A.buffer;L&&(v?this.updateTimestampOffset(L,x,.1,r,d,g):h!==void 0&&V(h)&&this.updateTimestampOffset(L,h,1e-6,r,d,g)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const L={};this.sourceBuffers.forEach(([R,I])=>{R&&(L[R]=Q.getBuffered(I))}),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:o,part:c,chunkMeta:l,parent:o.type,timeRanges:L})},onError:A=>{var L;const R={type:W.MEDIA_ERROR,parent:o.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},I=(L=this.media)==null?void 0:L.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)R.details=_.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)R.errorAction=Gt(!0);else if(A.name===lo&&this.sourceBufferCount===0)R.errorAction=Gt(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||I)&&(R.fatal=!0)}this.hls.trigger(m.ERROR,R)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===Y.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[le.AUDIOVIDEO]?r.push("audiovideo"):(n[le.AUDIO]&&r.push("audio"),n[le.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,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 s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.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===_.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;V(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(V(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(V(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=Q.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=Q.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return V(r)?{duration:r}:null;const n=this.media.duration,o=V(s.duration)?s.duration:0;return i>o&&i>n||!V(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(V(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ce(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.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:W.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ce(o)}`);try{const h=s.addSourceBuffer(l),u=pi(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&ss(s,"video")&&(i=zl(i,s));const r=bs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Bs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,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,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=V(i.duration)?i.duration:1/0,l=V(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new nu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.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:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Dn(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function ou(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function pi(a){return a==="audio"?1:0}class Tr{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 s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&V(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,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,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 s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Tr.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const lu={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Fe=lu,cu={HLS:"h"},hu=cu;class it{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof it?s:new it(s))),this.value=e,this.params=t}}const uu="Dict";function du(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function fu(a,e,t,s){return new Error(`failed to ${a} "${du(e)}" as ${t}`,{cause:s})}function rt(a,e,t){return fu("serialize",a,e,t)}class co{constructor(e){this.description=e}}const Cn="Bare Item",gu="Boolean";function mu(a){if(typeof a!="boolean")throw rt(a,gu);return a?"?1":"?0"}function pu(a){return btoa(String.fromCharCode(...a))}const yu="Byte Sequence";function Eu(a){if(ArrayBuffer.isView(a)===!1)throw rt(a,yu);return`:${pu(a)}:`}const vu="Integer";function Tu(a){return a<-999999999999999||999999999999999<a}function ho(a){if(Tu(a))throw rt(a,vu);return a.toString()}function Su(a){return`@${ho(a.getTime()/1e3)}`}function uo(a,e){if(a<0)return-uo(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const xu="Decimal";function Au(a){const e=uo(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rt(a,xu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Iu="String",Lu=/[\x00-\x1f\x7f]+/;function Ru(a){if(Lu.test(a))throw rt(a,Iu);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function bu(a){return a.description||a.toString().slice(7,-1)}const _u="Token";function Pn(a){const e=bu(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rt(e,_u);return e}function Hi(a){switch(typeof a){case"number":if(!V(a))throw rt(a,Cn);return Number.isInteger(a)?ho(a):Au(a);case"string":return Ru(a);case"symbol":return Pn(a);case"boolean":return mu(a);case"object":if(a instanceof Date)return Su(a);if(a instanceof Uint8Array)return Eu(a);if(a instanceof co)return Pn(a);default:throw rt(a,Cn)}}const Du="Key";function Yi(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw rt(a,Du);return a}function Sr(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${Yi(e)}`:`;${Yi(e)}=${Hi(t)}`).join("")}function fo(a){return a instanceof it?`${Hi(a.value)}${Sr(a.params)}`:Hi(a)}function Cu(a){return`(${a.value.map(fo).join(" ")})${Sr(a.params)}`}function Pu(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw rt(a,uu);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof it||(r=new it(r));let n=Yi(i);return r.value===!0?n+=Sr(r.params):(n+="=",Array.isArray(r.value)?n+=Cu(r):n+=fo(r)),n}).join(`,${s}`)}function go(a,e){return Pu(a,e)}const Ze="CMCD-Object",pe="CMCD-Request",bt="CMCD-Session",Et="CMCD-Status",ku={br:Ze,ab:Ze,d:Ze,ot:Ze,tb:Ze,tpb:Ze,lb:Ze,tab:Ze,lab:Ze,url:Ze,pb:pe,bl:pe,tbl:pe,dl:pe,ltc:pe,mtp:pe,nor:pe,nrr:pe,rc:pe,sn:pe,sta:pe,su:pe,ttfb:pe,ttfbb:pe,ttlb:pe,cmsdd:pe,cmsds:pe,smrt:pe,df:pe,cs:pe,ts:pe,cid:bt,pr:bt,sf:bt,sid:bt,st:bt,v:bt,msd:bt,bs:Et,bsd:Et,cdn:Et,rtp:Et,bg:Et,pt:Et,ec:Et,e:Et},wu={REQUEST:pe};function Ou(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function Fu(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?Ou(e):{};return s.reduce((r,n)=>{var o;const c=ku[n]||i[n]||wu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function Mu(a){return["ot","sf","st","e","sta"].includes(a)}function Nu(a){return typeof a=="number"?V(a):a!=null&&a!==""&&a!==!1}const mo="event";function Bu(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const ks=a=>Math.round(a),Wi=(a,e)=>Array.isArray(a)?a.map(t=>Wi(t,e)):a instanceof it&&typeof a.value=="string"?new it(Wi(a.value,e),a.params):(e.baseUrl&&(a=Bu(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Es=a=>ks(a/100)*100,Uu=(a,e)=>{let t=a;return e.version>=2&&(a instanceof it&&typeof a.value=="string"?t=new it([a]):typeof a=="string"&&(t=[a])),Wi(t,e)},$u={br:ks,d:ks,bl:Es,dl:Es,mtp:Es,nor:Uu,rtp:Es,tb:ks},po="request",yo="response",xr=["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"],Gu=["e"],Ku=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zs(a){return Ku.test(a)}function Vu(a){return xr.includes(a)||Gu.includes(a)||zs(a)}const Eo=["d","dl","nor","ot","rtp","su"];function Hu(a){return xr.includes(a)||Eo.includes(a)||zs(a)}const Yu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Wu(a){return xr.includes(a)||Eo.includes(a)||Yu.includes(a)||zs(a)}const qu=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ju(a){return qu.includes(a)||zs(a)}const Xu={[yo]:Wu,[mo]:Vu,[po]:Hu};function vo(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||po,r=s===1?ju:Xu[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===yo||i===mo;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ae({},$u,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const g=l[u];if(typeof g=="function"&&(d=g(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!V(d)&&(d=Date.now()),Nu(d)&&(Mu(u)&&typeof d=="string"&&(d=new co(d)),t[u]=d))}),t}function zu(a,e={}){const t={};if(!a)return t;const s=vo(a,e),i=Fu(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=go(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function Qu(a,e,t){return ae(a,zu(e,t))}const Zu="CMCD";function Ju(a,e={}){return a?go(vo(a,e),{whitespace:!1}):""}function ed(a,e={}){if(!a)return"";const t=Ju(a,e);return encodeURIComponent(t)}function td(a,e={}){if(!a)return"";const t=ed(a,e);return`${Zu}=${t}`}const kn=/CMCD=[^&#]+/;function sd(a,e,t){const s=td(e,t);if(!s)return a;if(kn.test(a))return a.replace(kn,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class id{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=i=>{try{this.apply(i,{ot:Fe.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===Fe.VIDEO||c===Fe.AUDIO||c==Fe.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.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 s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:hu.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ae(t,this.createData());const s=t.ot===Fe.INIT||t.ot===Fe.VIDEO||t.ot===Fe.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Qu(e.headers,t,r)):e.url=sd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Fe.TIMED_TEXT;if(e.sn==="initSegment")return Fe.INIT;if(t==="audio")return Fe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Fe.VIDEO:Fe.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Fe.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Fe.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const rd=3e5;class nd extends Ye{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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===Re.SendAlternateToPenaltyBox&&s.flags===Ue.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===_.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ce(r)} penalized: ${ce(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>rd&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ba(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===te.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===te.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new fe(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=To(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new rs({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${n}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${n}`);return p});t.push(...l),wn(this.audioTracks,s,c,n),wn(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const v={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,v),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wn(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ae({},n);return o.details=void 0,o.attrs=new fe(o.attrs),o.url=o.attrs.URI=To(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function To(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Vt extends Ye{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=Vt.CDMCleanupPromise?[Vt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Qt(this.config));const o=n.map(li).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=Ds(n);if(s!=="sinf"||o!==ge.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=Ae(new Uint8Array(i)),f=hr(JSON.parse(g).sinf),p=fa(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}const l=be(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let g=0;g<u.length;g++){const f=u[g],p=f.decryptdata;if(!p.keyId)continue;const y=be(p.keyId);if(Vs(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},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:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===ge.WIDEVINE&&s)return s}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,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Be?o(u):o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Ca===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=Uc(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ce(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${be(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=vs(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${be(e.decryptdata.keyId||[])} 28 + } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>li(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=li(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}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=Qt(this.config),s=e.map(Ds).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=ad(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=vs(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=On(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Be){const c=re({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Be(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Be){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${be(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=vs(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ds(e.keyFormat),r=i?[i]:Qt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Qt(this.config)),e.length===0)throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ce({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const f=n.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=vs(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new dr,h=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(v=>{l.eventNames().length?l.emit("error",v):this.handleError(v)}):y==="license-release"?e.keySystem===ge.FAIRPLAY&&this.updateKeySession(e,Bi("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${y}"`)},u=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=On(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(S=>y[S]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ce(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let v=y[o];if(v)u(v,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",u(v,e)},1e3)),this.log(`No status for keyId ${o} (${ce(y)}).`)}};we(e.mediaKeysSession,"message",h),we(e.mediaKeysSession,"keystatuseschange",d);const g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===ge.PLAYREADY&&r.length===16){const o=be(r);t[o]=s,_a(r)}const n=be(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{n(d.data)},onError:(d,g,f,p)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:re({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Bi(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Be({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==ge.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,we(s,"encrypted",this.onMediaEncrypted),we(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Me(e,"encrypted",this.onMediaEncrypted),Me(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 s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,At.clearKeyUriToKeyIdMap();const r=i.length;Vt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).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 s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${be(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(Gc(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Vt.CDMCleanupPromise=void 0;function vs(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return be(a.keyId)}function ad(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Be 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 On(a,e){const t=a==="output-restricted",s=t?_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Be({type:W.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class od{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 s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,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 So(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function xo(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ne.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){ne.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function $t(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function qi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=cd(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function ld(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function cd(a,e,t){const s=[],i=ld(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ws(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class hd extends vr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ws(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-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 s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;ws(s.textTracks).forEach(n=>{$t(n)})}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:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}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 s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=tt(o,n);if(h>-1)r=n[h];else{const u=tt(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||Ct(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(ls(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(Vi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===te.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Ct(e,s))return s;const i=tt(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=tt(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 s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ws(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>Vi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!V(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function ud(){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,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function ts(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Ht=.025;let qs=(function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a})({});function dd(a,e,t){return`${a.identifier}-${t+1}-${ts(e)}`}class fd{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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 yi(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,s=yi(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=V(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 yi(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)<Ht))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?qs.Range:qs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return gd(this)}}function yi(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Ht)?e.start:e.start+e.duration}function Ao(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Ei(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function gd(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function Ut(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class md{constructor(e,t,s,i){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=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,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=Ao(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 s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=Q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=Q.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 s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ut(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fn=.033;class pd extends Ye{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,g=h.cue.pre,f=h.cue.post;if(u&&!g)return-1;if(g&&!u||d&&!f)return 1;if(f&&!d)return-1;if(!u&&!g&&!d&&!f){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new fd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,g=h.cue.post,f=e[u-1]||null,p=h.appendInPlace,y=g?r:h.startOffset,E=h.duration,v=h.timelineOccupancy===qs.Range?E:0,T=h.resumptionOffset,S=f?.startTime===y,x=y+h.cumulativeDuration;let D=p?x+E:y+T;if(d||!g&&y<=0){const L=l;l+=v,h.timelineStart=x;const R=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:R,end:n},integrated:{start:L,end:l}})}else if(y<=r){if(!S){const I=y-c;if(I>Fn){const C=c,$=l;l+=I;const K=n;n+=I;const H={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+I,playout:{start:K,end:n},integrated:{start:$,end:l}};s.push(H)}else I>0&&f&&(f.cumulativeDuration+=I,s[s.length-1].end=y)}g&&(D=x),h.timelineStart=x;const L=l;l+=v;const R=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:R,end:n},integrated:{start:L,end:l}})}else return;const A=h.resumeTime;g||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const g=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:g,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Pt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Fn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=V(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Ht?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=Pt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Ht+h||Math.abs(l.end-s)<Ht+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function qe(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class yd{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ao(s,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){const v=this.assignAssetListError(e,_.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,v);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,g,f,p)=>{const y=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,_.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Mn(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function Ts(a,e){return`[${a}] Advancing timeline position to ${e}`}class Ed extends Ye{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} 29 + Schedule: ${c.map(p=>qe(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,g=null;n&&(d=this.updateItem(n,this.timelinePos),this.itemsMatch(n,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(v){Math.abs(E)>Ht&&this.warn(`${v} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(d,n),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new yd(e),this.schedule=new pd(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){Me(e,"play",this.onPlay),Me(e,"pause",this.onPause),Me(e,"seeking",this.onSeeking),Me(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;we(s,"seeking",this.onSeeking),we(s,"timeupdate",this.onTimeupdate),we(s,"play",this.onPlay),we(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);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 s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),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,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,g,f,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==qs.Point){const v=s(g);v?.interstitial===E&&(y+=v.assetItem.startOffset+v[p])}}else{const v=f==="bufferedPos"?n():e[f];y+=v-u.start}return y}return 0},r=(u,d)=>{var g;if(u!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(u),y=(f=e.schedule.items)==null?void 0:f[p];if(y){const E=y[d].start-y.start;return u+E}}return u},n=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[u])||0},c=(u,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),v=(f=e.schedule.items)==null?void 0:f[E],T=e.getBufferingPlayer(),S=T?.interstitial,x=S?.appendInPlace,D=y&&e.itemsMatch(y,v);if(y&&(x||D)){const A=s(e.playingAsset),L=A?.media||e.primaryMedia;if(L){const R=d==="primary"?L.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),I=u-R,C=(x?R:L.currentTime)+I;if(C>=0&&(!A||x||C<=A.duration)){L.currentTime=C;return}}}if(v){let A=u;if(d!=="primary"){const R=v[d].start,I=u-R;A=v.start+I}const L=!e.isInterstitial(v);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(L||v.event.appendInPlace)){const R=e.media||(x?T?.media:null);R&&(R.currentTime=A)}else if(y){const R=e.findItemIndex(y);if(E>R){const C=e.schedule.findJumpRestrictedIndex(R+1,E);if(C>R){e.setSchedulePosition(C);return}}let I=0;if(L)e.timelinePos=A,e.checkBuffer();else{const C=v.event.assetList,$=u-(v[d]||v).start;for(let K=C.length;K--;){const H=C[K];if(H.duration&&$>=H.startOffset&&$<H.startOffset+H.duration){I=K;break}}}e.setSchedulePosition(E,I)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var g;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),g=e.effectivePlayingItem;g&&g===d&&c(u+g.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return n()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(u);if(d.appendInPlace){const f=u.playout.start+u.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!V(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 s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ce(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),h=`${f}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ce(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(d===r&&g){const f=o&&e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}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 s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(Ts("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Ei(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=Ei(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(Ts("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&qe(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,u=this.playingAsset,d=u?.identifier,g=d?this.getAssetPlayer(d):null;if(g&&d&&(!this.eventItemsMatch(n,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const f=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${h.assetList.length} ${Ut(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:f,event:h,schedule:i.slice(0),scheduleIndex:e,player:g}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(d,r),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${qe(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const p=this.findItemIndex(r);this.advanceSchedule(p,f,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=n.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const f=Ei(h,s-1);if(h.isAssetPastPlayoutLimit(f)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=f}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${qe(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=h.assetList[s];if(!g){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=h.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${h}`),d=this.createAssetPlayer(h,g,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Mn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Mn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.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,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${qe(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Ts("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${qe(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Ts("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.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 s=this.hls.levels[t.level];if(!s.details)return;const i=re(re({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=re(re({},this.altSelection),{},{audio:s});return}const r=re(re({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=re(re({},this.altSelection),{},{subtitles:s});return}const r=re(re({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Hr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=Q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${qe(e)} (was ${qe(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=Q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const g=r.event;if(u-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${qe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.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 s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:dd(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ae({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const S=this.timelinePos-t.timelineStart;if(S>1){const x=t.duration;x&&S<x&&(h=S)}}const u=t.identifier,d=re(re({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=ae({},g,{contentId:ts(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const f=new md(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0;const y=S=>{if(S.live){var x;const L=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:L},I=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,I,s,L.message);return}const D=S.edge-S.fragmentStart,A=t.duration;(p||A===null||D>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${D}`),t.duration=D,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(S,{details:x})=>y(x)),f.on(m.LEVEL_PTS_UPDATED,(S,{details:x})=>y(x)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(S,x)=>{const D=this.getAssetPlayer(u);if(D&&x.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=x.tracks;const A=this.primaryMedia;this.bufferingAsset===D.assetItem&&A&&!D.media&&this.bufferAssetPlayer(D,A)}};f.on(m.BUFFER_CODECS,E);const v=()=>{var S;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),A=(S=this.schedule.items)==null?void 0:S[D];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};f.on(m.BUFFERED_TO_END,v);const T=S=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,S)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(S,x)=>{if(!this.schedule)return;const D=this.getAssetPlayer(u);if(x.details===_.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ut(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&qe(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Ut(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const u=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!ra(u,e.tracks)){const d=new Error(`Asset ${Ut(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),g={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===_.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&Ut(n)} ${e.error}`),!this.schedule)return;const o=n?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=ae({},e,{fatal:!1,errorAction:Gt(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${qe(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===n;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(d){var f;const p=this.schedule.findEventIndex(n),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.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(y)}this.setSchedulePosition(p)}else if(g?.identifier===n){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case _.ASSET_LIST_PARSING_ERROR:case _.ASSET_LIST_LOAD_ERROR:case _.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case _.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Nn=500;class vd extends ur{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",Y.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=P.IDLE,this.setInterval(Nn),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:s,success:i}=t;if(this.fragContextChanged(s)||(Te(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,Y.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===Y.SUBTITLE&&(t.details===_.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&oo(this.levels,t)){this.levels=t.map(s=>new rs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new rs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Y.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Nn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)n.hasProgramDateTime&&u.hasProgramDateTime?(Ys(n,u),l=n.fragmentStart):d&&(l=d.start,$i(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,$i(n,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(Pt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Kt(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,cr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=Q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const v=i.maxFragLookUpTolerance,T=o>g-v?0:v;f=Pt(p,u,Math.max(u[0].start,o),T),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,E=u[y-1];if(E&&E.cc===f.cc&&this.fragmentTracker.getState(E)===Ie.NOT_LOADED&&(f=E),this.fragmentTracker.getState(f)===Ie.NOT_LOADED){const v=this.mapToInitFragWhenRequired(f);v&&this.loadFragment(v,s,o)}}}loadFragment(e,t,s){Te(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Td(this.tracksBuffered[this.currentTrackId]||[])}}class Td{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Sd={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},Io=a=>String.fromCharCode(Sd[a]||a),je=15,ct=100,xd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ad={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Id={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ld={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Rd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class bd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ne.log(`${this.time} [${e}] ${s}`)}}}const _t=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Lo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class _d{constructor(){this.uchar=" ",this.penState=new Lo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Dd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Lo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ct;t++)this.chars.push(new _d);this.logger=e}equals(e){for(let t=0;t<ct;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ct;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ct;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ct&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ct)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Io(e);if(this.pos>=ct){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<ct;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<ct;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class vi{constructor(e){this.rows=[],this.currRow=je-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<je;t++)this.rows.push(new Dd(e));this.logger=e}reset(){for(let e=0;e<je;e++)this.rows[e].clear();this.currRow=je-1}equals(e){let t=!0;for(let s=0;s<je;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<je;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<je;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ce(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<je;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ce(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 s="",i=-1;for(let r=0;r<je;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(` 30 + `)),s}getTextAndFormat(){return this.rows}}class Bn{constructor(e,t,s){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 vi(s),this.nonDisplayedMemory=new vi(s),this.lastOutputScreen=new vi(s),this.currRollUpRow=this.displayedMemory.rows[je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[je-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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 s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ce(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 Un{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Pd(),this.logger=void 0;const i=this.logger=new bd;this.channels=[null,new Bn(e,t,i),new Bn(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+_t([t[s],t[s+1]])+"] -> ("+_t([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Cd(i,r,c)){Ss(null,null,c),this.logger.log(3,()=>"Repeated command ("+_t([i,r])+") is dropped");continue}Ss(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Ss(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+_t([i,r])+" orig: "+_t([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+_t([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?xd[e]:Id[e]:s=n===1?Ad[e]:Ld[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Io(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+_t(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Rd[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ss(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Ss(a,e,t){t.a=a,t.b=e}function Cd(a,e,t){return t.a===a&&t.b===e}function Pd(){return{a:null,b:null}}var Ar=(function(){if(Hs!=null&&Hs.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function n(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",g=!1,f=o,p=c,y=l,E=null,v="",T=!0,S="auto",x="start",D=50,A="middle",L=50,R="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return g},set:function(I){g=!!I}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");f=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(I){y=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return v},set:function(I){const C=s(I);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");v=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(I){T=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return S},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");x=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return L},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");L=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return R},set:function(I){const C=i(I);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");R=C,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n})();class kd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ro(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.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 wd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function bo(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const ji=new Ar(0,0,""),xs=ji.align==="middle"?"middle":"center";function Od(a,e,t){const s=a;function i(){const o=Ro(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new wd;bo(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(d,f[0]),l.percent(d,f[0])&&l.set("snapToLines",!1),l.alt(d,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",xs,"end"]);break;case"position":f=g.split(","),l.percent(d,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",xs,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,g);break;case"align":l.alt(d,g,["start",xs,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&ji.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",xs);let u=l.get("position","auto");u==="auto"&&ji.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function _o(a){return a.replace(/<br(?: \/)?>/gi,` 31 + `)}class Fd{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new kd,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 s(){let r=t.buffer,n=0;for(r=_o(r);n<r.length&&r[n]!=="\r"&&r[n]!==` 32 + `;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===` 33 + `&&++n,t.buffer=r.slice(n),o}function i(r){bo(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Ar(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Od(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!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+=` 34 + `),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+=` 35 + 36 + `,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 Md=/\r\n|\n\r|\n|\r/g,Ti=function(e,t,s=0){return e.slice(s,s+t.length)===t},Nd=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!V(t)||!V(s)||!V(i)||!V(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function Ir(a,e,t){return ts(a.toString())+ts(e.toString())+ts(t)}const Bd=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function Ud(a,e,t,s,i,r,n){const o=new Fd,c=Ve(new Uint8Array(a)).trim().replace(Md,` 37 + `).split(` 38 + `),l=[],h=e?Yh(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,p=!0;o.oncue=function(y){const E=t[s];let v=t.ccOffset;const T=(d-h)/9e4;if(E!=null&&E.new&&(g!==void 0?v=t.ccOffset=E.start:Bd(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}v=T-t.presentationOffset}const S=y.endTime-y.startTime,x=$e((y.startTime+v-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+S,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=Ir(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){n(f);return}r(l)},c.forEach(y=>{if(p)if(Ti(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{Ti(E,"LOCAL:")?u=E.slice(6):Ti(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=Nd(u)/1e3}catch(E){f=E}return}else y===""&&(p=!1);o.parse(y+` 39 + `)}),o.flush()}const Si="stpp.ttml.im1t",Do=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Co=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,$d={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(a,e,t,s){const i=ee(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ve(o)),n=Hh(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Gd(o,n)))}catch(o){s(o)}}function Gd(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Gn(xi(i,"styling","style")),l=Gn(xi(i,"layout","region")),h=xi(i,"body","[begin]");return[].map.call(h,u=>{const d=Po(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=Ii(u.getAttribute("begin"),n),f=Ii(u.getAttribute("dur"),n);let p=Ii(u.getAttribute("end"),n);if(g===null)throw Kn(u);if(p===null){if(f===null)throw Kn(u);p=g+f}const y=new Ar(g-e,p-e,d);y.id=Ir(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],v=c[u.getAttribute("style")],T=Kd(E,v,c),{textAlign:S}=T;if(S){const x=$d[S];x&&(y.lineAlign=x),y.align=S}return ae(y,T),y}).filter(u=>u!==null)}function xi(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gn(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Po(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+` 40 + `:(r=s.childNodes)!=null&&r.length?Po(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Kd(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=Ai(e,s,c)||Ai(a,s,c)||Ai(i,s,c);return l&&(o[c]=l),o},{})}function Ai(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Kn(a){return new Error(`Could not parse ttml timestamp ${a}`)}function Ii(a,e){if(!a)return null;let t=Ro(a);return t===null&&(Do.test(a)?t=Vd(a,e):Co.test(a)&&(t=Hd(a,e))),t}function Vd(a,e){const t=Do.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Hd(a,e){const t=Co.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class As{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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Yd{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=Hn(),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 As(this,"textTrack1"),t=new As(this,"textTrack2"),s=new As(this,"textTrack3"),i=new As(this,"textTrack4");this.cea608Parser1=new Un(1,e,t),this.cea608Parser2=new Un(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=Wd(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===Y.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.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:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Vn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,$t(s[e]),So(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{$t(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Hn(),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 s=0;s<t.length;s++)$t(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Si);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(oo(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?ws(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Vn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)$t(h);else{const u=ko(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.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 n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Y.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===Y.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Si?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;$n(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?He(s.initSegment.data,new Uint8Array(i)).buffer:i;Ud(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||$n(t,this.initPTS[e.cc],()=>{s.textCodec=Si,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>xo(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===Y.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===Y.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>qi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>qi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function ko(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Vn(a,e){return!!a&&a.kind===ko(e)&&Vi(e,a)}function Wd(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Hn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const qd=/\s/,jd={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)qd.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=_o(l.trim()),f=Ir(e,t,g);a!=null&&(u=a.cues)!=null&&u.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=d+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>xo(a,d))),i}};function Xd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const zd=/(\d+)-(\d+)\/(\d+)/;class Yn{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||ef,this.controller=new self.AbortController,this.stats=new sr}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,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=Qd(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&V(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new tf(y||"fetch, bad network response",p,u)}i.loading.first=g,i.total=Jd(u.headers)||i.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&V(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,f):n?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:u,code:f.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!V(t.highWaterMark)&&E(i,e,u,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=u&&u.code||0,f=u?u.message:null;(d=this.callbacks)==null||d.onError({code:g,text:f},e,u?u.details:null,i)})}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,s,i=0,r){const n=new Ga,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Qd(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ae({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Zd(a){const e=zd.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Jd(a){const e=a.get("Content-Range");if(e){const s=Zd(e);if(V(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function ef(a,e){return new self.Request(a.url,e)}class tf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const sf=/^age:\s*[\d.]+\s*$/im;class wo{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 sr,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,s){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=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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),s.timeout=r&&V(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=h??t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(n=this.callbacks)==null?void 0:n.onProgress;y&&y(s,e,f,t);const E={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,g={url:e.url,data:void 0,code:l};if(Ks(u,d,!1,g))this.retry(u);else{var c;ne.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ks(e,t,!0))this.retry(e);else{var s;ne.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=ar(e,s.retry),s.retry++,ne.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.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&&sf.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 rf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},nf=re(re({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:wo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:pc,bufferController:au,capLevelController:Tr,errorController:Sc,fpsController:od,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:Ca,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:rf},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},af()),{},{subtitleStreamController:vd,subtitleTrackController:hd,timelineController:Yd,audioStreamController:su,audioTrackController:iu,emeController:Vt,cmcdController:id,contentSteeringController:nd,interstitialsController:Ed});function af(){return{cueHandler:jd,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 of(a,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 s=Xi(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${n}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const g=s[o].default;switch(e[o]={default:g},h){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ce(e[o])}`)}),re(re({},s),e)}function Xi(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Xi):Object.keys(a).reduce((e,t)=>(e[t]=Xi(a[t]),e),{}):a}function lf(a,e){const t=a.loader;t!==Yn&&t!==wo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Xd()&&(a.loader=Yn,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Os=2,cf=.1,hf=.05,uf=100;class df extends La{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.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(uf),this.mediaSource=t.mediaSource;const s=this.media=t.media;we(s,"playing",this.onMediaPlaying),we(s,"waiting",this.onMediaWaiting),we(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Me(s,"playing",this.onMediaPlaying),Me(s,"waiting",this.onMediaWaiting),Me(s,"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 s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!Q.getBuffered(n).length){this.nudgeRetry=0;return}const u=Q.bufferInfo(n,e,0),d=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const D=Wn(this.hls.inFlightFragments,e),A=u.len>Os,L=!d||D||d-e>Os&&!g.getPartialFragment(e);if(A||L)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,R=!!(f!=null&&f.live)?f.targetduration*2:Os,I=Is(e,g);if(A>0&&(A<=R||I)){n.paused||this._trySkipBufferHole(I);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let v=this.stalled;if(v===null)if(E>0&&y-E<p)v=this.stalled=E;else{this.stalled=y;return}const T=y-v;if(!o&&(T>=p||E)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const x=Q.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=Q.bufferedInfo(Q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=Q.timeRangesToArray(i),o=Q.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=Q.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=Is(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=Q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Is(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,Y.MAIN),n=s.getFragAtPos(i,Y.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ce(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=Q.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-n;if(d>0&&(h||u)){if(d>r.maxBufferHole){let f=!1;if(n===0){const p=s.getAppendedFrag(0,Y.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Wn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const v=Is(E,s);if(v)E+=v.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(c+hf,n+cf);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${g}`),p={type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wn(a,e){const t=qn(a.main);if(t&&t.start<=e)return t;const s=qn(a.audio);return s&&s.start<=e?s:null}function qn(a){if(!a)return null;switch(a.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return a.frag}function Is(a,e){return e.getAppendedFrag(a,Y.MAIN)||e.getPartialFragment(a)}const ff=.25;function zi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Li(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ce(i?re({type:i},s):s))}return r}const Ls=(()=>{const a=zi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class gf{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 s;this.media=t.media,((s=t.overrides)==null?void 0:s.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&&$t(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;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return So(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=zi();if(n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===Ke.emsg&&!s||!i)continue;const l=ja(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Ls&&(u=Ls),u-h<=0&&(u=h+ff);for(let g=0;g<l.length;g++){const f=l[g];if(!Xa(f)){this.updateId3CueEnds(h,c);const p=Li(n,h,u,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===Ls&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===Ke.audioId3&&c:i==="video"?l=h=>h.type===Ke.emsg&&o:l=h=>h.type===Ke.audioId3&&c||h.type===Ke.emsg&&o,qi(r,t,s,l)}}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:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=zi();if(s&&i&&!n){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=Li(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var g;const E=p[y],v=(g=u[E])==null?void 0:g.cues;delete u[E],v&&Object.keys(v).forEach(T=>{const S=v[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(h.length===0||!V(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],v=E.startTime,T=u[y],S=T?.cues||{};let x=T?.durationKnown||!1,D=Ls;const{duration:A,endDate:L}=E;if(L&&A!==null)D=v+A,x=!0;else if(E.endOnNext&&!x){const I=h.reduce((C,$)=>{if($!==E.id){const K=l[$];if(K.class===E.class&&K.startDate>E.startDate&&(!C||E.startDate<C.startDate))return K}return C},null);I&&(D=I.startTime,x=!0)}const R=Object.keys(E.attr);for(let I=0;I<R.length;I++){const C=R[I];if(!Oc(C))continue;const $=S[C];if($)x&&!(T!=null&&T.durationKnown)?$.endTime=D:Math.abs($.startTime-v)>.01&&($.startTime=v,$.endTime=D);else if(o){let K=E.attr[C];Fc(C)&&(K=na(K));const O=Li(o,v,D,{key:C,data:K},Ke.dateRange);O&&(O.id=y,this.id3Track.addCue(O),S[C]=O,n&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:S,dateRange:E,durationKnown:x}}}}}class mf{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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,g)}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:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}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 s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}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 s=e.buffered.length;return(s?e.buffered.end(s-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 s;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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 pf extends vr{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 s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:g}=h;d&&(h.audioCodec=d=Bs(d,s)||void 0),g&&(g=h.videoCodec=Ql(g));const{width:f,height:p,unknownCodecs:y}=h,E=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!d),E||d&&!this.isAudioSupported(d)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":x,RESOLUTION:D,"VIDEO-RANGE":A}=u,R=`${`${x||"."}-`}${h.bitrate}-${D}-${T}-${v}-${A}-${S}`;if(r[R])if(r[R].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const I=n[R]+=1;h.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const C=this.createLevel(h);r[R]=C,i.push(C)}else r[R].addGroupId("audio",u.AUDIO),r[R].addGroupId("text",u.SUBTITLES);else{const I=this.createLevel(h);r[R]=I,n[R]=1,i.push(I)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new rs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=ya(i,[])}return t}isAudioSupported(e){return ss(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ss(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:v,videoRange:T,width:S,height:x})=>(!!v||!!(S&&x))&&oc(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ce(t.levels.map(x=>x.attrs.CODECS).filter((x,D,A)=>A.indexOf(x)===D))}`,this.warn(T),v+=` (${T})`);const S=new Error(v);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),jn(o)),t.subtitles&&(c=t.subtitles,jn(c));const u=l.slice(0);l.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return Us.indexOf(v.videoRange)-Us.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){const S=Br(v.videoCodec),x=Br(T.videoCodec);if(S!==x)return x-S}if(v.uri===T.uri&&v.codecSet!==T.codecSet){const S=Ns(v.codecSet),x=Ns(T.codecSet);if(S!==x)return x-S}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let v=0;v<u.length;v++)if(u[v].pathwayId===l[0].pathwayId){d=u[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===d){var g;this._firstLevel=v;const T=d.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const x=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);x>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}const f=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!f&&o.some(v=>!!v.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}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 h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i?.details,l);this.loadPlaylist(h)}}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(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Y.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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 s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ba(s),this._levels=s,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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=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:s}))}}function jn(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Oo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Fo(){if(!It())return!1;const e=Oo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function yf(){if(!Fo())return!1;const a=It();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(is(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(is(e,"audio"))))}function Ef(){var a;const e=Oo();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const vf=100;class Tf extends ur{constructor(e,t,s){super(e,t,s,"stream-controller",Y.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 i=this.media,r=i?i.currentTime:null;if(r===null||!V(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,Y.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.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:s,hls:i}=this;if(this.stopLoad(),this.setInterval(vf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.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 l=n.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&Te(g)&&this.fragmentTracker.getState(g)!==Ie.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,E=l.fragments[y-1];E&&g.cc===E.cc&&(g=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,E=(y===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,Y.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,Y.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ie.NOT_LOADED||i===Ie.PARTIAL?Te(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,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Y.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 s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;we(s,"playing",this.onMediaPlaying),we(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Me(s,"playing",this.onMediaPlaying),Me(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Ef(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=Q.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:g}=Q.bufferedInfo(u.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new ao(this.hls,Y.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new lr(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,p),E=this.initPTS[s.cc];g.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if($s(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=$s(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===Y.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Te(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&Q.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===te.LEVEL&&(this.state=P.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case _.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 _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==le.AUDIO||!this.altAudio){const s=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,Y.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 s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=Q.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:h,text:u,id3:d,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){const y=g.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,S,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}const E=g.initPTS,v=g.timescale,T=this.initPTS[o.cc];if(V(E)&&(!T||T.baseTime!==E||T.timescale!==v)){const S=g.trackId;this.initPTS[o.cc]={baseTime:E,timescale:v,trackId:S},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:v,trackId:S})}}if(h&&f){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],E=o.sn===f.startSN,v=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:x,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:S,startDTS:x,endDTS:D};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),L=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,R=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&L<R-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,S,o.start,D,!0)}else E&&T-(f.appliedTimelineOffset||0)>Os&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,S,x,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||v)}else if(E||v)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:v,endDTS:T}=p;c&&(c.elementaryStreams[le.AUDIO]={startPTS:y,endPTS:E,startDTS:v,endDTS:T}),o.setElementaryStreamInfo(le.AUDIO,y,E,v,T),this.bufferFragmentData(p,o,c,r)}if(f&&d!=null&&d.samples.length){const y={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&u){const y={id:t,frag:o,details:f,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${Te(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=bs(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=Y.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=Y.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.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(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Y.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.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=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(Q.isBuffered(e,s)?t=this.getAppendedFrag(s):Q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.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 V(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(V(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Pt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}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 Sf extends Ye{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.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=_.KEY_LOAD_ERROR,s,i,r){return new ht({type:W.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Te(e)||!Te(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=Ds(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Qt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}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 s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=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,_.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=Ri(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+be(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={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,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=Ul(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${be(o)}`),At.setKeyIdForUri(e.decryptdata.uri,o)):(o=At.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${be(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Te(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,p)=>{const{frag:y,keyInfo:E}=f,v=Ri(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,n({frag:y,keyInfo:E})},onError:(d,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,re({url:c.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ri(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Ri(a){if(a.keyFormat!==_e.FAIRPLAY){const e=a.keyId;if(e)return be(e)}return a.uri}function Xn(a){const{type:e}=a;switch(e){case te.AUDIO_TRACK:return Y.AUDIO;case te.SUBTITLE_TRACK:return Y.SUBTITLE;default:return Y.MAIN}}function bi(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class xf{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,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:te.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[te.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[te.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===te.MANIFEST?r=s.manifestLoadPolicy.default:r=ae({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),V((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===te.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===te.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===te.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ae({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=l.data;h.parsing.start=performance.now(),st.isMediaPlaylist(f)||u.type!==te.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,g):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=bi(e,s),c=st.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f}=c;this.variableList=f,h.forEach(v=>{const{unknownCodecs:T}=v;if(T){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:x,videoCodec:D}=v;for(let A=T.length;A--;){const L=T[A];ss(L,"audio",S)?(v.audioCodec=x=x?`${x},${L}`:L,Yt.audio[x.substring(0,4)]=2,T.splice(A,1)):ss(L,"video",S)&&(v.videoCodec=D=D?`${D},${L}`:L,Yt.video[D.substring(0,4)]=2,T.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=st.parseMasterPlaylistMedia(n,o,c);p.length&&!p.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new fe({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,h=bi(e,s),u=V(c)?c:V(o)?o:0,d=Xn(s),g=st.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===te.MANIFEST){const f={attrs:new fe({}),bitrate:0,details:g,name:"",url:h};g.requestScheduled=t.loading.start+Fa(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===te.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===te.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===te.AUDIO_TRACK||e.type===te.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=_.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case te.MANIFEST:c=s?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,l=!0;break;case te.LEVEL:c=s?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,l=!1;break;case te.AUDIO_TRACK:c=s?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case te.SUBTITLE_TRACK:c=s?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:W.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=t?.url||e.url;u.response=re({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:g}=i,f=bi(t,i),p=Xn(i);let y=typeof i.level=="number"&&p===Y.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case te.MANIFEST:case te.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const v=o.levels.indexOf(h);v>-1&&(y=v)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:g,withoutMultiVariant:c===te.MANIFEST});break;case te.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break;case te.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:g});break}}}class De{static get version(){return ns}static isMSESupported(){return Fo()}static isSupported(){return yf()}static getMediaSource(){return It()}static get Events(){return m}static get MetadataSchema(){return Ke}static get ErrorTypes(){return W}static get ErrorDetails(){return _}static get DefaultConfig(){return De.defaultConfig?De.defaultConfig:nf}static set DefaultConfig(e){De.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 dr,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=bl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=of(De.DefaultConfig,e,t);this.userConfig=e,s.progressive&&lf(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new xc(this),d=s.interstitialsController,g=d?this.interstitialsController=new d(this,De):null,f=this.bufferController=new r(this,u),p=this.capLevelController=new n(this),y=new c(this),E=new xf(this),v=s.contentSteeringController,T=v?new v(this):null,S=this.levelController=new pf(this,T),x=new gf(this),D=new Sf(this.config,this.logger),A=this.streamController=new Tf(this,u,D),L=this.gapController=new df(this,u);p.setStreamController(A),y.setStreamController(A);const R=[E,S,A];g&&R.splice(1,0,g),T&&R.splice(1,0,T),this.networkControllers=R;const I=[h,f,L,p,y,x,u];this.audioTrackController=this.createController(s.audioTrackController,R);const C=s.audioStreamController;C&&R.push(this.audioStreamController=new C(this,u,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,R);const $=s.subtitleStreamController;$&&R.push(this.subtititleStreamController=new $(this,u,D)),this.createController(s.timelineController,I),D.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(mf,I),this.coreComponents=I,R.push(l);const K=l.onErrorOut;typeof K=="function"&&this.on(m.ERROR,K,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),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:W.OTHER_ERROR,details:_.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,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}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,s=this._url,i=this._url=tr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||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?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Y.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Y.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Y.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=ud()),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){ac(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 s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}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 s=Ta(t);return Ea(e,s,navigator.mediaCapabilities)}}De.defaultConfig=void 0;var Af=Oe('<div class="error-overlay svelte-zbxgh1"> </div>'),If=Oe('<div class="player-wrapper svelte-zbxgh1" role="region"><video playsinline="" class="svelte-zbxgh1"><track kind="captions"/></video> <div><div class="scrub-bar svelte-zbxgh1" role="slider"><div><img alt="scrub" class="frog-sprite svelte-zbxgh1" draggable="false"/></div></div></div> <button><img src="/frogeye.png" alt="fullscreen" class="frogeye svelte-zbxgh1"/></button> <!></div>',2);function Lf(a,e){Zi(e,!0);let t=ie(void 0),s=null,i=ie(""),r=ie(!1),n=ie(0),o=ie(0),c=ie(void 0),l=ie(!1),h=ie(0),u=ie(0),d=ie(!1),g=0,f=ie(!0),p=null,y=ie(!1);function E(){s&&(s.destroy(),s=null)}function v(){if(!F(t)||!e.src)return;E(),q(i,""),!!F(t).canPlayType("application/vnd.apple.mpegurl")?(F(t).addEventListener("loadedmetadata",()=>{F(t)?.play().catch(()=>{})}),F(t).src=e.src,F(t).load()):De.isSupported()?(s=new De({enableWorker:!0,lowLatencyMode:!1}),s.loadSource(e.src),s.attachMedia(F(t)),s.on(De.Events.MANIFEST_PARSED,()=>{F(t)?.play().catch(()=>{})}),s.on(De.Events.ERROR,(M,N)=>{if(console.error("HLS error:",N),N.fatal)switch(N.type){case De.ErrorTypes.NETWORK_ERROR:q(i,`Network error: ${N.details}`),s?.startLoad();break;case De.ErrorTypes.MEDIA_ERROR:q(i,`Media error: ${N.details}`),s?.recoverMediaError();break;default:q(i,`Fatal error: ${N.details}`),E();break}})):q(i,"HLS playback is not supported in this browser.")}ii(()=>(e.src,F(t)&&v(),E)),ii(()=>(document.addEventListener("fullscreenchange",R),()=>document.removeEventListener("fullscreenchange",R)));let T=0;function S(){if(!F(t)||F(l))return;q(n,F(t).currentTime,!0),q(o,F(t).duration||0,!0);const k=F(o)>0?F(n)/F(o):0,M=k-T;Math.abs(M)>.002&&(q(u,F(u)===0?1:0,!0),q(d,M<0),T=k),q(h,k,!0)}function x(){q(r,!0)}function D(){q(r,!1)}function A(){F(t)&&(F(t).paused?F(t).play().catch(()=>{}):F(t).pause())}function L(){const k=F(t)?.closest(".player-wrapper");k&&(document.fullscreenElement?document.exitFullscreen?.().catch(()=>{}):k.requestFullscreen?.().catch(()=>{}))}function R(){q(y,!!document.fullscreenElement)}function I(k){if(!F(c))return;const M=F(c).getBoundingClientRect(),N=Math.max(0,Math.min(1,(k.clientX-M.left)/M.width)),G=N-g;Math.abs(G)>.02&&(q(u,F(u)===0?1:0,!0),q(d,G<0),g=N),q(h,N,!0),F(t)&&F(o)>0&&(F(t).currentTime=N*F(o),q(n,N*F(o)))}function C(k){k.preventDefault(),q(l,!0),I(k),window.addEventListener("mousemove",K),window.addEventListener("mouseup",H)}function $(k){k.preventDefault(),k.stopPropagation(),q(l,!0),window.addEventListener("mousemove",K),window.addEventListener("mouseup",H)}function K(k){F(l)&&I(k)}function H(){q(l,!1),window.removeEventListener("mousemove",K),window.removeEventListener("mouseup",H)}function O(k){k.code==="Space"&&F(t)&&(k.preventDefault(),A())}ii(()=>(window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)));function w(){q(f,!0),p&&clearTimeout(p),p=setTimeout(()=>{F(r)&&q(f,!1)},2500)}Fs(a,{seed:"player-main",padding:4,children:(k,M)=>{var N=If(),G=de(N);Ms(G,ye=>q(t,ye),()=>F(t));var B=ve(G,2);let U;var j=de(B);dt(j,"aria-valuemin",0),dt(j,"tabindex",0);var J=de(j);let X;var Z=de(J);ue(J),ue(j),Ms(j,ye=>q(c,ye),()=>F(c)),ue(B);var oe=ve(B,2);let he;var xe=ve(oe,2);{var Ce=ye=>{var nt=Af(),kt=de(nt,!0);ue(nt),Ge(()=>Xe(kt,F(i))),ke(ye,nt)};mt(xe,ye=>{F(i)&&ye(Ce)})}ue(N),Ge(()=>{U=Zt(B,1,"controls svelte-zbxgh1",null,U,{visible:F(f)||!F(r)}),dt(j,"aria-valuenow",F(n)),dt(j,"aria-valuemax",F(o)),X=Zt(J,1,"scrub-frog svelte-zbxgh1",null,X,{flipped:F(d)}),Rs(J,`left: ${F(h)*100}%;`),dt(Z,"src",F(u)===0?"/froggiestand.png":"/froggiejump.png"),he=Zt(oe,1,"fullscreen-btn svelte-zbxgh1",null,he,{visible:F(f)||!F(r)}),dt(oe,"title",F(y)?"Exit fullscreen":"Fullscreen")}),ft("mousemove",N,w),xt("mouseenter",N,w),xt("mouseleave",N,()=>{F(r)&&q(f,!1)}),xt("timeupdate",G,S),xt("play",G,x),xt("pause",G,D),ft("click",G,A),ft("mousedown",j,C),ft("mousedown",J,$),ft("click",oe,L),ke(k,N)},$$slots:{default:!0}}),Ji()}er(["mousemove","click","mousedown"]);var Rf=Oe('<img class="thumb-img svelte-1nxalmg"/>'),bf=Oe('<div class="loading-spinner svelte-1nxalmg"><div class="spinner svelte-1nxalmg"></div></div>'),_f=Oe('<div class="scrub-bar svelte-1nxalmg"><div class="scrub-bar-fill svelte-1nxalmg"></div></div>'),Df=Oe('<div><img alt="hop" class="frog-sprite svelte-1nxalmg"/></div>'),Cf=Oe('<div class="thumbnail svelte-1nxalmg" role="img"><!> <canvas></canvas> <!> <!> <!> <div class="thumb-shadow svelte-1nxalmg"></div></div>'),Pf=Oe('<span class="duration-badge svelte-1nxalmg"> </span> <div class="thumb-wrapper svelte-1nxalmg"><!></div> <div class="info svelte-1nxalmg"><h3 class="title svelte-1nxalmg"> </h3> <p class="creator svelte-1nxalmg"> </p> <p class="date svelte-1nxalmg"> </p></div>',1),kf=Oe('<button class="card svelte-1nxalmg"><!></button>');function wf(a,e){Zi(e,!0);let t=ie(Di(e.video.value.creator)),s=ie(null);const i=e.video.uri.split("/").pop()||e.video.uri,r=ul(e.video.value.creator),n=`transform: rotate(${r.rotation}deg) translate(${r.translateX}px, ${r.translateY}px);`;let o=ie(void 0),c=ie(void 0),l=ie(!1),h=ie(0),u=ie(!1),d=ie(!1),g=ie(!1),f=null,p=null,y=0,E=!1,v=null;zn(()=>{Ci(e.video.value.creator).then(k=>q(t,k,!0)),dl(e.video).then(k=>q(s,k,!0))}),Mo(S);function T(){if(f)return;q(d,!0),f=document.createElement("video"),f.muted=!0,f.playsInline=!0,f.preload="auto",f.style.cssText="position:fixed;top:-9999px;left:-9999px;width:320px;height:180px;pointer-events:none;",document.body.appendChild(f),f.addEventListener("seeked",x);const k=ia(e.video.uri);!!f.canPlayType("application/vnd.apple.mpegurl")?(f.addEventListener("loadedmetadata",()=>{f&&(y=f.duration,q(u,!0),A(F(h)))}),f.src=k,f.load()):De.isSupported()&&(p=new De({enableWorker:!1,lowLatencyMode:!1,startLevel:0}),p.loadSource(k),p.attachMedia(f),p.on(De.Events.LEVEL_LOADED,(N,G)=>{y=G.details.totalduration,q(u,!0),A(F(h))}),p.on(De.Events.ERROR,(N,G)=>{G.fatal&&q(d,!1)}))}function S(){p&&(p.destroy(),p=null),f&&(f.removeEventListener("seeked",x),f.remove(),f=null),q(u,!1),q(d,!1),q(g,!1),E=!1,v=null,y=0}function x(){if(E=!1,q(d,!1),L(),v!==null){const k=v;v=null,D(k)}}function D(k){!f||!F(u)||(E=!0,f.currentTime=k)}function A(k){if(!F(u)||!y)return;const M=k*y;E?v=M:D(M)}function L(){if(!f||!F(c))return;const k=f.videoWidth,M=f.videoHeight;if(!k||!M)return;const N=F(c).getBoundingClientRect(),G=window.devicePixelRatio||1;F(c).width=N.width*G,F(c).height=N.height*G;const B=F(c).getContext("2d");B&&(B.drawImage(f,0,0,F(c).width,F(c).height),q(g,!0))}let R=ie(0),I=0,C=ie(!1);function $(){q(l,!0),T()}function K(k){if(!F(o))return;const M=F(o).getBoundingClientRect(),N=Math.max(0,Math.min(1,(k.clientX-M.left)/M.width)),G=N-I;Math.abs(G)>.03&&(q(R,F(R)===0?1:0,!0),q(C,G<0),I=N),q(h,N,!0),A(F(h))}function H(){q(l,!1)}var O=kf(),w=de(O);Fs(w,{get seed(){return i},fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:2.2,padding:"clamp(24px, 4vw, 36px)",children:(k,M)=>{var N=Pf(),G=Jn(N),B=de(G,!0);ue(G);var U=ve(G,2),j=de(U);{let ye=ea(()=>i+"-thumb");Fs(j,{get seed(){return F(ye)},fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:1.5,padding:0,children:(nt,kt)=>{var We=Cf(),Qs=de(We);{var se=me=>{var Ee=Rf();Ge(()=>{dt(Ee,"src",F(s)),dt(Ee,"alt",e.video.value.title)}),ke(me,Ee)};mt(Qs,me=>{F(s)&&me(se)})}var Se=ve(Qs,2);let Pe;Ms(Se,me=>q(c,me),()=>F(c));var ze=ve(Se,2);{var Ne=me=>{var Ee=bf();ke(me,Ee)};mt(ze,me=>{F(l)&&F(d)&&!F(g)&&me(Ne)})}var at=ve(ze,2);{var ot=me=>{var Ee=_f(),Rt=de(Ee);ue(Ee),Ge(()=>Rs(Rt,`width: ${F(h)*100}%`)),ke(me,Ee)};mt(at,me=>{F(l)&&F(u)&&me(ot)})}var cs=ve(at,2);{var wt=me=>{var Ee=Df();let Rt;var Zs=de(Ee);ue(Ee),Ge(()=>{Rt=Zt(Ee,1,"scrub-frog svelte-1nxalmg",null,Rt,{flipped:F(C)}),Rs(Ee,`left: ${F(h)*100}%;`),dt(Zs,"src",F(R)===0?"/froggiestand.png":"/froggiejump.png")}),ke(me,Ee)};mt(cs,me=>{F(l)&&me(wt)})}nl(2),ue(We),Ms(We,me=>q(o,me),()=>F(o)),Ge(()=>Pe=Zt(Se,1,"scrub-canvas svelte-1nxalmg",null,Pe,{visible:F(l)&&F(g)})),xt("mouseenter",We,$),ft("mousemove",We,K),xt("mouseleave",We,H),ke(nt,We)},$$slots:{default:!0}})}ue(U);var J=ve(U,2),X=de(J),Z=de(X,!0);ue(X);var oe=ve(X,2),he=de(oe,!0);ue(oe);var xe=ve(oe,2),Ce=de(xe,!0);ue(xe),ue(J),Ge((ye,nt)=>{Xe(B,ye),Xe(Z,e.video.value.title),Xe(he,F(t)),Xe(Ce,nt)},[()=>ta(e.video.value.duration),()=>sa(e.video.value.createdAt)]),ke(k,N)},$$slots:{default:!0}}),ue(O),Ge(()=>Rs(O,n)),ft("click",O,()=>e.onSelect(e.video)),ke(a,O),Ji()}er(["click","mousemove"]);var Of=Oe('<h2 class="player-title svelte-1uha8ag"> </h2> <p class="player-meta svelte-1uha8ag"><span class="creator-tag svelte-1uha8ag"> </span> <span class="dot svelte-1uha8ag">·</span> <span class="dot svelte-1uha8ag">·</span> </p>',1),Ff=Oe('<section class="player-section svelte-1uha8ag"><!> <div class="player-info svelte-1uha8ag"><!></div></section>'),Mf=Oe('<div class="error svelte-1uha8ag"> </div>'),Nf=Oe('<button class="page-btn svelte-1uha8ag">← previous</button>'),Bf=Oe('<button class="page-btn svelte-1uha8ag">next →</button>'),Uf=Oe('<div class="app svelte-1uha8ag"><!> <!> <!> <section class="grid svelte-1uha8ag"></section> <div class="pagination svelte-1uha8ag"><!> <span class="page-num svelte-1uha8ag"> </span> <!></div></div>');function zf(a,e){Zi(e,!0);const t=9;let s=ie(Di([])),i=ie(!1),r=ie(null),n=ie(""),o=ie(""),c=ie(Di([void 0])),l=ie(0),h=ie(!0);async function u(){q(i,!0),q(o,"");try{const O=await gl(F(c)[F(l)],t);q(s,O.records,!0),q(h,!!O.cursor&&O.records.length===t,!0),F(h)&&F(c).length<=F(l)+1&&q(c,[...F(c),O.cursor],!0)}catch(O){q(o,O.message,!0)}q(i,!1)}function d(){!F(h)||F(i)||(Cr(l),u(),window.scrollTo({top:0,behavior:"smooth"}))}function g(){F(l)<=0||F(i)||(Cr(l,-1),u(),window.scrollTo({top:0,behavior:"smooth"}))}function f(O){q(r,O,!0),Ci(O.value.creator).then(k=>q(n,k,!0));const w=new URL(window.location.href);w.searchParams.set("v",O.uri),window.history.pushState({},"",w.toString()),window.scrollTo({top:0,behavior:"smooth"})}function p(){q(r,null);const O=new URL(window.location.href);O.searchParams.delete("v"),window.history.pushState({},"",O.toString())}zn(async()=>{await u();const w=new URLSearchParams(window.location.search).get("v");if(w){const k=F(s).find(M=>M.uri===w);k&&f(k)}});function y(){const w=new URLSearchParams(window.location.search).get("v");if(w){const k=F(s).find(M=>M.uri===w);k&&(q(r,k,!0),Ci(k.value.creator).then(M=>q(n,M,!0)))}else q(r,null)}var E=Uf();xt("popstate",ol,y),cl("1uha8ag",O=>{al(()=>{ll.title="vod frog"})});var v=de(E);fl(v,{onHomeClick:p});var T=ve(v,2);{var S=O=>{var w=Ff(),k=de(w);{let G=ea(()=>ia(F(r).uri));Lf(k,{get src(){return F(G)}})}var M=ve(k,2),N=de(M);Fs(N,{seed:"player-info",fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:1.8,padding:48,children:(G,B)=>{var U=Of(),j=Jn(U),J=de(j,!0);ue(j);var X=ve(j,2),Z=de(X),oe=de(Z,!0);ue(Z);var he=ve(Z,3),xe=ve(he,2);ue(X),Ge((Ce,ye)=>{Xe(J,F(r).value.title),Xe(oe,F(n)||F(r).value.creator),Xe(he,` ${Ce??""} `),Xe(xe,` ${ye??""}`)},[()=>sa(F(r).value.createdAt),()=>ta(F(r).value.duration)]),ke(G,U)},$$slots:{default:!0}}),ue(M),ue(w),ke(O,w)};mt(T,O=>{F(r)&&O(S)})}var x=ve(T,2);{var D=O=>{var w=Mf(),k=de(w,!0);ue(w),Ge(()=>Xe(k,F(o))),ke(O,w)};mt(x,O=>{F(o)&&O(D)})}var A=ve(x,2);pl(A,21,()=>F(s),O=>O.uri,(O,w)=>{wf(O,{get video(){return F(w)},onSelect:f})}),ue(A);var L=ve(A,2),R=de(L);{var I=O=>{var w=Nf();Ge(()=>w.disabled=F(i)),ft("click",w,g),ke(O,w)};mt(R,O=>{F(l)>0&&O(I)})}var C=ve(R,2),$=de(C);ue(C);var K=ve(C,2);{var H=O=>{var w=Bf();Ge(()=>w.disabled=F(i)),ft("click",w,d),ke(O,w)};mt(K,O=>{F(h)&&O(H)})}ue(L),ue(E),Ge(()=>Xe($,`page ${F(l)+1}`)),ke(a,E),Ji()}er(["click"]);export{zf as component};
+1
build/_app/immutable/nodes/3.CW9t1woG.js
··· 1 + import{a as i,f as n}from"../chunks/DGbOEUpF.js";import{o as oa}from"../chunks/DxGD2b0U.js";import{a1 as la,a4 as va,a8 as ia,a5 as r,B as b,A as a,a9 as na,a7 as p,aa as y,a6 as o,ab as j,ac as da,a3 as c}from"../chunks/CkzjbUDB.js";import{s as _}from"../chunks/BsDbD4Ku.js";import{i as u,s as pa,a as ca}from"../chunks/XE2G8ySY.js";import{h as ma}from"../chunks/DmyE0d-6.js";import{F as fa,g as _a,W as N,s as w}from"../chunks/D_t83wNY.js";import{s as ua}from"../chunks/C0nNmPgn.js";const ga=!1,xa=!1,Ga=Object.freeze(Object.defineProperty({__proto__:null,prerender:ga,ssr:xa},Symbol.toStringTag,{value:"Module"})),ba=()=>{const m=ua;return{page:{subscribe:m.page.subscribe},navigating:{subscribe:m.navigating.subscribe},updated:m.updated}},ha={subscribe(m){return ba().page.subscribe(m)}};var $a=n('<div class="loading svelte-oxml5t"><img src="/froggiejump.png" alt="loading" class="loading-frog svelte-oxml5t"/> <p class="loading-text svelte-oxml5t">hopping over to fetch profile...</p></div>'),ka=n('<div class="error svelte-oxml5t"> </div>'),ya=n('<img alt="banner" class="banner-img svelte-oxml5t"/>'),wa=n('<img class="avatar svelte-oxml5t"/>'),Ca=n('<div class="avatar-wrapper svelte-oxml5t"><!></div>'),Fa=n('<p class="description svelte-oxml5t"> </p>'),Ba=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">followers</span></div>'),Pa=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">following</span></div>'),Wa=n('<div class="stat svelte-oxml5t"><span class="stat-num svelte-oxml5t"> </span> <span class="stat-label svelte-oxml5t">posts</span></div>'),Aa=n('<div class="profile-card svelte-oxml5t"><!> <h1 class="display-name svelte-oxml5t"> </h1> <p class="handle svelte-oxml5t"> </p> <!> <div class="stats svelte-oxml5t"><!> <!> <!></div> <a target="_blank" class="profile-link svelte-oxml5t">view on witchsky →</a></div>'),ja=n('<div class="profile-layout svelte-oxml5t"><!> <div class="profile-card-area svelte-oxml5t"><!></div></div>'),Na=n('<div class="profile-page svelte-oxml5t"><!> <!> <div class="back-link svelte-oxml5t"><a href="/" class="svelte-oxml5t">← back to vods</a></div></div>');function Ia(m,S){la(S,!0);const q=()=>ca(ha,"$page",G),[G,I]=pa();let e=j(null),C=j(!0),h=j(""),D=da(()=>q().params.handle);oa(async()=>{b(C,!0),b(h,"");try{b(e,await _a(a(D)),!0)}catch(l){b(h,l.message,!0)}b(C,!1)});var F=Na();ma("oxml5t",l=>{ia(()=>{na.title=`${(a(e)?.displayName||a(D))??""} — vod frog 🐸`})});var E=r(F);fa(E,{});var J=p(E,2);{var K=l=>{var d=$a();i(l,d)},L=l=>{var d=ka(),$=r(d,!0);o(d),c(()=>_($,a(h))),i(l,d)},Q=l=>{var d=ja(),$=r(d);{var R=g=>{N(g,{seed:"profile-banner",fill:"#3992FF",strokeColor:"#0A182B",strokeWidth:2,padding:4,children:(O,k)=>{var x=ya();c(()=>w(x,"src",a(e).banner)),i(O,x)},$$slots:{default:!0}})};u($,g=>{a(e).banner&&g(R)})}var M=p($,2),U=r(M);N(U,{seed:"profile-card",fill:"#39FF44",strokeColor:"#0A182B",strokeWidth:2,padding:48,children:(g,O)=>{var k=Aa(),x=r(k);{var V=t=>{var s=Ca(),v=r(s);N(v,{seed:"profile-avatar",fill:"#FFDEED",strokeColor:"#0A182B",strokeWidth:1.5,padding:4,children:(f,Sa)=>{var A=wa();c(()=>{w(A,"src",a(e).avatar),w(A,"alt",a(e).displayName||a(e).handle)}),i(f,A)},$$slots:{default:!0}}),o(s),i(t,s)};u(x,t=>{a(e).avatar&&t(V)})}var B=p(x,2),X=r(B,!0);o(B);var P=p(B,2),Y=r(P);o(P);var z=p(P,2);{var Z=t=>{var s=Fa(),v=r(s,!0);o(s),c(()=>_(v,a(e).description)),i(t,s)};u(z,t=>{a(e).description&&t(Z)})}var W=p(z,2),H=r(W);{var aa=t=>{var s=Ba(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).followersCount)),i(t,s)};u(H,t=>{a(e).followersCount!==void 0&&t(aa)})}var T=p(H,2);{var ea=t=>{var s=Pa(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).followsCount)),i(t,s)};u(T,t=>{a(e).followsCount!==void 0&&t(ea)})}var ta=p(T,2);{var sa=t=>{var s=Wa(),v=r(s),f=r(v,!0);o(v),y(2),o(s),c(()=>_(f,a(e).postsCount)),i(t,s)};u(ta,t=>{a(e).postsCount!==void 0&&t(sa)})}o(W);var ra=p(W,2);o(k),c(()=>{_(X,a(e).displayName||a(e).handle),_(Y,`@${a(e).handle??""}`),w(ra,"href",`https://witchsky.app/profile/${a(e).handle??""}`)}),i(g,k)},$$slots:{default:!0}}),o(M),o(d),i(l,d)};u(J,l=>{a(C)?l(K):a(h)?l(L,1):a(e)&&l(Q,2)})}y(2),o(F),i(m,F),va(),I()}export{Ia as component,Ga as universal};
+1 -1
build/_app/version.json
··· 1 - {"version":"1774903841109"} 1 + {"version":"1774912484423"}
build/frogeye.png

This is a binary file and will not be displayed.

build/froggie.png

This is a binary file and will not be displayed.

build/froggiejump.png

This is a binary file and will not be displayed.

build/froggiestand.png

This is a binary file and will not be displayed.

build/frogicon.png

This is a binary file and will not be displayed.

+23 -24
build/index.html
··· 1 1 <!doctype html> 2 2 <html lang="en"> 3 - <head> 4 - <meta charset="utf-8" /> 5 - <link rel="icon" href="/frogcursor.png" /> 6 - <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 - <title>VODS VODS VODS</title> 8 - <link href="/_app/immutable/entry/start.YsP-T6iU.js" rel="modulepreload"> 9 - <link href="/_app/immutable/chunks/D9RahMPT.js" rel="modulepreload"> 10 - <link href="/_app/immutable/chunks/w0kPbzMq.js" rel="modulepreload"> 11 - <link href="/_app/immutable/chunks/B43_79mg.js" rel="modulepreload"> 12 - <link href="/_app/immutable/entry/app.BiVWJwsp.js" rel="modulepreload"> 13 - <link href="/_app/immutable/chunks/BcVkVDn_.js" rel="modulepreload"> 14 - <link href="/_app/immutable/chunks/mmStoiki.js" rel="modulepreload"> 15 - <link href="/_app/immutable/chunks/C_B-Ij-b.js" rel="modulepreload"> 16 - <link href="/_app/immutable/chunks/C6hdjiAW.js" rel="modulepreload"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <link rel="icon" href="/frogicon.png" /> 6 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 + <title>vod frog</title> 8 + <link href="/_app/immutable/entry/start.BUzUbSG3.js" rel="modulepreload"> 9 + <link href="/_app/immutable/chunks/C0nNmPgn.js" rel="modulepreload"> 10 + <link href="/_app/immutable/chunks/CkzjbUDB.js" rel="modulepreload"> 11 + <link href="/_app/immutable/chunks/DxGD2b0U.js" rel="modulepreload"> 12 + <link href="/_app/immutable/entry/app.CwuxgLSd.js" rel="modulepreload"> 13 + <link href="/_app/immutable/chunks/BsDbD4Ku.js" rel="modulepreload"> 14 + <link href="/_app/immutable/chunks/DGbOEUpF.js" rel="modulepreload"> 15 + <link href="/_app/immutable/chunks/XE2G8ySY.js" rel="modulepreload"> 16 + <link href="/_app/immutable/chunks/CFYBLbZM.js" rel="modulepreload"> 17 + <link href="/_app/immutable/chunks/Dr80VTgO.js" rel="modulepreload"> 17 18 18 - </head> 19 - <body data-sveltekit-prerender="auto"> 20 - 19 + </head> 20 + <body> 21 + <div style="display: contents"> 21 22 <script> 22 23 { 23 - __sveltekit_1uytokf = { 24 + __sveltekit_1gh8pzr = { 24 25 base: "" 25 26 }; 26 27 27 28 const element = document.currentScript.parentElement; 28 29 29 30 Promise.all([ 30 - import("/_app/immutable/entry/start.YsP-T6iU.js"), 31 - import("/_app/immutable/entry/app.BiVWJwsp.js") 31 + import("/_app/immutable/entry/start.BUzUbSG3.js"), 32 + import("/_app/immutable/entry/app.CwuxgLSd.js") 32 33 ]).then(([kit, app]) => { 33 34 kit.start(app, element); 34 35 }); 35 36 } 36 37 </script> 37 - 38 - </body> 39 - </html> 40 - body> 38 + </div> 39 + </body> 41 40 </html>
build/leaves.png

This is a binary file and will not be displayed.

+14 -3
src/lib/FrogHeader.svelte
··· 16 16 </div> 17 17 <div class="subtitle-lines"> 18 18 <p class="subtitle">an exploration by</p> 19 - <p class="subtitle">@goose.art using @stream.place</p> 19 + <p class="subtitle"><a href="https://witchsky.app/profile/goose.art" target="_blank" class="subtitle-link">@goose.art</a> using <a href="https://witchsky.app/profile/stream.place" target="_blank" class="subtitle-link">@stream.place</a></p> 20 20 </div> 21 21 </header> 22 22 ··· 37 37 } 38 38 39 39 .logo-text { 40 - font-family: 'PicNic', cursive, system-ui; 40 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 41 41 font-size: clamp(3rem, 8vw, 5.5rem); 42 42 color: #0A182B; 43 43 margin: 0; ··· 70 70 z-index: 0; 71 71 } 72 72 73 + .subtitle-link { 74 + color: #0A182B; 75 + text-decoration: underline; 76 + text-decoration-color: #FF3992; 77 + transition: color 0.15s; 78 + } 79 + 80 + .subtitle-link:hover { 81 + color: #FF3992; 82 + } 83 + 73 84 .subtitle { 74 - font-family: 'PicNic', cursive, system-ui; 85 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 75 86 font-size: clamp(0.85rem, 2vw, 1.15rem); 76 87 color: #0A182B; 77 88 margin: 0;
+18 -14
src/lib/VideoCard.svelte
··· 60 60 61 61 const src = getPlaylistUrl(video.uri); 62 62 63 - if (Hls.isSupported()) { 63 + const hasNativeHls = !!scrubVideo.canPlayType('application/vnd.apple.mpegurl'); 64 + 65 + if (hasNativeHls) { 66 + // Prefer native HLS on Safari for Opus support 67 + scrubVideo.addEventListener('loadedmetadata', () => { 68 + if (scrubVideo) { 69 + videoDuration = scrubVideo.duration; 70 + scrubReady = true; 71 + seekToProgress(scrubProgress); 72 + } 73 + }); 74 + scrubVideo.src = src; 75 + scrubVideo.load(); 76 + } else if (Hls.isSupported()) { 64 77 hls = new Hls({ enableWorker: false, lowLatencyMode: false, startLevel: 0 }); 65 78 hls.loadSource(src); 66 79 hls.attachMedia(scrubVideo); ··· 72 85 hls.on(Hls.Events.ERROR, (_e, data) => { 73 86 if (data.fatal) scrubLoading = false; 74 87 }); 75 - } else if (scrubVideo.canPlayType('application/vnd.apple.mpegurl')) { 76 - scrubVideo.src = src; 77 - scrubVideo.addEventListener('loadedmetadata', () => { 78 - if (scrubVideo) { 79 - videoDuration = scrubVideo.duration; 80 - scrubReady = true; 81 - seekToProgress(scrubProgress); 82 - } 83 - }); 84 88 } 85 89 } 86 90 ··· 216 220 217 221 .duration-badge { 218 222 display: block; 219 - font-family: 'PicNic', cursive, system-ui; 223 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 220 224 font-size: 1.4rem; 221 225 color: #FF3992; 222 226 font-weight: bold; ··· 323 327 324 328 .title { 325 329 margin: 0; 326 - font-family: 'Fang', system-ui, sans-serif; 330 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 327 331 font-size: 0.9rem; 328 332 font-weight: 700; 329 333 color: #0A182B; ··· 337 341 338 342 .creator { 339 343 margin: 4px 0 0; 340 - font-family: 'Fang', system-ui, sans-serif; 344 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 341 345 font-size: 0.8rem; 342 346 color: #0A182B; 343 347 opacity: 0.8; ··· 347 351 348 352 .date { 349 353 margin: 2px 0 0; 350 - font-family: 'Fang', system-ui, sans-serif; 354 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 351 355 font-size: 0.75rem; 352 356 color: #FF3992; 353 357 font-style: italic;
+13 -11
src/lib/VideoPlayer.svelte
··· 39 39 destroy(); 40 40 errorMsg = ""; 41 41 42 - if (Hls.isSupported()) { 42 + const hasNativeHls = !!videoEl.canPlayType("application/vnd.apple.mpegurl"); 43 + 44 + if (hasNativeHls) { 45 + // Prefer native HLS on Safari — Safari 17+ handles Opus in HLS natively. 46 + // Using hls.js (MSE) on Safari breaks Opus audio since Safari's MSE doesn't support Opus. 47 + videoEl.addEventListener("loadedmetadata", () => { 48 + videoEl?.play().catch(() => {}); 49 + }); 50 + videoEl.src = src; 51 + videoEl.load(); 52 + } else if (Hls.isSupported()) { 53 + // Use hls.js on Chrome, Firefox, etc. 43 54 hls = new Hls({ enableWorker: true, lowLatencyMode: false }); 44 55 hls.loadSource(src); 45 56 hls.attachMedia(videoEl); ··· 64 75 break; 65 76 } 66 77 } 67 - }); 68 - } else if (videoEl.canPlayType("application/vnd.apple.mpegurl")) { 69 - videoEl.src = src; 70 - videoEl.addEventListener("loadedmetadata", () => { 71 - videoEl?.play().catch(() => {}); 72 - }); 73 - videoEl.addEventListener("error", () => { 74 - errorMsg = 75 - "Audio may not work — these streams use Opus. Try Chrome or Firefox."; 76 78 }); 77 79 } else { 78 80 errorMsg = "HLS playback is not supported in this browser."; ··· 394 396 color: #ffdeed; 395 397 padding: 8px 12px; 396 398 border-radius: 6px; 397 - font-family: "Fang", system-ui, sans-serif; 399 + font-family: "Nunito", "Fang", system-ui, sans-serif; 398 400 font-size: 0.8rem; 399 401 } 400 402 </style>
+24
src/lib/api.ts
··· 69 69 }); 70 70 } 71 71 72 + // --- Profile --- 73 + 74 + export const BSKY_PUBLIC_API = 'https://public.api.bsky.app'; 75 + 76 + export interface BskyProfile { 77 + did: string; 78 + handle: string; 79 + displayName?: string; 80 + description?: string; 81 + avatar?: string; 82 + banner?: string; 83 + followersCount?: number; 84 + followsCount?: number; 85 + postsCount?: number; 86 + createdAt?: string; 87 + } 88 + 89 + export async function getProfile(actor: string): Promise<BskyProfile> { 90 + const params = new URLSearchParams({ actor }); 91 + const res = await fetch(`${BSKY_PUBLIC_API}/xrpc/app.bsky.actor.getProfile?${params}`); 92 + if (!res.ok) throw new Error(`Failed to fetch profile: ${res.status}`); 93 + return res.json(); 94 + } 95 + 72 96 // --- Handle resolution --- 73 97 74 98 const handleCache = new Map<string, string>();
+5 -1
src/routes/+layout.svelte
··· 7 7 8 8 <svelte:head> 9 9 <link rel="icon" href="/frogicon.png" /> 10 + <!-- Google Fonts: Shrikhand for headers (PicNic-like), Nunito for body (Fang-like) --> 11 + <link rel="preconnect" href="https://fonts.googleapis.com" /> 12 + <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous" /> 13 + <link href="https://fonts.googleapis.com/css2?family=Shrikhand&family=Nunito:wght@400;700&display=swap" rel="stylesheet" /> 10 14 <style> 11 15 /* Cursor must be in global head style to override everything */ 12 16 *, *::before, *::after { ··· 32 36 } 33 37 34 38 :global(body) { 35 - font-family: 'Fang', system-ui, -apple-system, BlinkMacSystemFont, sans-serif; 39 + font-family: 'Nunito', 'Fang', system-ui, -apple-system, BlinkMacSystemFont, sans-serif; 36 40 } 37 41 38 42 :global(*) {
+6 -6
src/routes/+page.svelte
··· 179 179 180 180 .player-title { 181 181 margin: 0; 182 - font-family: "PicNic", cursive, system-ui; 182 + font-family: "Shrikhand", "PicNic", cursive, system-ui; 183 183 font-size: clamp(1.4rem, 3vw, 2rem); 184 184 color: #0a182b; 185 185 } 186 186 187 187 .player-meta { 188 188 margin: 6px 0 0; 189 - font-family: "Fang", system-ui, sans-serif; 189 + font-family: "Nunito", "Fang", system-ui, sans-serif; 190 190 color: #0a182b; 191 191 opacity: 0.7; 192 192 font-size: 0.85rem; ··· 213 213 font-size: 1rem; 214 214 cursor: pointer; 215 215 flex-shrink: 0; 216 - font-family: "Fang", system-ui, sans-serif; 216 + font-family: "Nunito", "Fang", system-ui, sans-serif; 217 217 transition: 218 218 background 0.15s, 219 219 color 0.15s; ··· 246 246 border: 3px solid #0a182b; 247 247 padding: 12px 32px; 248 248 border-radius: 40px; 249 - font-family: "PicNic", cursive, system-ui; 249 + font-family: "Shrikhand", "PicNic", cursive, system-ui; 250 250 font-size: 1.1rem; 251 251 cursor: pointer; 252 252 transition: all 0.2s ease; ··· 268 268 } 269 269 270 270 .page-num { 271 - font-family: "PicNic", cursive, system-ui; 271 + font-family: "Shrikhand", "PicNic", cursive, system-ui; 272 272 font-size: 1.1rem; 273 273 color: #0a182b; 274 274 } ··· 279 279 padding: 12px 16px; 280 280 border-radius: 8px; 281 281 margin: 0 10px 20px; 282 - font-family: "Fang", system-ui, sans-serif; 282 + font-family: "Nunito", "Fang", system-ui, sans-serif; 283 283 border: 2px solid #ff3992; 284 284 } 285 285
+263
src/routes/profile/[handle]/+page.svelte
··· 1 + <script lang="ts"> 2 + import { onMount } from 'svelte'; 3 + import { page } from '$app/stores'; 4 + import { getProfile, type BskyProfile } from '$lib/api'; 5 + import WavyBorder from '$lib/WavyBorder.svelte'; 6 + import FrogHeader from '$lib/FrogHeader.svelte'; 7 + 8 + let profile: BskyProfile | null = $state(null); 9 + let loading = $state(true); 10 + let error = $state(''); 11 + 12 + let handle = $derived($page.params.handle); 13 + 14 + onMount(async () => { 15 + loading = true; 16 + error = ''; 17 + try { 18 + profile = await getProfile(handle); 19 + } catch (e: any) { 20 + error = e.message; 21 + } 22 + loading = false; 23 + }); 24 + </script> 25 + 26 + <svelte:head> 27 + <title>{profile?.displayName || handle} — vod frog 🐸</title> 28 + </svelte:head> 29 + 30 + <div class="profile-page"> 31 + <FrogHeader /> 32 + 33 + {#if loading} 34 + <div class="loading"> 35 + <img src="/froggiejump.png" alt="loading" class="loading-frog" /> 36 + <p class="loading-text">hopping over to fetch profile...</p> 37 + </div> 38 + {:else if error} 39 + <div class="error">{error}</div> 40 + {:else if profile} 41 + <div class="profile-layout"> 42 + <!-- Banner --> 43 + {#if profile.banner} 44 + <WavyBorder seed="profile-banner" fill="#3992FF" strokeColor="#0A182B" strokeWidth={2} padding={4}> 45 + <img src={profile.banner} alt="banner" class="banner-img" /> 46 + </WavyBorder> 47 + {/if} 48 + 49 + <!-- Profile card --> 50 + <div class="profile-card-area"> 51 + <WavyBorder seed="profile-card" fill="#39FF44" strokeColor="#0A182B" strokeWidth={2} padding={48}> 52 + <div class="profile-card"> 53 + {#if profile.avatar} 54 + <div class="avatar-wrapper"> 55 + <WavyBorder seed="profile-avatar" fill="#FFDEED" strokeColor="#0A182B" strokeWidth={1.5} padding={4}> 56 + <img src={profile.avatar} alt={profile.displayName || profile.handle} class="avatar" /> 57 + </WavyBorder> 58 + </div> 59 + {/if} 60 + 61 + <h1 class="display-name">{profile.displayName || profile.handle}</h1> 62 + <p class="handle">@{profile.handle}</p> 63 + 64 + {#if profile.description} 65 + <p class="description">{profile.description}</p> 66 + {/if} 67 + 68 + <div class="stats"> 69 + {#if profile.followersCount !== undefined} 70 + <div class="stat"> 71 + <span class="stat-num">{profile.followersCount}</span> 72 + <span class="stat-label">followers</span> 73 + </div> 74 + {/if} 75 + {#if profile.followsCount !== undefined} 76 + <div class="stat"> 77 + <span class="stat-num">{profile.followsCount}</span> 78 + <span class="stat-label">following</span> 79 + </div> 80 + {/if} 81 + {#if profile.postsCount !== undefined} 82 + <div class="stat"> 83 + <span class="stat-num">{profile.postsCount}</span> 84 + <span class="stat-label">posts</span> 85 + </div> 86 + {/if} 87 + </div> 88 + 89 + <a href="https://witchsky.app/profile/{profile.handle}" target="_blank" class="profile-link"> 90 + view on witchsky → 91 + </a> 92 + </div> 93 + </WavyBorder> 94 + </div> 95 + </div> 96 + {/if} 97 + 98 + <div class="back-link"> 99 + <a href="/">← back to vods</a> 100 + </div> 101 + </div> 102 + 103 + <style> 104 + .profile-page { 105 + max-width: 800px; 106 + margin: 0 auto; 107 + padding: 0 clamp(24px, 7vw, 80px) 60px; 108 + } 109 + 110 + .loading { 111 + text-align: center; 112 + padding: 60px 20px; 113 + } 114 + 115 + .loading-frog { 116 + width: 64px; 117 + height: auto; 118 + animation: hop 0.6s ease-in-out infinite alternate; 119 + } 120 + 121 + @keyframes hop { 122 + 0% { transform: translateY(0); } 123 + 100% { transform: translateY(-12px); } 124 + } 125 + 126 + .loading-text { 127 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 128 + font-size: 1.2rem; 129 + color: #0A182B; 130 + margin-top: 12px; 131 + } 132 + 133 + .error { 134 + background: rgba(255, 57, 146, 0.15); 135 + color: #FF3992; 136 + padding: 12px 16px; 137 + border-radius: 8px; 138 + margin: 20px 0; 139 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 140 + border: 2px solid #FF3992; 141 + } 142 + 143 + .profile-layout { 144 + display: flex; 145 + flex-direction: column; 146 + gap: 24px; 147 + } 148 + 149 + .banner-img { 150 + width: 100%; 151 + display: block; 152 + aspect-ratio: 3 / 1; 153 + object-fit: cover; 154 + } 155 + 156 + .profile-card-area { 157 + margin-top: -20px; 158 + } 159 + 160 + .profile-card { 161 + display: flex; 162 + flex-direction: column; 163 + align-items: center; 164 + text-align: center; 165 + gap: 8px; 166 + } 167 + 168 + .avatar-wrapper { 169 + width: clamp(80px, 15vw, 120px); 170 + margin-bottom: 8px; 171 + } 172 + 173 + .avatar { 174 + width: 100%; 175 + display: block; 176 + aspect-ratio: 1; 177 + object-fit: cover; 178 + border-radius: 0; 179 + } 180 + 181 + .display-name { 182 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 183 + font-size: clamp(1.8rem, 4vw, 2.8rem); 184 + color: #0A182B; 185 + margin: 0; 186 + line-height: 1.1; 187 + } 188 + 189 + .handle { 190 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 191 + font-size: 1rem; 192 + color: #0A182B; 193 + opacity: 0.7; 194 + margin: 0; 195 + } 196 + 197 + .description { 198 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 199 + font-size: 0.95rem; 200 + color: #0A182B; 201 + margin: 8px 0; 202 + max-width: 500px; 203 + line-height: 1.5; 204 + } 205 + 206 + .stats { 207 + display: flex; 208 + gap: clamp(16px, 4vw, 32px); 209 + margin: 12px 0; 210 + } 211 + 212 + .stat { 213 + display: flex; 214 + flex-direction: column; 215 + align-items: center; 216 + } 217 + 218 + .stat-num { 219 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 220 + font-size: 1.4rem; 221 + color: #0A182B; 222 + font-weight: bold; 223 + } 224 + 225 + .stat-label { 226 + font-family: 'Nunito', 'Fang', system-ui, sans-serif; 227 + font-size: 0.75rem; 228 + color: #0A182B; 229 + opacity: 0.6; 230 + } 231 + 232 + .profile-link { 233 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 234 + font-size: 1rem; 235 + color: #0A182B; 236 + text-decoration: underline; 237 + text-decoration-color: #FF3992; 238 + margin-top: 8px; 239 + transition: color 0.15s; 240 + } 241 + 242 + .profile-link:hover { 243 + color: #FF3992; 244 + } 245 + 246 + .back-link { 247 + text-align: center; 248 + padding: 30px; 249 + } 250 + 251 + .back-link a { 252 + font-family: 'Shrikhand', 'PicNic', cursive, system-ui; 253 + font-size: 1.1rem; 254 + color: #0A182B; 255 + text-decoration: underline; 256 + text-decoration-color: #FF3992; 257 + transition: color 0.15s; 258 + } 259 + 260 + .back-link a:hover { 261 + color: #FF3992; 262 + } 263 + </style>
+2
src/routes/profile/[handle]/+page.ts
··· 1 + export const prerender = false; 2 + export const ssr = false;