From 1bb32beaf9dff368dcb4d8410cd5379cacda5e16 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:40:18 -0800 Subject: [PATCH 01/27] Helper: read a PS4 game's version from VERSION too (#934) An updated PS4 game keeps APP_VER at the base game's 01.00 and records its update in appinfo.db's VERSION (RDR2 CUSA03041: APP_VER 01.00, VERSION 01.32). The helper only asked for CONTENT_VERSION and APP_VER, so the console page's game list showed the base version, cheats for the installed update did not match, and clean-up named the wrong version. Every helper reader now asks for CONTENT_VERSION, VERSION and APP_VER and picks CONTENT_VERSION, else the higher of VERSION and APP_VER, from one shared header (appinfo_version.h) with host tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/include/appinfo_version.h | 55 +++++++++++++++++++++ payload/include/webui_cheats_store.h | 5 +- payload/src/cheats.c | 16 ++++-- payload/src/storage_cleanup.c | 11 +++-- payload/src/webui_api.c | 7 +-- payload/src/webui_cheats_store.c | 11 +++-- payload/tests/webui_cheats_store_selftest.c | 37 +++++++++++++- 7 files changed, 125 insertions(+), 17 deletions(-) create mode 100644 payload/include/appinfo_version.h diff --git a/payload/include/appinfo_version.h b/payload/include/appinfo_version.h new file mode 100644 index 000000000..341f16ccd --- /dev/null +++ b/payload/include/appinfo_version.h @@ -0,0 +1,55 @@ +#ifndef PS5UPLOAD_APPINFO_VERSION_H +#define PS5UPLOAD_APPINFO_VERSION_H + +/* A title's installed version from its appinfo.db rows (#934). + * + * A PS5 title says CONTENT_VERSION ("01.000.016"). A PS4 title says APP_VER and VERSION: an + * installed update raises VERSION ("01.32") while APP_VER stays at the base game's "01.00" + * (RDR2 CUSA03041, ELDEN RING CUSA28527), so the higher of the two is the version it runs. + * Every helper reader (the game list, the cheat version, clean-up) asks for these keys and picks + * the same way; the engine (AppInfoRows::installed_version) and the pages + * (installedAppVersion in client/src/lib/versionNumbers.ts) do too. + * + * Header-only and pure, so the host tests include it as is. */ + +#include + +/* For an APP_INFO_QUERY "keys" list, and for an SQL IN (...) list. */ +#define APPINFO_VERSION_KEYS "CONTENT_VERSION,VERSION,APP_VER" +#define APPINFO_VERSION_SQL_KEYS "'CONTENT_VERSION','VERSION','APP_VER'" + +/* Dotted versions compared number by number ("01.32" above "01.05", "1.10" above "1.9"). Leading + * spaces of a part are skipped; anything else that is not a digit or a dot ends the comparison + * there. <0, 0 or >0. */ +static inline int appinfo_version_cmp(const char *a, const char *b) { + while ((a && *a) || (b && *b)) { + unsigned long x = 0, y = 0; + while (a && *a == ' ') a++; + while (b && *b == ' ') b++; + for (; a && *a >= '0' && *a <= '9'; a++) + if (x < 100000000ul) x = x * 10ul + (unsigned long)(*a - '0'); + for (; b && *b >= '0' && *b <= '9'; b++) + if (y < 100000000ul) y = y * 10ul + (unsigned long)(*b - '0'); + if (x != y) return x < y ? -1 : 1; + if (a && *a == '.') a++; + else a = NULL; /* the end, or junk: nothing more to compare */ + if (b && *b == '.') b++; + else b = NULL; + } + return 0; +} + +/* The installed version: CONTENT_VERSION when there is one, else the higher of VERSION and + * APP_VER. Any argument may be NULL or "" (absent). Returns one of the arguments, or "" when all + * are absent. */ +static inline const char *appinfo_version_pick(const char *content, const char *version, + const char *app_ver) { + int hv = version && version[0], ha = app_ver && app_ver[0]; + if (content && content[0]) return content; + if (hv && ha) return appinfo_version_cmp(version, app_ver) >= 0 ? version : app_ver; + if (hv) return version; + if (ha) return app_ver; + return ""; +} + +#endif diff --git a/payload/include/webui_cheats_store.h b/payload/include/webui_cheats_store.h index 19b41c91a..fe4c17826 100644 --- a/payload/include/webui_cheats_store.h +++ b/payload/include/webui_cheats_store.h @@ -32,8 +32,9 @@ const char *webui_cheat_store_query(const char *query, char fmt[WEBUI_CHEAT_FMT_ int webui_cheat_target(const char *root, const char *fmt, const char *name, char *out, size_t cap); /* The game's version from an APP_INFO_QUERY reply ({"ok":true,"rows":[{"key":..,"val":..}..]}): - * CONTENT_VERSION (PS5, "01.000.016") first, else APP_VER (PS4, "01.05"), the same forms the cheat - * files name their target version in. Only digits and dots, 1..cap-1 bytes. 1 found, else 0 and "". */ + * CONTENT_VERSION (PS5, "01.000.016") first, else the higher of VERSION and APP_VER (PS4, "01.32": + * an update raises VERSION, appinfo_version.h), the same forms the cheat files name their target + * version in. Only digits and dots, 1..cap-1 bytes. 1 found, else 0 and "". */ int webui_cheat_appinfo_version(const char *json, size_t n, char *out, size_t cap); #endif diff --git a/payload/src/cheats.c b/payload/src/cheats.c index 99dbced4c..f622a2129 100644 --- a/payload/src/cheats.c +++ b/payload/src/cheats.c @@ -24,6 +24,7 @@ * part of ps5upload, GPL-3.0-or-later. */ +#include "appinfo_version.h" #include "cheats.h" #include "cheats_list.h" #include "cheats_json.h" @@ -1408,16 +1409,19 @@ static int resolve_mod_locs(pid_t pid, intptr_t base, const cheat_mod_t *mod, ch /* ── XML game patches (#527) ─────────────────────────────────────── */ /* The game's version as the console reports it: appinfo.db's CONTENT_VERSION ("01.004.000") and - * APP_VER ("01.04"), else the installed param.json's contentVersion. */ + * a PS4 game's version ("01.32": the higher of VERSION and APP_VER, see appinfo_version.h), else + * the installed param.json's contentVersion. */ typedef struct { char content[32]; - char app[32]; + char app[32]; /* the PS4 version picked from VERSION and APP_VER */ + char version[32]; /* VERSION as read, for that pick */ } game_ver_t; static int game_ver_row(void *ctx, int ncol, const char *const *vals) { game_ver_t *v = (game_ver_t *)ctx; if (ncol < 2 || !vals[0] || !vals[1]) return 0; if (strcmp(vals[0], "CONTENT_VERSION") == 0) snprintf(v->content, sizeof v->content, "%s", vals[1]); + else if (strcmp(vals[0], "VERSION") == 0) snprintf(v->version, sizeof v->version, "%s", vals[1]); else if (strcmp(vals[0], "APP_VER") == 0) snprintf(v->app, sizeof v->app, "%s", vals[1]); return 0; } @@ -1430,9 +1434,15 @@ static void game_versions(const char *title, game_ver_t *v) { if (!((title[i] >= 'A' && title[i] <= 'Z') || (title[i] >= '0' && title[i] <= '9'))) return; char sql[200]; snprintf(sql, sizeof sql, - "SELECT key, val FROM tbl_appinfo WHERE titleId='%s' AND key IN ('CONTENT_VERSION','APP_VER')", + "SELECT key, val FROM tbl_appinfo WHERE titleId='%s' AND key IN (" APPINFO_VERSION_SQL_KEYS ")", title); (void)content_db_select_text(CONTENT_DB_APPINFO, sql, 8, v, game_ver_row); + { + /* A PS4 update raises VERSION and leaves APP_VER at the base game's "01.00" (#934). */ + char app[sizeof v->app]; + snprintf(app, sizeof app, "%s", appinfo_version_pick(NULL, v->version, v->app)); + memcpy(v->app, app, sizeof app); + } if (v->content[0] || v->app[0]) return; char path[128]; snprintf(path, sizeof path, "/system_ex/app/%s/sce_sys/param.json", title); diff --git a/payload/src/storage_cleanup.c b/payload/src/storage_cleanup.c index c1ac1c0d7..180c87423 100644 --- a/payload/src/storage_cleanup.c +++ b/payload/src/storage_cleanup.c @@ -31,6 +31,7 @@ #include #include +#include "appinfo_version.h" #include "ava1_op.h" #include "cheats_list.h" /* cheats_utf8_char_len */ #include "cleanup_rules.h" @@ -367,14 +368,16 @@ static int installed(const char *tid) { return G.appdb_ok ? 0 : 1; } -/* Installed versions from appinfo.db (CONTENT_VERSION, else APP_VER). */ +/* Installed versions from appinfo.db (CONTENT_VERSION, else the higher of VERSION and APP_VER: + * appinfo_version.h). */ typedef struct { - char content[16], app[16]; + char content[16], version[16], app[16]; } sc_ver_t; static int ver_row(void *ctx, int ncol, const char *const *vals) { sc_ver_t *v = ctx; if (ncol < 2 || !vals[0] || !vals[1]) return 0; if (strcmp(vals[0], "CONTENT_VERSION") == 0) snprintf(v->content, sizeof v->content, "%s", vals[1]); + else if (strcmp(vals[0], "VERSION") == 0) snprintf(v->version, sizeof v->version, "%s", vals[1]); else if (strcmp(vals[0], "APP_VER") == 0) snprintf(v->app, sizeof v->app, "%s", vals[1]); return 0; } @@ -385,9 +388,9 @@ static void installed_version(const char *tid, char *out, size_t cap) { out[0] = '\0'; if (!scr_is_title_id(tid)) return; snprintf(sql, sizeof sql, - "SELECT key, val FROM tbl_appinfo WHERE titleId='%s' AND key IN ('CONTENT_VERSION','APP_VER')", tid); + "SELECT key, val FROM tbl_appinfo WHERE titleId='%s' AND key IN (" APPINFO_VERSION_SQL_KEYS ")", tid); (void)content_db_select_text(CONTENT_DB_APPINFO, sql, 8, &v, ver_row); - snprintf(out, cap, "%s", v.content[0] ? v.content : v.app); + snprintf(out, cap, "%s", appinfo_version_pick(v.content, v.version, v.app)); } /* ---- items ---- */ diff --git a/payload/src/webui_api.c b/payload/src/webui_api.c index 68e113d9f..50781e3cb 100644 --- a/payload/src/webui_api.c +++ b/payload/src/webui_api.c @@ -20,6 +20,7 @@ #include #include +#include "appinfo_version.h" #include "archive_extract.h" #include "ava1_data.h" #include "console_convert.h" @@ -1321,7 +1322,7 @@ static void r_apps_info(const char *b, size_t n, uint8_t *out, int fd) { return; } k = snprintf(req, sizeof req, - "{\"title_id\":\"%s\",\"keys\":\"CONTENT_VERSION,APP_VER,#_size,#_last_access_time,#_install_time\"}", + "{\"title_id\":\"%s\",\"keys\":\"" APPINFO_VERSION_KEYS ",#_size,#_last_access_time,#_install_time\"}", tid); /* letters and digits only */ st = call_text(AVA1_METHOD_APP_INFO_QUERY, req, (size_t)k, out, &ol, &t, &tl); if (st != AVA1_STATUS_OK || !tl || t[0] != '{') continue; @@ -2275,7 +2276,7 @@ static void r_cheats_engine(const char *b, size_t n, uint8_t *out, int fd) { } /* {title_id}: the game's installed version, read like the PC app reads it (APP_INFO_QUERY's - * CONTENT_VERSION, else APP_VER): {"version":"01.05"} or {"version":null} when appinfo.db does not + * CONTENT_VERSION, else the higher of VERSION and APP_VER): {"version":"01.05"} or {"version":null} when appinfo.db does not * say (the page then lists every version's cheats). Never an error for an unknown version. */ static void r_cheats_version(const char *b, size_t n, uint8_t *out, int fd) { char title[32], req[96], ver[32], json[64]; @@ -2283,7 +2284,7 @@ static void r_cheats_version(const char *b, size_t n, uint8_t *out, int fd) { size_t ol, tl; int st, k; if (need_title(fd, b, n, title, sizeof title) != 0) return; - k = snprintf(req, sizeof req, "{\"title_id\":\"%s\",\"keys\":\"CONTENT_VERSION,APP_VER\"}", title); + k = snprintf(req, sizeof req, "{\"title_id\":\"%s\",\"keys\":\"" APPINFO_VERSION_KEYS "\"}", title); st = call_text(AVA1_METHOD_APP_INFO_QUERY, req, (size_t)k, out, &ol, &t, &tl); if (st == AVA1_STATUS_OK && webui_cheat_appinfo_version((const char *)t, tl, ver, sizeof ver) == 1) k = snprintf(json, sizeof json, "{\"version\":\"%s\"}", ver); /* digits and dots only */ diff --git a/payload/src/webui_cheats_store.c b/payload/src/webui_cheats_store.c index a4eb8d029..97253a7f1 100644 --- a/payload/src/webui_cheats_store.c +++ b/payload/src/webui_cheats_store.c @@ -7,6 +7,7 @@ #include #include +#include "appinfo_version.h" #include "webui_codec.h" int webui_cheat_format_ok(const char *fmt) { @@ -121,7 +122,8 @@ static int version_ok(char *v) { int webui_cheat_appinfo_version(const char *json, size_t n, char *out, size_t cap) { const char *arr; size_t alen, i = 1; - char key[32], val[64], app_ver[64] = ""; + char key[32], val[64], version[64] = "", app_ver[64] = ""; + const char *pick; if (cap) out[0] = '\0'; if (!json || cap < 2 || webui_json_array(json, n, "rows", &arr, &alen) != 1) return 0; while (i < alen) { @@ -139,12 +141,15 @@ int webui_cheat_appinfo_version(const char *json, size_t n, char *out, size_t ca memcpy(out, val, strlen(val) + 1); return 1; } + if (strcmp(key, "VERSION") == 0) memcpy(version, val, strlen(val) + 1); if (strcmp(key, "APP_VER") == 0) memcpy(app_ver, val, strlen(val) + 1); } i += len; } - if (app_ver[0]) { - memcpy(out, app_ver, strlen(app_ver) + 1); + /* A PS4 update raises VERSION and leaves APP_VER at the base game's "01.00" (#934). */ + pick = appinfo_version_pick(NULL, version, app_ver); + if (pick[0]) { + memcpy(out, pick, strlen(pick) + 1); return 1; } return 0; diff --git a/payload/tests/webui_cheats_store_selftest.c b/payload/tests/webui_cheats_store_selftest.c index ee2155268..b32477b9f 100644 --- a/payload/tests/webui_cheats_store_selftest.c +++ b/payload/tests/webui_cheats_store_selftest.c @@ -2,8 +2,8 @@ * /api/cheats/store query and file name are checked strictly (a plain base name with the format's * extension, never a path), the target folders are made when missing, and the bytes land through * wf_receive_file as a same-folder temp + rename: a cut-off body leaves the old file and no temp. - * The appinfo reply reader prefers CONTENT_VERSION over APP_VER. File tests run in a fresh mkdtemp - * directory. Build: see the root Makefile test-payload. */ + * The appinfo reply reader prefers CONTENT_VERSION, else the higher of VERSION and APP_VER (#934). + * File tests run in a fresh mkdtemp directory. Build: see the root Makefile test-payload. */ #include #include #include @@ -12,6 +12,7 @@ #include #include +#include "appinfo_version.h" #include "webui_cheats_store.h" #include "webui_files.h" @@ -203,6 +204,37 @@ static void versions(void) { CHECK(webui_cheat_appinfo_version(nested, strlen(nested), v, sizeof v) == 1 && strcmp(v, "02.10") == 0); CHECK(webui_cheat_appinfo_version("{\"ok\":false,\"error\":\"x\"}", 25, v, sizeof v) == 0); CHECK(webui_cheat_appinfo_version(ps5, strlen(ps5), v, 4) == 0); /* does not fit */ + + /* #934: an updated PS4 game keeps APP_VER at the base's 01.00 and says its update in VERSION. */ + const char *rdr2 = "{\"ok\":true,\"title_id\":\"CUSA03041\",\"rows\":[{\"key\":\"APP_VER\",\"val\":\"01.00\"}," + "{\"key\":\"VERSION\",\"val\":\"01.32\"}],\"source\":\"sqlite\",\"error\":null}"; + const char *app_higher = "{\"ok\":true,\"rows\":[{\"key\":\"VERSION\",\"val\":\"01.00\"},{\"key\":\"APP_VER\",\"val\":\"01.09\"}]}"; + const char *only_version = "{\"ok\":true,\"rows\":[{\"key\":\"VERSION\",\"val\":\"01.26\"}]}"; + const char *ps5_with_version = "{\"ok\":true,\"rows\":[{\"key\":\"VERSION\",\"val\":\"01.32\"}," + "{\"key\":\"CONTENT_VERSION\",\"val\":\"01.500.000\"}]}"; + CHECK(webui_cheat_appinfo_version(rdr2, strlen(rdr2), v, sizeof v) == 1 && strcmp(v, "01.32") == 0); + CHECK(webui_cheat_appinfo_version(app_higher, strlen(app_higher), v, sizeof v) == 1 && strcmp(v, "01.09") == 0); + CHECK(webui_cheat_appinfo_version(only_version, strlen(only_version), v, sizeof v) == 1 && strcmp(v, "01.26") == 0); + CHECK(webui_cheat_appinfo_version(ps5_with_version, strlen(ps5_with_version), v, sizeof v) == 1 && + strcmp(v, "01.500.000") == 0); +} + +static void version_pick(void) { + CHECK(strcmp(appinfo_version_pick("01.000.016", "01.32", "01.00"), "01.000.016") == 0); + CHECK(strcmp(appinfo_version_pick(NULL, "01.32", "01.00"), "01.32") == 0); + CHECK(strcmp(appinfo_version_pick("", "01.00", "01.09"), "01.09") == 0); + CHECK(strcmp(appinfo_version_pick(NULL, "01.05", "01.05"), "01.05") == 0); + CHECK(strcmp(appinfo_version_pick(NULL, "", "01.00"), "01.00") == 0); + CHECK(strcmp(appinfo_version_pick(NULL, "01.26", NULL), "01.26") == 0); + CHECK(strcmp(appinfo_version_pick(NULL, NULL, NULL), "") == 0); + CHECK(appinfo_version_cmp("01.32", "01.05") > 0); + CHECK(appinfo_version_cmp("1.10", "1.9") > 0); + CHECK(appinfo_version_cmp("01.05", "1.5") == 0); + CHECK(appinfo_version_cmp("01.00", "01.00.001") < 0); + CHECK(appinfo_version_cmp(" 01.05", "01.05") == 0); + CHECK(appinfo_version_cmp("abc", "01.00") < 0); + CHECK(appinfo_version_cmp("", "") == 0); + CHECK(appinfo_version_cmp("99999999999999999999", "1") > 0); /* no overflow */ } int main(void) { @@ -211,6 +243,7 @@ int main(void) { queries(); store(); versions(); + version_pick(); if (failures) { fprintf(stderr, "webui_cheats_store_selftest: %d failure(s)\n", failures); return 1; From a2e82d686e2e96bc001e69a96b466104c9e5e224 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:43:48 -0800 Subject: [PATCH 02/27] App and console page: show an updated PS4 game's version (#934) The Cheats screen and the console page's game list read a title's version as CONTENT_VERSION, else APP_VER. An updated PS4 game keeps APP_VER at the base's 01.00 and says its update in VERSION, so they showed 01.00 and matched cheats for the base game. Both now read CONTENT_VERSION, else the higher of VERSION and APP_VER, through one helper (installedAppVersion). The Cheats screen asks the engine for VERSION too, which any helper already answers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/api/ps5.ts | 10 ++++--- client/src/console/games/model.test.ts | 10 +++++++ client/src/console/games/model.ts | 3 ++- client/src/lib/versionNumbers.test.ts | 36 ++++++++++++++++++++++++++ client/src/lib/versionNumbers.ts | 17 ++++++++++++ 5 files changed, 71 insertions(+), 5 deletions(-) create mode 100644 client/src/lib/versionNumbers.test.ts diff --git a/client/src/api/ps5.ts b/client/src/api/ps5.ts index 6d2e482f1..226c0a0d9 100644 --- a/client/src/api/ps5.ts +++ b/client/src/api/ps5.ts @@ -27,6 +27,7 @@ import { isTauriEnv } from "../lib/tauriEnv"; import { toExtractResult, type ExtractResult } from "../lib/archiveName"; import { invoke } from "../lib/invokeLogged"; import { randomHexId } from "../lib/randomId"; +import { APPINFO_VERSION_KEYS, installedAppVersion } from "../lib/versionNumbers"; import { noteJobWatched } from "../lib/watchedJobIds"; import { getCachedIcon, setCachedIcon } from "../lib/iconMemoryCache"; import { @@ -6414,8 +6415,9 @@ export async function cheatsEngineSet( * id and install / last-opened times. Keys are appinfo.db column names; * absent ones are simply missing from the result. */ export interface AppInfoDetails { - /** CONTENT_VERSION (PS5, `01.000.016`) or APP_VER (PS4, `01.05`) — the - * same form the cheat files name their target version in. */ + /** CONTENT_VERSION (PS5, `01.000.016`), else the higher of VERSION and + * APP_VER (PS4, `01.32`: an update raises VERSION) — the same form the + * cheat files name their target version in. */ version: string | null; sizeBytes: number | null; contentId: string | null; @@ -6436,7 +6438,7 @@ export async function appInfoDetails( addr: toMgmtAddr(transferAddr), // Tauri maps camelCase to the command's snake_case `title_id`. titleId, - keys: "CONTENT_VERSION,APP_VER,#_size,#_install_time,#_last_access_time,CONTENT_ID", + keys: `${APPINFO_VERSION_KEYS},#_size,#_install_time,#_last_access_time,CONTENT_ID`, }); // A refusal throws here and lands in the catch below: no details. const res = assertOk(resp, "Read game details"); @@ -6444,7 +6446,7 @@ export async function appInfoDetails( const get = (k: string) => v.get(k) || null; const size = Number(get("#_size")); return { - version: get("CONTENT_VERSION") ?? get("APP_VER"), + version: installedAppVersion(get), sizeBytes: Number.isFinite(size) && size > 0 ? size : null, contentId: get("CONTENT_ID"), installedAt: get("#_install_time"), diff --git a/client/src/console/games/model.test.ts b/client/src/console/games/model.test.ts index 8603d9810..cb1cdf94b 100644 --- a/client/src/console/games/model.test.ts +++ b/client/src/console/games/model.test.ts @@ -119,6 +119,16 @@ describe("games model", () => { }); expect(i).toEqual({ version: "01.000.016", sizeBytes: 1073741824, lastPlayed: Date.UTC(2026, 9, 20, 12) }); expect(parseInfo({ rows: [{ key: "APP_VER", val: "01.05" }] }).version).toBe("01.05"); + // #934: an updated PS4 game keeps APP_VER at the base's 01.00 and says 01.32 in VERSION. + expect( + parseInfo({ + ok: true, + rows: [ + { key: "APP_VER", val: "01.00" }, + { key: "VERSION", val: "01.32" }, + ], + }).version, + ).toBe("01.32"); expect(parseInfo(null)).toEqual({ version: null, sizeBytes: null, lastPlayed: null }); expect(parseInfoTime("1760000000")).toBe(1760000000000); expect(parseInfoTime("1760000000000")).toBe(1760000000000); diff --git a/client/src/console/games/model.ts b/client/src/console/games/model.ts index 029ee43eb..50a3e9f3a 100644 --- a/client/src/console/games/model.ts +++ b/client/src/console/games/model.ts @@ -13,6 +13,7 @@ * time come from appinfo.db (the same keys the PC app's game page reads). */ import { compareNames } from "../../lib/collate"; +import { installedAppVersion } from "../../lib/versionNumbers"; import { ApiError, call } from "../api"; export const TILE_TITLE_ID = "PSUP00001"; @@ -163,7 +164,7 @@ export function parseInfo(raw: unknown): AppInfo { } const size = Number(v.get("#_size")); return { - version: v.get("CONTENT_VERSION") ?? v.get("APP_VER") ?? null, + version: installedAppVersion((k) => v.get(k)), sizeBytes: Number.isFinite(size) && size > 0 ? size : null, lastPlayed: parseInfoTime(v.get("#_last_access_time")), }; diff --git a/client/src/lib/versionNumbers.test.ts b/client/src/lib/versionNumbers.test.ts new file mode 100644 index 000000000..1cfb58bca --- /dev/null +++ b/client/src/lib/versionNumbers.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { APPINFO_VERSION_KEYS, compareVersions, installedAppVersion, sameVersion } from "./versionNumbers"; + +const from = (rows: Record) => (k: string) => rows[k]; + +describe("installedAppVersion", () => { + it("asks for every key it reads", () => { + expect(APPINFO_VERSION_KEYS.split(",")).toEqual(["CONTENT_VERSION", "VERSION", "APP_VER"]); + }); + + it("reads an updated PS4 game's version from VERSION (#934)", () => { + // The reporter's replies: RDR2 and ELDEN RING keep APP_VER at the base game's 01.00. + expect(installedAppVersion(from({ APP_VER: "01.00", VERSION: "01.32" }))).toBe("01.32"); + expect(installedAppVersion(from({ APP_VER: "01.00", VERSION: "01.26" }))).toBe("01.26"); + }); + + it("prefers CONTENT_VERSION, then the higher of VERSION and APP_VER", () => { + expect(installedAppVersion(from({ CONTENT_VERSION: "01.500.000" }))).toBe("01.500.000"); + expect(installedAppVersion(from({ CONTENT_VERSION: "01.000.016", APP_VER: "01.00", VERSION: "01.32" }))).toBe( + "01.000.016", + ); + expect(installedAppVersion(from({ VERSION: "01.00", APP_VER: "01.09" }))).toBe("01.09"); + expect(installedAppVersion(from({ APP_VER: "01.05" }))).toBe("01.05"); + expect(installedAppVersion(from({ VERSION: "01.26" }))).toBe("01.26"); + expect(installedAppVersion(from({ CONTENT_VERSION: "", VERSION: "", APP_VER: "01.00" }))).toBe("01.00"); + expect(installedAppVersion(from({}))).toBeNull(); + }); +}); + +describe("compareVersions / sameVersion", () => { + it("compare by numbers", () => { + expect(compareVersions("01.32", "01.05")).toBeGreaterThan(0); + expect(sameVersion("01.000.016", "1.0.16")).toBe(true); + expect(sameVersion("01.32", null)).toBe(false); + }); +}); diff --git a/client/src/lib/versionNumbers.ts b/client/src/lib/versionNumbers.ts index 4aed33366..81df8206a 100644 --- a/client/src/lib/versionNumbers.ts +++ b/client/src/lib/versionNumbers.ts @@ -21,6 +21,23 @@ export function compareVersions(a: string, b: string): number { return 0; } +/** The appinfo.db keys a title's installed version is read from (installedAppVersion). */ +export const APPINFO_VERSION_KEYS = "CONTENT_VERSION,VERSION,APP_VER"; + +/** A title's installed version from its appinfo.db values (`get` returns a key's trimmed value, + * or null/undefined/"" when absent): CONTENT_VERSION (a PS5 title's, `01.000.016`), else the + * higher of VERSION and APP_VER (a PS4 title's: an installed update raises VERSION, `01.32`, + * while APP_VER stays at the base game's `01.00`, #934). The helper and the engine pick the same + * way. Null when none is there. */ +export function installedAppVersion(get: (key: string) => string | null | undefined): string | null { + const content = get("CONTENT_VERSION"); + if (content) return content; + const version = get("VERSION"); + const app = get("APP_VER"); + if (version && app) return compareVersions(version, app) >= 0 ? version : app; + return version || app || null; +} + export function sameVersion(a: string | null | undefined, b: string | null | undefined): boolean { if (!a || !b) return false; if (versionParts(a).length === 0 || versionParts(b).length === 0) return false; From 70554ff1d6c6316f64b1bb28e8e907bbe159084e Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:47:05 -0800 Subject: [PATCH 03/27] Engine: read a PS4 game's installed update from VERSION (#934) The collection read a title's version as APP_VER, else CONTENT_VERSION, and the install checks read APP_VER only. An updated PS4 game keeps APP_VER at the base's 01.00 and says its update in VERSION, so the game page showed 01.00 and offered the update it already has, and the install preflight named the base version. AppInfoRows now has installed_version (CONTENT_VERSION, else the higher of VERSION and APP_VER) and app_version (the higher of VERSION and APP_VER). The collection uses the first; the install checks use the second. The engine just asks for more keys, which every helper already answers, so this works before the helper is updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../crates/ps5upload-core/src/diagnostics.rs | 112 ++++++++++++++++++ .../src/collection/console.rs | 3 +- .../ps5upload-engine/src/collection_api.rs | 23 ++-- .../ps5upload-engine/src/pkg_install.rs | 29 ++--- 4 files changed, 135 insertions(+), 32 deletions(-) diff --git a/engine/crates/ps5upload-core/src/diagnostics.rs b/engine/crates/ps5upload-core/src/diagnostics.rs index 4a62b71b9..6b8a96b2f 100644 --- a/engine/crates/ps5upload-core/src/diagnostics.rs +++ b/engine/crates/ps5upload-core/src/diagnostics.rs @@ -377,6 +377,50 @@ pub struct AppInfoRows { pub error: Option, } +/// The appinfo.db keys a title's installed version is read from (see +/// [`AppInfoRows::installed_version`]). Any helper answers them: the query takes any key list. +pub const APPINFO_VERSION_KEYS: &str = "CONTENT_VERSION,VERSION,APP_VER"; + +/// The keys a PS4-form (`01.32`) version is read from (see [`AppInfoRows::app_version`]). +pub const APPINFO_APP_VERSION_KEYS: &str = "VERSION,APP_VER"; + +impl AppInfoRows { + /// A key's value, trimmed; `None` when absent or blank. + pub fn value(&self, key: &str) -> Option<&str> { + self.rows + .iter() + .find(|r| r.key == key) + .map(|r| r.val.trim()) + .filter(|v| !v.is_empty()) + } + + /// A PS4 title's version: the higher of `VERSION` and `APP_VER`. An installed update raises + /// `VERSION` (`01.32`) while `APP_VER` stays at the base game's `01.00` (#934); the higher + /// of the two also keeps a title whose `APP_VER` is the one that moved. `None` when neither + /// is there. + pub fn app_version(&self) -> Option { + use crate::patch_verify::parse_app_ver; + match (self.value("VERSION"), self.value("APP_VER")) { + (Some(v), Some(a)) => match (parse_app_ver(v), parse_app_ver(a)) { + (Some(x), Some(y)) if y > x => Some(a), + (None, Some(_)) => Some(a), + _ => Some(v), + }, + (v, a) => v.or(a), + } + .map(str::to_string) + } + + /// A title's installed version: `CONTENT_VERSION` (a PS5 title's, `01.000.016`), else + /// [`Self::app_version`] (a PS4 title's, `01.32`). The helper's own readers pick the same way + /// (payload/include/appinfo_version.h). `None` when the rows say none. + pub fn installed_version(&self) -> Option { + self.value("CONTENT_VERSION") + .map(str::to_string) + .or_else(|| self.app_version()) + } +} + /// Read per-title metadata out of appinfo.db, the database behind /// Settings → Storage. /// @@ -759,6 +803,74 @@ mod tests { assert_eq!(rows.rows[0].key, "CONTENT_VERSION"); assert_eq!(rows.rows[0].val, "01.00"); } + + fn rows(pairs: &[(&str, &str)]) -> AppInfoRows { + AppInfoRows { + ok: true, + title_id: String::new(), + rows: pairs + .iter() + .map(|(k, v)| AppInfoRow { + key: k.to_string(), + val: v.to_string(), + }) + .collect(), + source: None, + error: None, + } + } + + #[test] + fn an_updated_ps4_game_reads_its_version_from_version() { + // #934, the reporter's replies: RDR2 and ELDEN RING keep APP_VER at the base's 01.00. + let rdr2: AppInfoRows = serde_json::from_str( + r#"{"ok":true,"title_id":"CUSA03041","rows":[{"key":"APP_VER","val":"01.00"}, + {"key":"VERSION","val":"01.32"}],"source":"sqlite","error":null}"#, + ) + .unwrap(); + assert_eq!(rdr2.installed_version().as_deref(), Some("01.32")); + assert_eq!(rdr2.app_version().as_deref(), Some("01.32")); + let elden = rows(&[("APP_VER", "01.00"), ("VERSION", "01.26")]); + assert_eq!(elden.installed_version().as_deref(), Some("01.26")); + } + + #[test] + fn installed_version_prefers_content_version_then_the_higher_ps4_one() { + // A PS5 title. + let ps5 = rows(&[("CONTENT_VERSION", "01.500.000")]); + assert_eq!(ps5.installed_version().as_deref(), Some("01.500.000")); + assert_eq!(ps5.app_version(), None); + let both = rows(&[("APP_VER", "01.00"), ("CONTENT_VERSION", "01.000.016")]); + assert_eq!(both.installed_version().as_deref(), Some("01.000.016")); + // APP_VER the one that moved: still the higher. + let app_moved = rows(&[("VERSION", "01.00"), ("APP_VER", "01.09")]); + assert_eq!(app_moved.installed_version().as_deref(), Some("01.09")); + // Only one of the two, blanks and junk. + assert_eq!( + rows(&[("APP_VER", " 01.05 ")]) + .installed_version() + .as_deref(), + Some("01.05") + ); + assert_eq!( + rows(&[("VERSION", "01.26")]).installed_version().as_deref(), + Some("01.26") + ); + assert_eq!( + rows(&[("VERSION", " "), ("APP_VER", "01.00")]) + .installed_version() + .as_deref(), + Some("01.00") + ); + assert_eq!( + rows(&[("VERSION", "x"), ("APP_VER", "01.00")]) + .app_version() + .as_deref(), + Some("01.00") + ); + assert_eq!(rows(&[]).installed_version(), None); + assert_eq!(rows(&[("CONTENT_ID", "X")]).installed_version(), None); + } } #[cfg(test)] diff --git a/engine/crates/ps5upload-engine/src/collection/console.rs b/engine/crates/ps5upload-engine/src/collection/console.rs index f67803e21..4dfa2256f 100644 --- a/engine/crates/ps5upload-engine/src/collection/console.rs +++ b/engine/crates/ps5upload-engine/src/collection/console.rs @@ -13,7 +13,8 @@ use super::{Game, Location}; pub struct ConsoleTitle { /// The console knows the title (it has `/user/app/`). pub installed: bool, - /// Its installed version (`APP_VER`), when it could be read. + /// Its installed version (`CONTENT_VERSION`, else the higher of `VERSION` and `APP_VER`), + /// when it could be read. pub version: Option, /// An update is installed (`/user/patch/`). pub patch_installed: bool, diff --git a/engine/crates/ps5upload-engine/src/collection_api.rs b/engine/crates/ps5upload-engine/src/collection_api.rs index 4ed01d5d7..32ab53968 100644 --- a/engine/crates/ps5upload-engine/src/collection_api.rs +++ b/engine/crates/ps5upload-engine/src/collection_api.rs @@ -529,8 +529,6 @@ pub struct ConsoleQuery { addr: String, } -/// A title's installed version, normalized like the collection's: `APP_VER` (PS4) or -/// `CONTENT_VERSION` (PS5). `None` when it could not be read. /// The console's titles: upper-case title ID → the path it was registered from, if any. A title /// whose app folder is on the internal or an extended drive counts too: the installed-apps list /// counts those, and two reads that disagreed made a game on the M.2 drive flip between @@ -662,21 +660,16 @@ pub(crate) fn read_title( t } -/// The installed version: `APP_VER` (PS4) or `CONTENT_VERSION` (PS5), normalized. `Ok(None)` -/// when the console has neither; `Err` when it could not be asked. +/// The installed version, normalized: `CONTENT_VERSION` (PS5), else the higher of `VERSION` and +/// `APP_VER` (PS4: an update raises `VERSION` and leaves `APP_VER` at the base's, #934). +/// `Ok(None)` when the console has none; `Err` when it could not be asked. Any helper answers +/// these keys, so this needs no helper update. fn installed_version(addr: &str, title_id: &str) -> Result, String> { + use ps5upload_core::diagnostics::{appinfo_query, APPINFO_VERSION_KEYS}; let rows = - ps5upload_core::diagnostics::appinfo_query(addr, title_id, Some("APP_VER,CONTENT_VERSION")) - .map_err(|e| format!("{e:#}"))?; - let get = |k: &str| { - rows.rows - .iter() - .find(|r| r.key == k) - .map(|r| r.val.trim().to_string()) - .filter(|v| !v.is_empty()) - }; - Ok(get("APP_VER") - .or_else(|| get("CONTENT_VERSION")) + appinfo_query(addr, title_id, Some(APPINFO_VERSION_KEYS)).map_err(|e| format!("{e:#}"))?; + Ok(rows + .installed_version() .map(|v| ps5upload_pkg::kind::normalize_version(&v))) } diff --git a/engine/crates/ps5upload-engine/src/pkg_install.rs b/engine/crates/ps5upload-engine/src/pkg_install.rs index 31ee1aa48..c253c90dc 100644 --- a/engine/crates/ps5upload-engine/src/pkg_install.rs +++ b/engine/crates/ps5upload-engine/src/pkg_install.rs @@ -2478,15 +2478,13 @@ pub(crate) enum InstalledState { Unknown, } +/// The version is the PS4 form (`01.32`, [`read_installed_app_ver`]). pub(crate) fn read_installed_state(mgmt_addr: &str, title_id: &str) -> InstalledState { - match ps5upload_core::diagnostics::appinfo_query(mgmt_addr, title_id, Some("APP_VER")) { + use ps5upload_core::diagnostics::{appinfo_query, APPINFO_APP_VERSION_KEYS}; + match appinfo_query(mgmt_addr, title_id, Some(APPINFO_APP_VERSION_KEYS)) { Err(_) => InstalledState::Unknown, Ok(rows) => rows - .rows - .into_iter() - .find(|r| r.key == "APP_VER") - .map(|r| r.val) - .filter(|v| !v.trim().is_empty()) + .app_version() .map_or(InstalledState::Absent, InstalledState::Installed), } } @@ -2739,17 +2737,16 @@ pub(crate) fn artifact_wait_loop( } } -/// Read a title's installed `APP_VER`, or `None` when it cannot be read (title -/// absent, payload too old, console busy). `None` deliberately means "unknown" -/// and never "failed" — see patch_verify, which stays inconclusive on it. +/// Read a title's installed app version (`01.32`): the higher of appinfo.db's `VERSION` and +/// `APP_VER`, since an installed PS4 update raises `VERSION` and leaves `APP_VER` at the base +/// game's (#934). `None` when it cannot be read (title absent, payload too old, console busy). +/// `None` deliberately means "unknown" and never "failed" — see patch_verify, which stays +/// inconclusive on it. pub(crate) fn read_installed_app_ver(mgmt_addr: &str, title_id: &str) -> Option { - let rows = - ps5upload_core::diagnostics::appinfo_query(mgmt_addr, title_id, Some("APP_VER")).ok()?; - rows.rows - .into_iter() - .find(|r| r.key == "APP_VER") - .map(|r| r.val) - .filter(|v| !v.trim().is_empty()) + use ps5upload_core::diagnostics::{appinfo_query, APPINFO_APP_VERSION_KEYS}; + appinfo_query(mgmt_addr, title_id, Some(APPINFO_APP_VERSION_KEYS)) + .ok()? + .app_version() } /// What the wait for a patch to take effect found. From c1355531079916ea369be9279fab2473defc3c91 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:55:50 -0800 Subject: [PATCH 04/27] Backup restore: a restore that put nothing back is not a success restore_from_manifest counted only the files it copied back and the reply was ok:true whenever the manifest could be read. A snapshot whose every entry was skipped (a path outside the writable folders, a damaged line) or failed (missing file, write error) answered ok:true with restored:0, and the app said "Restored 0 files" as if it had worked. The helper now counts every manifest line as restored, skipped or failed, and the reply (backup_restore_reply, host-tested) is ok:false with the reason when nothing was restored, and ok:true with "partial":true and the counts when only some files came back. The old fields stay. The engine passes the new counts through and also refuses ok:true with restored:0 from an older helper; the Backup screen says how many files could not be restored after a partial restore. Tests: backup_selftest covers the counts and every reply shape; engine unit tests cover the partial, empty and older-helper replies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- Makefile | 2 +- client/src/api/ps5.ts | 6 ++ client/src/i18n/locales/ar.ts | 1 + client/src/i18n/locales/bn.ts | 1 + client/src/i18n/locales/de.ts | 1 + client/src/i18n/locales/en.ts | 1 + client/src/i18n/locales/es.ts | 1 + client/src/i18n/locales/fa.ts | 1 + client/src/i18n/locales/fr.ts | 1 + client/src/i18n/locales/hi.ts | 1 + client/src/i18n/locales/hu.ts | 1 + client/src/i18n/locales/id.ts | 1 + client/src/i18n/locales/it.ts | 1 + client/src/i18n/locales/ja.ts | 1 + client/src/i18n/locales/ko.ts | 1 + client/src/i18n/locales/pl.ts | 1 + client/src/i18n/locales/pt-BR.ts | 1 + client/src/i18n/locales/ru.ts | 1 + client/src/i18n/locales/th.ts | 1 + client/src/i18n/locales/tr.ts | 1 + client/src/i18n/locales/vi.ts | 1 + client/src/i18n/locales/zh-CN.ts | 1 + client/src/i18n/locales/zh-TW.ts | 1 + client/src/screens/Backup/index.tsx | 17 ++-- engine/crates/ps5upload-core/src/backup.rs | 78 ++++++++++++++++--- .../crates/ps5upload-engine/api/openapi.json | 3 + engine/crates/ps5upload-engine/src/lib.rs | 3 + payload/include/backup.h | 21 ++++- payload/src/backup.c | 72 +++++++++++++---- payload/src/runtime.c | 27 ++++--- payload/tests/backup_selftest.c | 76 ++++++++++++++++++ scripts/i18n-source-hashes.json | 1 + 32 files changed, 281 insertions(+), 46 deletions(-) diff --git a/Makefile b/Makefile index 80f8f6e47..59e76dcd2 100644 --- a/Makefile +++ b/Makefile @@ -1254,7 +1254,7 @@ test-payload: payload -o $(SELFTEST_DIR)/ps5upload-backup-selftest \ $(PAYLOAD_DIR)/tests/backup_selftest.c @$(RUN_LIMITED) $(SELFTEST_DIR)/ps5upload-backup-selftest - @echo "✓ a snapshot restores byte for byte, the newest five are kept, the list stays valid and inside its buffer" + @echo "✓ a snapshot restores byte for byte, the newest five are kept, the list stays valid and inside its buffer; a restore that put nothing back is not ok" @echo "Running file replace self-test (host build)..." @cc -O2 -Wall -Wextra -Werror -I$(PAYLOAD_DIR)/include \ -o $(SELFTEST_DIR)/ps5upload-atomic-file-selftest \ diff --git a/client/src/api/ps5.ts b/client/src/api/ps5.ts index 226c0a0d9..6c5f84122 100644 --- a/client/src/api/ps5.ts +++ b/client/src/api/ps5.ts @@ -455,6 +455,12 @@ export interface BackupRestoreResult { ok: boolean; tag: string; restored: number; + /** Entries not used (outside the allowed folders, damaged); absent from an older engine. */ + skipped?: number; + /** Files that could not be written back. */ + failed?: number; + /** Some files came back and some did not. */ + partial?: boolean; } /** Snapshot a file or directory tree under a backup tag. */ diff --git a/client/src/i18n/locales/ar.ts b/client/src/i18n/locales/ar.ts index 0368a3594..a10f4f1a7 100644 --- a/client/src/i18n/locales/ar.ts +++ b/client/src/i18n/locales/ar.ts @@ -9271,6 +9271,7 @@ rp_users_add_hint: "للعب باسم مستخدم آخر أيضًا، سجّل "saves_folders_none": "لا توجد نسخة احتياطية لهذا المجلد بعد.", "saves_folders_before_restore": "محفوظة قبل استعادة", "saves_folders_legacy": "من قبل حفظ النسخ لكل PS5 على حدة", +backup_restore_partial: "تمت استعادة {count} ملفًا؛ تعذّرت استعادة {missed}", }; export default ar; diff --git a/client/src/i18n/locales/bn.ts b/client/src/i18n/locales/bn.ts index 8b5733e9c..52c8960d3 100644 --- a/client/src/i18n/locales/bn.ts +++ b/client/src/i18n/locales/bn.ts @@ -9271,6 +9271,7 @@ rp_users_add_hint: "অন্য ব্যবহারকারী হিসে "saves_folders_none": "এই ফোল্ডারের এখনও কোনো ব্যাকআপ নেই।", "saves_folders_before_restore": "পুনরুদ্ধারের আগে রাখা", "saves_folders_legacy": "প্রতিটি PS5-এর জন্য আলাদা ব্যাকআপ রাখার আগের", +backup_restore_partial: "{count}টি ফাইল পুনরুদ্ধার করা হয়েছে; {missed}টি পুনরুদ্ধার করা যায়নি", }; export default bn; diff --git a/client/src/i18n/locales/de.ts b/client/src/i18n/locales/de.ts index 938a3dfc6..047f15606 100644 --- a/client/src/i18n/locales/de.ts +++ b/client/src/i18n/locales/de.ts @@ -9279,6 +9279,7 @@ rp_users_add_hint: "Um auch als anderer Benutzer zu spielen, melde dich auf der "saves_folders_none": "Von diesem Ordner gibt es noch keine Sicherung.", "saves_folders_before_restore": "vor einer Wiederherstellung behalten", "saves_folders_legacy": "aus der Zeit vor Sicherungen pro PS5", +backup_restore_partial: "{count} Dateien wiederhergestellt; {missed} konnten nicht wiederhergestellt werden", }; export default de; diff --git a/client/src/i18n/locales/en.ts b/client/src/i18n/locales/en.ts index ecdcc4852..d6b7fadb1 100644 --- a/client/src/i18n/locales/en.ts +++ b/client/src/i18n/locales/en.ts @@ -3369,6 +3369,7 @@ schedule_fired_body: "Schedule fired.", backup_working: "Working...", backup_snapshot_ok: "Snapshotted {files} files ({bytes})", backup_restore_ok: "Restored {count} files", + backup_restore_partial: "Restored {count} files; {missed} could not be restored", backup_delete_ok: "Snapshot deleted", backup_restore_confirm_title: "Restore snapshot?", backup_restore_confirm_msg: diff --git a/client/src/i18n/locales/es.ts b/client/src/i18n/locales/es.ts index 980a84f5f..fbc70b7a9 100644 --- a/client/src/i18n/locales/es.ts +++ b/client/src/i18n/locales/es.ts @@ -9224,6 +9224,7 @@ rp_users_add_hint: "Para jugar también como otro usuario, inicia sesión con es "saves_folders_none": "Todavía no hay copia de esta carpeta.", "saves_folders_before_restore": "guardada antes de restaurar", "saves_folders_legacy": "de antes de guardar copias por PS5", +backup_restore_partial: "Se restauraron {count} archivos; {missed} no se pudieron restaurar", }; export default es; diff --git a/client/src/i18n/locales/fa.ts b/client/src/i18n/locales/fa.ts index 2abe041aa..5563851ee 100644 --- a/client/src/i18n/locales/fa.ts +++ b/client/src/i18n/locales/fa.ts @@ -9549,6 +9549,7 @@ rp_users_add_hint: "برای بازی به‌عنوان کاربری دیگر ن "saves_folders_none": "هنوز پشتیبانی از این پوشه نیست.", "saves_folders_before_restore": "نگه‌داشته پیش از بازگردانی", "saves_folders_legacy": "از پیش از نگه‌داری پشتیبان‌ها برای هر PS5", +backup_restore_partial: "{count} فایل بازگردانی شد؛ {missed} مورد بازگردانی نشد", }; export default fa; diff --git a/client/src/i18n/locales/fr.ts b/client/src/i18n/locales/fr.ts index 934935622..9562593b6 100644 --- a/client/src/i18n/locales/fr.ts +++ b/client/src/i18n/locales/fr.ts @@ -9287,6 +9287,7 @@ rp_users_add_hint: "Pour jouer aussi avec un autre utilisateur, connectez-vous "saves_folders_none": "Aucune copie de ce dossier pour l’instant.", "saves_folders_before_restore": "conservée avant une restauration", "saves_folders_legacy": "d’avant les copies par PS5", +backup_restore_partial: "{count} fichiers restaurés ; {missed} n'ont pas pu être restaurés", }; export default fr; diff --git a/client/src/i18n/locales/hi.ts b/client/src/i18n/locales/hi.ts index 27c186466..5efb95b21 100644 --- a/client/src/i18n/locales/hi.ts +++ b/client/src/i18n/locales/hi.ts @@ -9285,6 +9285,7 @@ rp_users_add_hint: "किसी दूसरे उपयोगकर्ता "saves_folders_none": "इस फ़ोल्डर का अभी कोई बैकअप नहीं है।", "saves_folders_before_restore": "पुनर्स्थापना से पहले रखा गया", "saves_folders_legacy": "हर PS5 के लिए अलग बैकअप रखने से पहले का", +backup_restore_partial: "{count} फ़ाइलें पुनर्स्थापित की गईं; {missed} पुनर्स्थापित नहीं की जा सकीं", }; export default hi; diff --git a/client/src/i18n/locales/hu.ts b/client/src/i18n/locales/hu.ts index 1f18314b7..caba1637d 100644 --- a/client/src/i18n/locales/hu.ts +++ b/client/src/i18n/locales/hu.ts @@ -9563,6 +9563,7 @@ rp_users_add_hint: "Ha másik felhasználóként is játszanál, jelentkezz be a "saves_folders_none": "Erről a mappáról még nincs mentés.", "saves_folders_before_restore": "visszaállítás előtt megtartva", "saves_folders_legacy": "abból az időből, mielőtt a mentések PS5-önként külön kerültek", +backup_restore_partial: "{count} fájl visszaállítva; {missed} nem állítható vissza", }; export default hu; diff --git a/client/src/i18n/locales/id.ts b/client/src/i18n/locales/id.ts index 78b123681..22d153fd7 100644 --- a/client/src/i18n/locales/id.ts +++ b/client/src/i18n/locales/id.ts @@ -9280,6 +9280,7 @@ rp_users_add_hint: "Untuk bermain juga sebagai pengguna lain, masuk ke pengguna "saves_folders_none": "Belum ada cadangan folder ini.", "saves_folders_before_restore": "disimpan sebelum pemulihan", "saves_folders_legacy": "dari sebelum cadangan disimpan per PS5", +backup_restore_partial: "{count} berkas dipulihkan; {missed} tidak dapat dipulihkan", }; export default id; diff --git a/client/src/i18n/locales/it.ts b/client/src/i18n/locales/it.ts index 3adc16c99..480f01ef9 100644 --- a/client/src/i18n/locales/it.ts +++ b/client/src/i18n/locales/it.ts @@ -9224,6 +9224,7 @@ rp_users_add_hint: "Per giocare anche come un altro utente, accedi con quell’u "saves_folders_none": "Ancora nessun backup di questa cartella.", "saves_folders_before_restore": "conservato prima di un ripristino", "saves_folders_legacy": "di prima dei backup separati per PS5", +backup_restore_partial: "{count} file ripristinati; impossibile ripristinarne {missed}", }; export default it; diff --git a/client/src/i18n/locales/ja.ts b/client/src/i18n/locales/ja.ts index eeca1dbc0..66bac274d 100644 --- a/client/src/i18n/locales/ja.ts +++ b/client/src/i18n/locales/ja.ts @@ -9290,6 +9290,7 @@ rp_users_add_hint: "別のユーザーでもプレイするには、PS5 でそ "saves_folders_none": "このフォルダーのバックアップはまだありません。", "saves_folders_before_restore": "復元前に保存", "saves_folders_legacy": "PS5 ごとの保存より前のもの", +backup_restore_partial: "{count}個のファイルを復元しました。{missed}個は復元できませんでした", }; export default ja; diff --git a/client/src/i18n/locales/ko.ts b/client/src/i18n/locales/ko.ts index 7515001cd..dce63cdaf 100644 --- a/client/src/i18n/locales/ko.ts +++ b/client/src/i18n/locales/ko.ts @@ -9288,6 +9288,7 @@ rp_users_add_hint: "다른 사용자로도 플레이하려면 PS5에서 그 사 "saves_folders_none": "이 폴더의 백업이 아직 없습니다.", "saves_folders_before_restore": "복원 전에 보관됨", "saves_folders_legacy": "PS5별로 보관하기 전의 백업", +backup_restore_partial: "{count}개 파일을 복원했습니다. {missed}개는 복원하지 못했습니다", }; export default ko; diff --git a/client/src/i18n/locales/pl.ts b/client/src/i18n/locales/pl.ts index 8c618766a..f7342984f 100644 --- a/client/src/i18n/locales/pl.ts +++ b/client/src/i18n/locales/pl.ts @@ -9508,6 +9508,7 @@ rp_users_add_hint: "Aby grać także jako inny użytkownik, zaloguj się na nim "saves_folders_none": "Brak jeszcze kopii tego folderu.", "saves_folders_before_restore": "zachowana przed przywróceniem", "saves_folders_legacy": "sprzed rozdzielenia kopii według PS5", +backup_restore_partial: "Przywrócono {count} plików; {missed} nie udało się przywrócić", }; export default pl; diff --git a/client/src/i18n/locales/pt-BR.ts b/client/src/i18n/locales/pt-BR.ts index 6255569d3..25898c52a 100644 --- a/client/src/i18n/locales/pt-BR.ts +++ b/client/src/i18n/locales/pt-BR.ts @@ -9286,6 +9286,7 @@ rp_users_add_hint: "Para jogar também como outro usuário, entre com esse usuá "saves_folders_none": "Ainda não há backup desta pasta.", "saves_folders_before_restore": "guardado antes de uma restauração", "saves_folders_legacy": "de antes dos backups serem separados por PS5", +backup_restore_partial: "{count} arquivos restaurados; {missed} não puderam ser restaurados", }; export default pt_BR; diff --git a/client/src/i18n/locales/ru.ts b/client/src/i18n/locales/ru.ts index 4354639da..a8656e94f 100644 --- a/client/src/i18n/locales/ru.ts +++ b/client/src/i18n/locales/ru.ts @@ -9224,6 +9224,7 @@ rp_users_add_hint: "Чтобы играть и за другого пользо "saves_folders_none": "Копий этой папки пока нет.", "saves_folders_before_restore": "сохранено перед восстановлением", "saves_folders_legacy": "из времени, когда копии ещё не разделялись по PS5", +backup_restore_partial: "Восстановлено файлов: {count}; не удалось восстановить: {missed}", }; export default ru; diff --git a/client/src/i18n/locales/th.ts b/client/src/i18n/locales/th.ts index 5e6ed8c7d..696d9799e 100644 --- a/client/src/i18n/locales/th.ts +++ b/client/src/i18n/locales/th.ts @@ -9278,6 +9278,7 @@ rp_users_add_hint: "หากต้องการเล่นในฐานะ "saves_folders_none": "โฟลเดอร์นี้ยังไม่มีข้อมูลสำรอง", "saves_folders_before_restore": "เก็บไว้ก่อนกู้คืน", "saves_folders_legacy": "จากก่อนที่จะแยกข้อมูลสำรองตาม PS5", +backup_restore_partial: "กู้คืน {count} ไฟล์แล้ว กู้คืนไม่ได้ {missed} ไฟล์", }; export default th; diff --git a/client/src/i18n/locales/tr.ts b/client/src/i18n/locales/tr.ts index 2bef5050e..bd4abac2e 100644 --- a/client/src/i18n/locales/tr.ts +++ b/client/src/i18n/locales/tr.ts @@ -9278,6 +9278,7 @@ rp_users_add_hint: "Başka bir kullanıcıyla da oynamak için PS5'te o kullanı "saves_folders_none": "Bu klasörün henüz yedeği yok.", "saves_folders_before_restore": "geri yüklemeden önce tutuldu", "saves_folders_legacy": "yedekler PS5 başına tutulmadan önceki", +backup_restore_partial: "{count} dosya geri yüklendi; {missed} dosya geri yüklenemedi", }; export default tr; diff --git a/client/src/i18n/locales/vi.ts b/client/src/i18n/locales/vi.ts index 9104b35cb..a6020dace 100644 --- a/client/src/i18n/locales/vi.ts +++ b/client/src/i18n/locales/vi.ts @@ -9273,6 +9273,7 @@ rp_users_add_hint: "Để chơi bằng cả người dùng khác, hãy đăng nh "saves_folders_none": "Thư mục này chưa có bản sao lưu.", "saves_folders_before_restore": "giữ lại trước khi khôi phục", "saves_folders_legacy": "từ trước khi bản sao lưu được tách theo từng PS5", +backup_restore_partial: "Đã khôi phục {count} tệp; không thể khôi phục {missed} tệp", }; export default vi; diff --git a/client/src/i18n/locales/zh-CN.ts b/client/src/i18n/locales/zh-CN.ts index a4ceda67b..89a214b58 100644 --- a/client/src/i18n/locales/zh-CN.ts +++ b/client/src/i18n/locales/zh-CN.ts @@ -9230,6 +9230,7 @@ rp_users_add_hint: "若也想以其他用户游玩,请在 PS5 上登录该用 "saves_folders_none": "这个文件夹还没有备份。", "saves_folders_before_restore": "恢复前保留", "saves_folders_legacy": "按 PS5 分别保存之前的备份", +backup_restore_partial: "已恢复 {count} 个文件;{missed} 个无法恢复", }; export default zh_CN; diff --git a/client/src/i18n/locales/zh-TW.ts b/client/src/i18n/locales/zh-TW.ts index c4208b7c7..8cd71552d 100644 --- a/client/src/i18n/locales/zh-TW.ts +++ b/client/src/i18n/locales/zh-TW.ts @@ -9224,6 +9224,7 @@ rp_users_add_hint: "若也想以其他使用者遊玩,請在 PS5 上登入該 "saves_folders_none": "這個資料夾還沒有備份。", "saves_folders_before_restore": "還原前保留", "saves_folders_legacy": "按 PS5 分別保存之前的備份", +backup_restore_partial: "已還原 {count} 個檔案;{missed} 個無法還原", }; export default zh_TW; diff --git a/client/src/screens/Backup/index.tsx b/client/src/screens/Backup/index.tsx index 87f1f712d..55a8eb7bc 100644 --- a/client/src/screens/Backup/index.tsx +++ b/client/src/screens/Backup/index.tsx @@ -247,12 +247,19 @@ export function SnapshotsPanel({ prefill }: { prefill?: SnapshotPrefill | null } { kind: "backup-restore", origin: "backup", label: tr("backup_task_restore", { tag: entry.tag }, "Restore {tag}"), consoleId: addr }, () => backupRestore(entry.tag, entry.timestamp, addr), ); + const missed = (result.skipped ?? 0) + (result.failed ?? 0); setActionMsg( - tr( - "backup_restore_ok", - { count: result.restored }, - `Restored ${result.restored} files`, - ), + result.partial && missed > 0 + ? tr( + "backup_restore_partial", + { count: result.restored, missed }, + `Restored ${result.restored} files; ${missed} could not be restored`, + ) + : tr( + "backup_restore_ok", + { count: result.restored }, + `Restored ${result.restored} files`, + ), ); } catch (e) { setError(humanizePs5Error(String(e))); diff --git a/engine/crates/ps5upload-core/src/backup.rs b/engine/crates/ps5upload-core/src/backup.rs index fe0c7d24f..494a4aac3 100644 --- a/engine/crates/ps5upload-core/src/backup.rs +++ b/engine/crates/ps5upload-core/src/backup.rs @@ -46,10 +46,40 @@ pub struct BackupRestoreResult { pub tag: String, #[serde(default)] pub restored: i32, + /// Manifest entries not used (outside the writable folders, damaged). 0 from an older helper, + /// which did not count them. + #[serde(default)] + pub skipped: i32, + /// Files that could not be written back (missing in the snapshot, a write error). + #[serde(default)] + pub failed: i32, + /// Some files came back and some did not (`ok` is still true). + #[serde(default)] + pub partial: bool, #[serde(default)] pub err: String, } +/// The restore's verdict: an error when the helper said it failed, or when nothing was restored. +/// An older helper answered ok:true with restored:0 when every entry was skipped or failed; that +/// is no success either. +fn restore_verdict(parsed: BackupRestoreResult) -> Result { + if !parsed.ok { + bail!( + "restore failed: {}", + if parsed.err.is_empty() { + "unknown error" + } else { + &parsed.err + } + ); + } + if parsed.restored <= 0 { + bail!("restore failed: nothing was restored"); + } + Ok(parsed) +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BackupDeleteResult { pub ok: bool, @@ -133,18 +163,7 @@ pub fn backup_restore(addr: &str, tag: &str, timestamp: i64) -> Result Result<()> { @@ -246,4 +265,39 @@ mod tests { let l: BackupList = serde_json::from_str(r#"{"snapshots":[]}"#).unwrap(); assert!(l.snapshots.is_empty()); } + + fn restore(json: &str) -> Result { + restore_verdict(serde_json::from_str(json).unwrap()) + } + + #[test] + fn a_partial_restore_keeps_its_counts() { + let r = restore( + r#"{"ok":true,"tag":"t","restored":2,"skipped":1,"failed":3,"partial":true,"err":""}"#, + ) + .unwrap(); + assert_eq!( + (r.restored, r.skipped, r.failed, r.partial), + (2, 1, 3, true) + ); + } + + #[test] + fn a_restore_of_nothing_is_an_error() { + let e = restore( + r#"{"ok":false,"tag":"t","restored":0,"skipped":2,"failed":0,"partial":false, + "err":"nothing was restored: 0 file(s) could not be written back, 2 entries were skipped (outside the allowed folders or damaged)"}"#, + ) + .unwrap_err(); + assert!(format!("{e:#}").contains("2 entries were skipped"), "{e:#}"); + // An older helper said ok:true with restored:0 for the same thing. + let e = restore(r#"{"ok":true,"tag":"t","restored":0,"err":""}"#).unwrap_err(); + assert!(format!("{e:#}").contains("nothing was restored"), "{e:#}"); + // An older helper's whole restore still parses, with zero for the new counts. + let r = restore(r#"{"ok":true,"tag":"t","restored":3,"err":""}"#).unwrap(); + assert_eq!( + (r.restored, r.skipped, r.failed, r.partial), + (3, 0, 0, false) + ); + } } diff --git a/engine/crates/ps5upload-engine/api/openapi.json b/engine/crates/ps5upload-engine/api/openapi.json index 838aa95d0..8c165baeb 100644 --- a/engine/crates/ps5upload-engine/api/openapi.json +++ b/engine/crates/ps5upload-engine/api/openapi.json @@ -31413,10 +31413,13 @@ "application/json": { "schema": { "properties": { + "failed": {}, "ok": { "type": "boolean" }, + "partial": {}, "restored": {}, + "skipped": {}, "tag": {} }, "type": "object" diff --git a/engine/crates/ps5upload-engine/src/lib.rs b/engine/crates/ps5upload-engine/src/lib.rs index 67734f871..3f08a08bb 100644 --- a/engine/crates/ps5upload-engine/src/lib.rs +++ b/engine/crates/ps5upload-engine/src/lib.rs @@ -9590,6 +9590,9 @@ async fn backup_restore_handler( "ok": true, "tag": result.tag, "restored": result.restored, + "skipped": result.skipped, + "failed": result.failed, + "partial": result.partial, })), ) .into_response(), diff --git a/payload/include/backup.h b/payload/include/backup.h index 099013fa7..388d93fce 100644 --- a/payload/include/backup.h +++ b/payload/include/backup.h @@ -22,9 +22,28 @@ int backup_snapshot(const char *tag, const char *src_path, int backup_list(const char *tag_filter, char *buf, size_t cap, size_t *written); -/* Restore a snapshot by tag+timestamp. Returns 0 on success. */ +/* What a restore did with the snapshot's manifest lines. */ +typedef struct { + int restored; /* files written back to their paths */ + int skipped; /* lines not used: no tab, a path outside the writable roots, a bad name, too long */ + int failed; /* files that could not be copied back (missing in the snapshot, a write error) */ +} backup_restore_counts_t; + +/* Restore a snapshot by tag+timestamp. Returns 0 when its manifest was read to the end (whatever + * each line came to: see `out`), -1 when the snapshot or its manifest is missing, BACKUP_CANCELLED. + * `out` (may be NULL) holds the counts so far in every case. */ +int backup_restore_ex(const char *tag, int64_t timestamp, backup_restore_counts_t *out); + +/* backup_restore_ex with only the restored count. */ int backup_restore(const char *tag, int64_t timestamp, int *out_restored); +/* The BACKUP_RESTORE reply for a restore that returned `rc` with `c`: `tag_json` is the tag already + * JSON-escaped. ok is true only when at least one file was restored; "partial" is true when some + * lines were not restored too. A restore that restored nothing (an empty manifest, every line + * skipped or failed) is ok:false with a reason in "err". Returns the length written (snprintf). */ +int backup_restore_reply(char *out, size_t cap, const char *tag_json, int rc, + const backup_restore_counts_t *c); + /* Delete a snapshot by tag+timestamp. Returns 0 on success. */ int backup_delete(const char *tag, int64_t timestamp); diff --git a/payload/src/backup.c b/payload/src/backup.c index 60641fcb2..51c8b70d6 100644 --- a/payload/src/backup.c +++ b/payload/src/backup.c @@ -434,12 +434,13 @@ int backup_list(const char *tag_filter, char *buf, size_t cap, return 0; } -static int restore_from_manifest(const char *snap_dir, int *restored) { +/* Every line that is not blank is counted once in `c`: restored, skipped or failed. A restore that + * restored none of them must not read as a success (backup_restore_reply). */ +static int restore_from_manifest(const char *snap_dir, backup_restore_counts_t *c) { char mpath[1024]; snprintf(mpath, sizeof(mpath), "%s/.manifest", snap_dir); FILE *f = fopen(mpath, "r"); if (!f) return -1; - int n = 0; /* A line is a name (up to 511 bytes in older snapshots), a tab and a path (up to 1023): longer * than the 1100 bytes this buffer was. A longer line came back from fgets in two pieces, and * the first piece, name and a path cut short, was restored: the file's bytes written to a path @@ -456,12 +457,17 @@ static int restore_from_manifest(const char *snap_dir, int *restored) { if (L == LINE_CAP - 1 && line[L - 1] != '\n') { int ch; while ((ch = fgetc(f)) != EOF && ch != '\n') {} + c->skipped++; continue; } while (L > 0 && (line[L - 1] == '\n' || line[L - 1] == '\r')) line[--L] = 0; + if (L == 0) continue; char *tab = strchr(line, '\t'); - if (!tab) continue; + if (!tab) { + c->skipped++; + continue; + } *tab = 0; const char *snap_basename = line; const char *original = tab + 1; @@ -471,32 +477,39 @@ static int restore_from_manifest(const char *snap_dir, int *restored) { * ../ components to write outside the intended game-data area. * is_path_allowed checks both the lexical form and the realpath() * resolved form (symlink-escape). */ - if (!is_path_allowed(original)) continue; + if (!is_path_allowed(original)) { + c->skipped++; + continue; + } /* The name is a file inside this snapshot: one path component, never "." or "..", * so a hand-edited manifest cannot make the restore read from outside the snapshot. */ if (!snap_basename[0] || strchr(snap_basename, '/') || strcmp(snap_basename, ".") == 0 || - strcmp(snap_basename, "..") == 0) + strcmp(snap_basename, "..") == 0) { + c->skipped++; continue; + } char src[1024]; snprintf(src, sizeof(src), "%s/%s", snap_dir, snap_basename); - int c = copy_file(src, original); - if (c == 0) { - n++; + int rc = copy_file(src, original); + if (rc == 0) { + c->restored++; mgmt_op_progress(1, 0); - } else if (c == BACKUP_CANCELLED) { + } else if (rc == BACKUP_CANCELLED) { fclose(f); free(line); - if (restored) *restored = n; return BACKUP_CANCELLED; /* the files restored so far stay restored */ + } else { + c->failed++; } } fclose(f); free(line); - if (restored) *restored = n; return 0; } -int backup_restore(const char *tag, int64_t timestamp, int *out_restored) { +int backup_restore_ex(const char *tag, int64_t timestamp, backup_restore_counts_t *out) { + backup_restore_counts_t c = { 0, 0, 0 }; + if (out) *out = c; if (backup_validate_tag(tag) != 0) return -1; pthread_mutex_lock(&g_backup_lock); char snapdir[1024]; @@ -507,13 +520,42 @@ int backup_restore(const char *tag, int64_t timestamp, int *out_restored) { pthread_mutex_unlock(&g_backup_lock); return -1; } - int restored = 0; - int rc = restore_from_manifest(snapdir, &restored); - if (out_restored) *out_restored = restored; + int rc = restore_from_manifest(snapdir, &c); + if (out) *out = c; pthread_mutex_unlock(&g_backup_lock); return rc; } +int backup_restore(const char *tag, int64_t timestamp, int *out_restored) { + backup_restore_counts_t c; + int rc = backup_restore_ex(tag, timestamp, &c); + if (out_restored) *out_restored = c.restored; + return rc; +} + +int backup_restore_reply(char *out, size_t cap, const char *tag_json, int rc, + const backup_restore_counts_t *c) { + static const backup_restore_counts_t none = { 0, 0, 0 }; + char err[192] = ""; + if (!c) c = &none; + int missed = c->skipped + c->failed; + int ok = rc == 0 && c->restored > 0; + if (rc != 0) + snprintf(err, sizeof err, "snapshot not found or restore failed"); + else if (c->restored == 0 && missed == 0) + snprintf(err, sizeof err, "nothing was restored: the snapshot lists no files"); + else if (c->restored == 0) + snprintf(err, sizeof err, + "nothing was restored: %d file(s) could not be written back, %d entr%s skipped " + "(outside the allowed folders or damaged)", + c->failed, c->skipped, c->skipped == 1 ? "y was" : "ies were"); + return snprintf(out, cap, + "{\"ok\":%s,\"tag\":\"%s\",\"restored\":%d,\"skipped\":%d,\"failed\":%d," + "\"partial\":%s,\"err\":\"%s\"}", + ok ? "true" : "false", tag_json ? tag_json : "", c->restored, c->skipped, + c->failed, ok && missed > 0 ? "true" : "false", err); +} + static int rm_rf(const char *path) { struct stat st; if (lstat(path, &st) != 0) return -1; diff --git a/payload/src/runtime.c b/payload/src/runtime.c index f105c0118..ad96885ec 100644 --- a/payload/src/runtime.c +++ b/payload/src/runtime.c @@ -5499,23 +5499,26 @@ static int handle_backup_restore(runtime_state_t *state, const char *body) { char tag[64] = {0}; extract_json_string_field(body, "tag", tag, sizeof(tag)); int64_t ts = (int64_t)extract_json_uint64_field(body, "timestamp"); - int restored = 0; - const char *err = ""; - int rc = -1; + backup_restore_counts_t counts = { 0, 0, 0 }; + char tesc[160]; + json_escape_into(tag, tesc, sizeof(tesc)); + char resp[512]; + int len; if (tag[0] && ts > 0) { - rc = backup_restore(tag, ts, &restored); + int rc = backup_restore_ex(tag, ts, &counts); if (rc == BACKUP_CANCELLED) return mgmt_reply(MGMT_FRAME_ERROR, "backup_cancelled", 16); - if (rc != 0) err = "snapshot not found or restore failed"; + /* ok only when something was restored: a restore that wrote nothing back (every entry + * skipped or failed, or none listed) used to say ok:true with restored:0. */ + len = backup_restore_reply(resp, sizeof(resp), tesc, rc, &counts); } else { - err = "missing tag or timestamp"; + len = snprintf(resp, sizeof(resp), + "{\"ok\":false,\"tag\":\"%s\",\"restored\":0,\"err\":\"missing tag or timestamp\"}", tesc); + } + if (len < 0 || (size_t)len >= sizeof(resp)) { + len = snprintf(resp, sizeof(resp), "{\"ok\":false,\"restored\":%d,\"err\":\"reply too long\"}", + counts.restored); } - char tesc[160]; - json_escape_into(tag, tesc, sizeof(tesc)); - char resp[512]; - int len = snprintf(resp, sizeof(resp), - "{\"ok\":%s,\"tag\":\"%s\",\"restored\":%d,\"err\":\"%s\"}", - rc == 0 ? "true" : "false", tesc, restored, err); pthread_mutex_lock(&state->state_mtx); state->command_count += 1; pthread_mutex_unlock(&state->state_mtx); diff --git a/payload/tests/backup_selftest.c b/payload/tests/backup_selftest.c index 9fb8ddc7c..94229bf3a 100644 --- a/payload/tests/backup_selftest.c +++ b/payload/tests/backup_selftest.c @@ -402,6 +402,23 @@ static void damaged_manifest(void) { CHECK(same_text(ok_dst, "good bytes")); CHECK(access(denied_dst, F_OK) != 0); + /* Every line is counted once, and the reply says what did not come back. */ + { + backup_restore_counts_t c = { -1, -1, -1 }; + char reply[512]; + g_denied = 1; + int rc = backup_restore_ex("t5", 2000, &c); + g_denied = 0; + CHECK(rc == 0); + CHECK(c.restored == 1); + CHECK(c.skipped == 4); /* no tab (twice), a denied path, a path outside the roots */ + CHECK(c.failed == 1); /* missing-file: not in the snapshot */ + CHECK(backup_restore_reply(reply, sizeof reply, "t5", rc, &c) > 0); + CHECK(strstr(reply, "\"ok\":true") != NULL); + CHECK(strstr(reply, "\"restored\":1,\"skipped\":4,\"failed\":1,\"partial\":true") != NULL); + CHECK(strstr(reply, "\"err\":\"\"") != NULL); + } + /* No snapshot, or a bad tag: a refusal, nothing restored. */ CHECK(backup_restore("t5", 9999, &restored) == -1); CHECK(backup_restore("../t5", 2000, &restored) == -1); @@ -416,6 +433,64 @@ static void damaged_manifest(void) { CHECK(backup_restore("t5", 2000, &restored) == -1); } +/* A restore that put nothing back is not a success: it used to reply ok:true with restored:0, and + * the app said "Restored 0 files" as if it had worked. */ +static void restore_of_nothing_is_not_ok(void) { + char snap[1024], p[1200], text[2048], reply[512]; + backup_restore_counts_t c; + int rc; + + snprintf(snap, sizeof snap, "%s/t8/4000", BACKUPS_ROOT); + snprintf(p, sizeof p, "%s/t8", BACKUPS_ROOT); + mkdir(p, 0777); + mkdir(snap, 0777); + snprintf(p, sizeof p, "%s/evil", snap); + put(p, "evil bytes"); + + /* Every entry skipped or failed. */ + snprintf(text, sizeof text, + "evil\t/outside/the/roots\n" + "missing\t%s/restored-nothing\n", + g_root); + snprintf(p, sizeof p, "%s/.manifest", snap); + put(p, text); + rc = backup_restore_ex("t8", 4000, &c); + CHECK(rc == 0); + CHECK(c.restored == 0 && c.skipped == 1 && c.failed == 1); + CHECK(backup_restore_reply(reply, sizeof reply, "t8", rc, &c) > 0); + CHECK(strstr(reply, "\"ok\":false") != NULL); + CHECK(strstr(reply, "\"restored\":0") != NULL); + CHECK(strstr(reply, "\"partial\":false") != NULL); + CHECK(strstr(reply, "nothing was restored: 1 file(s) could not be written back, 1 entry was skipped") != NULL); + + /* Nothing listed at all (blank lines only). */ + put(p, "\n\n"); + rc = backup_restore_ex("t8", 4000, &c); + CHECK(rc == 0); + CHECK(c.restored == 0 && c.skipped == 0 && c.failed == 0); + CHECK(backup_restore_reply(reply, sizeof reply, "t8", rc, &c) > 0); + CHECK(strstr(reply, "\"ok\":false") != NULL); + CHECK(strstr(reply, "the snapshot lists no files") != NULL); + + /* No snapshot: ok:false, the old reason. */ + rc = backup_restore_ex("t8", 4001, &c); + CHECK(rc == -1); + CHECK(c.restored == 0); + CHECK(backup_restore_reply(reply, sizeof reply, "t8", rc, &c) > 0); + CHECK(strstr(reply, "\"ok\":false") != NULL); + CHECK(strstr(reply, "snapshot not found or restore failed") != NULL); + + /* Everything restored: ok, not partial. */ + snprintf(text, sizeof text, "evil\t%s/restored-all\n", g_root); + put(p, text); + rc = backup_restore_ex("t8", 4000, &c); + CHECK(rc == 0 && c.restored == 1 && c.skipped == 0 && c.failed == 0); + CHECK(backup_restore_reply(reply, sizeof reply, "t8", rc, &c) > 0); + CHECK(strcmp(reply, "{\"ok\":true,\"tag\":\"t8\",\"restored\":1,\"skipped\":0,\"failed\":0," + "\"partial\":false,\"err\":\"\"}") == 0); + CHECK(backup_delete("t8", 4000) == 0); +} + /* Two paths that flatten to one name ("a/b_c" and "a_b/c"), and two long paths whose names are cut * to one tail: each keeps its own bytes. The second used to be copied over the first, and a restore * wrote the second file's bytes to both paths. */ @@ -536,6 +611,7 @@ int main(void) { list_survives_strange_folders(); list_stays_inside_its_buffer(); damaged_manifest(); + restore_of_nothing_is_not_ok(); same_flat_name_keeps_both(); long_manifest_lines(); (void)rm_rf(tmpl); diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index 6cee6130b..820312b86 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -447,6 +447,7 @@ "backup_restore_confirm_msg": "21640d22 MAbAmgL666iGQrsHLvlC9MH2YrDKS--yQ1vzxkP-AoDIRk1i77uvxn9unYMM", "backup_restore_confirm_title": "d92e5f51 kAcKgUJkJ6rQGVJBO1HYIjykEqcOYT5RIT_Y8KHdzgvGzxxGcjF3PQr0xqoR", "backup_restore_ok": "fff7bb67 V6oiaBjUGRCYqhZseY6vpa5vQ0Bbp6HgFy6LnELjNKCv56JHfmPxCKEeCK7G", + "backup_restore_partial": "ac419116 g_t8B0z4a7jepvOCxmYrlEUNOLpj247Pui62Ejyuo8oi3wY-HfYEoOQxSaHY", "backup_restore_title": "f2cf72b4 4Z4Hh7rN5qBu3-AwoiB2RCydlasYsuu8uepzFKK2bg_3zzsUdJVz31UctMxA", "backup_saved": "abfdc686 Jrnveqi69tEK2MqPJFy0-9BuyllXJxPDT0oHs9WfD-ur2Ija6-Kfck-jTfAV", "backup_show_all": "7bcbe547 TR6vz6hxs72dWBRaiZ_hfflwNZbJ_zEbr-SZxSfIr2Q8kh6e9OnUMZyHEMiP", From b2b295332c106956ea95a69241a560654545e2c7 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:56:00 -0800 Subject: [PATCH 05/27] Cheats: XML game patches check the game's module too The audit fix made physical cheat writes trust dynlib handle 0 only when it is the game's eboot.bin (#920: in a PS4 game's process handle 0 is another module), but an XML game patch still took handle 0 by number as its base: its lines were placed in that module, bounded by its size and pattern-scanned there. With the debugger write path (FW 8.20 and below) nothing else stopped it, and the AppElf check then said "the game runs ". xml_apply_on now applies the same rule (cheat_patch_base_ok, built on cheat_module_is_game: /app0 modules, handle 0 only when it is eboot.bin or its path cannot be read) to the module it uses, before the AppElf check and again on the module it resolved, for handle 0 and for a .prx AppElf alike. A refused patch writes nothing and says which module it found. Test: cheats_plan_selftest checks the rule and the message, including the #920 case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/include/cheats_plan.h | 6 ++++++ payload/src/cheats.c | 17 +++++++++++++++-- payload/src/cheats_plan.c | 15 +++++++++++++++ payload/tests/cheats_plan_selftest.c | 24 ++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 2 deletions(-) diff --git a/payload/include/cheats_plan.h b/payload/include/cheats_plan.h index fbb45e3d3..993ab4c78 100644 --- a/payload/include/cheats_plan.h +++ b/payload/include/cheats_plan.h @@ -96,4 +96,10 @@ int cheat_addr_ok(intptr_t addr, int len); * physical write there lands in every process that maps the page. */ int cheat_module_is_game(uint64_t handle, const char *path); +/* Whether an XML game patch may take the module with dynlib `handle`, loaded from `path`, as the + * base its lines are placed in and bounded by: cheat_module_is_game's rule, so a PS4 game's handle + * 0 that is not its eboot.bin is refused whatever way the write would go (physical or debugger). + * 1, or 0 with `why` (may be NULL) saying so. */ +int cheat_patch_base_ok(uint64_t handle, const char *path, char *why, size_t why_cap); + #endif /* PS5UPLOAD_CHEATS_PLAN_H */ diff --git a/payload/src/cheats.c b/payload/src/cheats.c index f622a2129..977fe4f65 100644 --- a/payload/src/cheats.c +++ b/payload/src/cheats.c @@ -1868,9 +1868,17 @@ static int xml_apply_on(pid_t pid, const char *title, cheat_mod_t *mod, const xm } return -1; } - char exe[256] = ""; + char exe[256] = "", base_path[256] = "", why[320] = ""; uint64_t mbase = 0, msize = 0; (void)module_info(pid, 0, &mbase, &msize, exe, sizeof exe); + /* The patch's base must be one of the game's own modules, as for every other cheat write + * (phys_write_allowed). In a PS4 game's process handle 0 is another module (#920): a patch + * with no AppElf took it as the game's code and, with no original bytes to compare, wrote into + * it. Said before the AppElf check, whose "the game runs " would mislead. */ + if (!gp_elf_is_module(m.app_elf) && !cheat_patch_base_ok(0, exe, why, sizeof why)) { + if (err) snprintf(err, err_cap, "%s", why); + return -1; + } if (!gp_elf_is_module(m.app_elf) && !gp_elf_ok(m.app_elf, exe)) { const char *b = strrchr(exe, '/'); if (err) snprintf(err, err_cap, "this patch is for %s; the game runs %s", m.app_elf, b ? b + 1 : exe); @@ -1882,11 +1890,16 @@ static int xml_apply_on(pid_t pid, const char *title, cheat_mod_t *mod, const xm hook_wait(hk); return -1; } - if (module_info(pid, handle, &mbase, &msize, NULL, 0) != 0 || !mbase || !msize) { + if (module_info(pid, handle, &mbase, &msize, base_path, sizeof base_path) != 0 || !mbase || !msize) { if (err) snprintf(err, err_cap, "the game's code is not loaded yet; try again"); hook_wait(hk); return -1; } + /* Again on the module the lines are placed in (a .prx AppElf, or handle 0 read just now). */ + if (!cheat_patch_base_ok(handle, base_path, why, sizeof why)) { + if (err) snprintf(err, err_cap, "%s", why); + return -1; + } const gp_line_t *lines = p->lines; int nl = p->nl; diff --git a/payload/src/cheats_plan.c b/payload/src/cheats_plan.c index 49d3acd78..86b538c72 100644 --- a/payload/src/cheats_plan.c +++ b/payload/src/cheats_plan.c @@ -106,6 +106,21 @@ int cheat_module_is_game(uint64_t handle, const char *path) { return strcasecmp(leaf, "eboot.bin") == 0; } +int cheat_patch_base_ok(uint64_t handle, const char *path, char *why, size_t why_cap) { + if (why && why_cap) why[0] = '\0'; + if (cheat_module_is_game(handle, path)) return 1; + if (why && why_cap) { + if (handle == 0) + snprintf(why, why_cap, + "the game's executable is not where this patch looks for it (that module is %s); " + "nothing was written", + path); + else + snprintf(why, why_cap, "%s is not one of the game's own modules; nothing was written", path); + } + return 0; +} + static int overlaps(intptr_t a, int alen, intptr_t b, int blen) { return a < b + (intptr_t)blen && b < a + (intptr_t)alen; } diff --git a/payload/tests/cheats_plan_selftest.c b/payload/tests/cheats_plan_selftest.c index 1639a0385..5c1407dac 100644 --- a/payload/tests/cheats_plan_selftest.c +++ b/payload/tests/cheats_plan_selftest.c @@ -167,6 +167,29 @@ static void test_module_is_game(void) { CHECK(!cheat_module_is_game(3, "")); } +/* An XML game patch's base module goes by the same rule (it used to take handle 0 by number). */ +static void test_patch_base_ok(void) { + char why[320]; + CHECK(cheat_patch_base_ok(0, "/app0/eboot.bin", why, sizeof why) && why[0] == '\0'); + CHECK(cheat_patch_base_ok(0, "/mnt/sandbox/pfsmnt/CUSA00284-app0/eboot.bin", why, sizeof why)); + CHECK(cheat_patch_base_ok(0, "", why, sizeof why)); /* unreadable path: as handle 0 always was */ + CHECK(cheat_patch_base_ok(5, "/app0/sce_module/libgame.prx", NULL, 0)); + /* #920: a PS4 game's handle 0 is another module (Rayman Legends, CUSA00284 on 11.60). */ + CHECK(!cheat_patch_base_ok(0, "/system/common/lib/libScePlayGo.sprx", why, sizeof why)); + CHECK(strstr(why, "libScePlayGo.sprx") != NULL && strstr(why, "nothing was written") != NULL); + /* A .prx AppElf that resolves to a system library. */ + CHECK(!cheat_patch_base_ok(9, "/system/common/lib/libSceGnmDriver.sprx", why, sizeof why)); + CHECK(strstr(why, "is not one of the game's own modules") != NULL); + CHECK(!cheat_patch_base_ok(9, "/system/common/lib/libSceGnmDriver.sprx", NULL, 0)); + /* A small buffer is cut, never overrun. */ + { + char tiny[8]; + memset(tiny, 'x', sizeof tiny); + CHECK(!cheat_patch_base_ok(0, "/system/common/lib/libc.sprx", tiny, sizeof tiny)); + CHECK(tiny[sizeof tiny - 1] == '\0'); + } +} + static void test_addr_ok(void) { CHECK(cheat_addr_ok(0x1FAD908, 9)); CHECK(!cheat_addr_ok(0, 4)); @@ -384,6 +407,7 @@ int main(void) { test_order_mc4_zero_cave(); test_addr_ok(); test_module_is_game(); + test_patch_base_ok(); test_apply_mock(); if (failures) { fprintf(stderr, "cheats_plan_selftest: %d failure(s)\n", failures); From 4450c590037c7624f1db04bf4917617d84bef9b4 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:03:22 -0800 Subject: [PATCH 06/27] Console page: transfers leave a worker free for the page The helper's web server has four workers. Reads before a route were already bounded (idle connections wait on the accept thread, a request has 5 s to arrive, a full queue closes new connections, queued ones expire), but an upload or a download holds its worker for as long as it moves bytes: minutes for a big file, or as long as a slow client keeps trickling above the 1 KiB/s floor. Four of them (a few downloads from a phone, or a client doing it on purpose) took every worker, and the page's own requests waited in the queue until they expired, so the page stopped answering. At most three transfers (streamed uploads and saves, and the downloads named by the new webui_cfg_t.long_for) now run at once. One more is answered 503 {"error":"busy"} with Retry-After: 2 straight after the Host/Origin/token checks (the page already shows "The console is busy. Try again in a moment." for that code), so the last worker is always there for the page. Turned-away transfers are counted in the existing drops log line. Test: webui_server_selftest holds three transfers (an upload and two downloads), checks a fourth of each kind gets 503 at once, a normal request is answered at once, and a transfer runs again once they end. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- Makefile | 2 +- payload/include/webui_server.h | 8 ++- payload/src/webui_api.c | 7 +++ payload/src/webui_server.c | 39 +++++++++++-- payload/tests/webui_server_selftest.c | 83 ++++++++++++++++++++++++++- 5 files changed, 132 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index 59e76dcd2..7f46bdacd 100644 --- a/Makefile +++ b/Makefile @@ -1100,7 +1100,7 @@ test-payload: payload $(PAYLOAD_DIR)/tests/webui_server_selftest.c $(PAYLOAD_DIR)/src/webui_server.c \ $(PAYLOAD_DIR)/src/webui_http.c $(PAYLOAD_DIR)/src/webui_auth.c @$(RUN_LIMITED) $(SELFTEST_DIR)/ps5upload-webui-server-selftest - @echo "✓ silent, half-sent and flooding web clients never stall the helper; an idle connection holds no worker" + @echo "✓ silent, half-sent and flooding web clients never stall the helper; an idle connection holds no worker; transfers leave one worker for the page" @echo "Running webui codec self-test (host build)..." @cc -O2 -Wall -Wextra -Werror -I$(PAYLOAD_DIR)/include -I$(AVA1_C) -I$(AVA1_C)/gen -I$(PAYLOAD_DIR)/gen \ -o $(SELFTEST_DIR)/ps5upload-webui-codec-selftest \ diff --git a/payload/include/webui_server.h b/payload/include/webui_server.h index a0707c1d8..96f57a861 100644 --- a/payload/include/webui_server.h +++ b/payload/include/webui_server.h @@ -7,7 +7,8 @@ * it without reading. A connection that has sent nothing waits on the accept * thread and holds no worker; a slow or hostile client that has holds one for at * most 5 s and can never stall the accept thread. One address gets 16 connections - * at most. */ + * at most. Transfers (uploads, downloads) take at most WEBUI_WORKERS - 1 workers, + * so the page's own requests are answered while they run. */ #ifndef PS5UPLOAD_WEBUI_SERVER_H #define PS5UPLOAD_WEBUI_SERVER_H @@ -37,6 +38,11 @@ typedef struct { /* Optional (NULL: nothing is streamed). 1 = this request (by method + path) is a streamed one. */ int (*stream_for)(const webui_req_t *r); webui_stream_fn stream; + /* Optional (NULL: none). 1 = this request (by method + path) may hold its worker for long, as a + * download to a slow reader does. With the streamed requests these are the transfers: at most + * WEBUI_WORKERS - 1 run at once, and one more is answered 503 {"error":"busy"} (Retry-After: 2) + * right after the Host/Origin/token checks, so a short request always finds a worker. */ + int (*long_for)(const webui_req_t *r); } webui_cfg_t; /* New token, bind, start the threads. Returns 0, or -1 when already running or diff --git a/payload/src/webui_api.c b/payload/src/webui_api.c index 50781e3cb..f8c333433 100644 --- a/payload/src/webui_api.c +++ b/payload/src/webui_api.c @@ -1930,6 +1930,12 @@ static void spawn_lan_apply(void) { if (rc != 0) fprintf(stderr, "webui: cannot start the rebind thread (%d); LAN applies at the next start\n", rc); } +/* The downloads (GET /dl//, serve_download): with the streamed uploads these are the + * transfers the server runs on at most all but one worker (webui_cfg_t.long_for). */ +static int api_long_for(const webui_req_t *r) { + return strcmp(r->method, "GET") == 0 && strncmp(r->path, "/dl/", 4) == 0; +} + /* Starts the :9180 server with the saved LAN setting (main.c at helper start, and turning Minion * back on). 0 when it runs (or already ran), -1 when it could not start (logged). */ int webui_api_server_start(void) { @@ -1945,6 +1951,7 @@ int webui_api_server_start(void) { wc.route = webui_api_route; wc.stream_for = webui_api_stream_for; wc.stream = webui_api_stream; + wc.long_for = api_long_for; if (webui_start(&wc) != 0) { if (webui_running()) return 0; /* another start won the race */ fprintf(stderr, "webui: server did not start\n"); diff --git a/payload/src/webui_server.c b/payload/src/webui_server.c index c9b48ba60..e13c26e20 100644 --- a/payload/src/webui_server.c +++ b/payload/src/webui_server.c @@ -11,6 +11,10 @@ * - a full queue closes the new connection instead of waiting; * - every connection has a deadline of accept time + 5 s; a worker reads in * poll slices up to that deadline and drops an expired connection unread; + * - a transfer (a streamed body, or a request the cfg's long_for names: the + * downloads) holds its worker for as long as it moves bytes, so at most + * WEBUI_LONG_MAX run at once; one more is answered 503 at once and the last + * worker stays free for the page's short requests; * - what was turned away is counted and logged every few seconds; * - writes carry SO_SNDTIMEO and a total budget, so a client that stops * reading frees the worker. @@ -44,6 +48,9 @@ #include "webui_auth.h" #define WEBUI_WORKERS 4 +/* Transfers (streamed bodies, the cfg's long_for requests) running at once: one worker is always + * left for the page's short requests. */ +#define WEBUI_LONG_MAX (WEBUI_WORKERS - 1) #define WEBUI_QUEUE_DEPTH 32 #define WEBUI_WAITING_MAX 32 /* connections waiting for their first bytes */ #define WEBUI_PER_SOURCE_MAX 16 /* one address's connections anywhere in the server: a browser opens 6 */ @@ -93,6 +100,7 @@ typedef struct srv { webui_route_fn route; int (*stream_for)(const webui_req_t *r); webui_stream_fn stream; + int (*long_for)(const webui_req_t *r); int lan; int rebind_req; /* accept thread: close and rebind with ->lan */ int bound; @@ -109,7 +117,9 @@ typedef struct srv { int w_done[WEBUI_WORKERS]; int w_fd[WEBUI_WORKERS]; /* connection being served, -1 if none */ uint32_t w_src[WEBUI_WORKERS]; /* its address */ + int w_long[WEBUI_WORKERS]; /* 1 while the worker is inside a transfer (WEBUI_LONG_MAX) */ unsigned expired; /* queued connections past their deadline before a worker got to them */ + unsigned busy; /* transfers answered 503: WEBUI_LONG_MAX were running */ worker_arg_t wargs[WEBUI_WORKERS]; char *wbuf[WEBUI_WORKERS]; } srv_t; @@ -451,6 +461,22 @@ static void serve(srv_t *s, int idx, conn_t c) { webui_send_json(c.fd, 403, "{\"error\":\"forbidden\"}"); return; } + if (rd == RD_STREAM || (s->long_for && s->long_for(&req))) { + /* A transfer holds its worker for as long as it moves bytes (minutes for a big upload or + * download, or a slow client's trickle). Past WEBUI_LONG_MAX of them every worker could be + * inside one and the page stopped answering: one more is told to come back instead. */ + int busy = 0; + pthread_mutex_lock(&s->mu); + for (i = 0; i < WEBUI_WORKERS; i++) busy += s->w_long[i]; + if (busy >= WEBUI_LONG_MAX) s->busy++; + else s->w_long[idx] = 1; + pthread_mutex_unlock(&s->mu); + if (busy >= WEBUI_LONG_MAX) { + static const char body[] = "{\"error\":\"busy\"}"; + webui_send_ex(c.fd, 503, "application/json", body, sizeof body - 1, "Retry-After: 2\r\n"); + return; + } + } if (rd == RD_STREAM) { /* The bytes past the headers that came in the same reads (never more than the body). */ size_t pre = got > req.header_len ? got - req.header_len : 0; @@ -498,6 +524,7 @@ static void *worker_main(void *arg) { } pthread_mutex_lock(&s->mu); s->w_fd[idx] = -1; + s->w_long[idx] = 0; pthread_mutex_unlock(&s->mu); close(c.fd); } @@ -556,16 +583,19 @@ typedef struct { /* One line every WEBUI_WATCH_MS at most, only when something was turned away: a console page that * stops answering must leave a trace of why. */ static void report_drops(srv_t *s, drops_t *d) { - unsigned expired; + unsigned expired, busy; pthread_mutex_lock(&s->mu); expired = s->expired; s->expired = 0; + busy = s->busy; + s->busy = 0; pthread_mutex_unlock(&s->mu); - if (d->queue_full || d->per_source || d->idle_evicted || expired) + if (d->queue_full || d->per_source || d->idle_evicted || expired || busy) fprintf(stderr, "webui: connections turned away: %u queue full, %u over %d from one address, " - "%u idle evicted, %u expired in the queue\n", - d->queue_full, d->per_source, WEBUI_PER_SOURCE_MAX, d->idle_evicted, expired); + "%u idle evicted, %u expired in the queue, %u transfers over %d at once\n", + d->queue_full, d->per_source, WEBUI_PER_SOURCE_MAX, d->idle_evicted, expired, busy, + WEBUI_LONG_MAX); memset(d, 0, sizeof *d); } @@ -848,6 +878,7 @@ int webui_start(const webui_cfg_t *cfg) { s->route = cfg->route; s->stream_for = cfg->stream_for; s->stream = cfg->stream; + s->long_for = cfg->long_for; s->lan = cfg->lan ? 1 : 0; webui_token_new(s->token); if (s->lan) { diff --git a/payload/tests/webui_server_selftest.c b/payload/tests/webui_server_selftest.c index 37f43a863..1a9afe152 100644 --- a/payload/tests/webui_server_selftest.c +++ b/payload/tests/webui_server_selftest.c @@ -41,11 +41,20 @@ static int failures = 0; static uint16_t g_port; static int stub_route(const webui_req_t *r, const uint8_t *body, size_t body_len, int fd) { - (void)r; (void)body; (void)body_len; + (void)body; (void)body_len; + if (strcmp(r->path, "/api/slow") == 0) { + /* A long download to a slow reader: holds its worker until the client goes (10 s at most). */ + char b[256]; + struct pollfd p = { fd, POLLIN, 0 }; + while (poll(&p, 1, 10000) > 0 && recv(fd, b, sizeof b, 0) > 0) {} + } webui_send_json(fd, 200, "{\"ok\":true}"); return 0; } +/* Requests that may hold a worker for long besides the streamed ones (the helper's downloads). */ +static int long_for(const webui_req_t *r) { return strcmp(r->path, "/api/slow") == 0; } + /* Streamed route: reads the rest of the body itself (with its own timeout), answers {"n":}. */ static int stream_for(const webui_req_t *r) { return strcmp(r->path, "/api/stream") == 0; } @@ -152,6 +161,7 @@ static int start_server(void) { c.route = stub_route; c.stream_for = stream_for; c.stream = stream_route; + c.long_for = long_for; return webui_start(&c); } @@ -257,6 +267,76 @@ static void streamed_body(void) { CHECK(status == 401); } +/* Open a request that then holds its worker: a download to a reader that never reads (GET + * /api/slow) or an upload that never sends its body (POST /api/stream). The socket, or -1. */ +static int hold(int upload) { + char req[512]; + int s = dial(), n; + if (s < 0) return -1; + if (upload) + n = snprintf(req, sizeof req, + "POST /api/stream HTTP/1.1\r\nHost: 127.0.0.1:%u\r\nX-PS5U-Token: %s\r\n" + "Content-Length: 1000000\r\n\r\n", + (unsigned)g_port, webui_token()); + else + n = snprintf(req, sizeof req, "GET /api/slow HTTP/1.1\r\nHost: 127.0.0.1:%u\r\nX-PS5U-Token: %s\r\n\r\n", + (unsigned)g_port, webui_token()); + if (send(s, req, (size_t)n, 0) != n) { + close(s); + return -1; + } + return s; +} + +/* Transfers never take every worker: with three running (uploads and downloads alike, each holding + * its worker for as long as its client keeps it open), a fourth is told 503 busy at once, and the + * page's own requests are still answered at once. Before, four slow transfers held all four workers + * and every other request waited in the queue until it expired. */ +static void transfers_leave_a_worker(void) { + int held[3], i, s, n, status; + char req[512], resp[2048]; + double t0; + held[0] = hold(1); + held[1] = hold(0); + held[2] = hold(0); + for (i = 0; i < 3; i++) CHECK(held[i] >= 0); + sleep_ms(500); /* the workers have them */ + + for (i = 0; i < 2; i++) { + t0 = now_s(); + s = hold(i == 0); + CHECK(s >= 0); + if (s < 0) continue; + status = -1; + if (read_all(s, resp, sizeof resp, 3000) > 0) (void)sscanf(resp, "HTTP/1.1 %d", &status); + close(s); + CHECK(status == 503); + CHECK(strstr(resp, "{\"error\":\"busy\"}") != NULL); + CHECK(strstr(resp, "Retry-After: 2\r\n") != NULL); + CHECK(now_s() - t0 < 1.0); + } + t0 = now_s(); + CHECK(request("/api/x", webui_token(), resp, sizeof resp) == 200); + CHECK(now_s() - t0 < 1.0); + + /* Once they end, a transfer runs again. */ + for (i = 0; i < 3; i++) + if (held[i] >= 0) close(held[i]); + sleep_ms(500); + s = dial(); + CHECK(s >= 0); + if (s < 0) return; + n = snprintf(req, sizeof req, + "POST /api/stream HTTP/1.1\r\nHost: 127.0.0.1:%u\r\nX-PS5U-Token: %s\r\nContent-Length: 3\r\n\r\nabc", + (unsigned)g_port, webui_token()); + CHECK(send(s, req, (size_t)n, 0) == n); + status = -1; + if (read_all(s, resp, sizeof resp, 3000) > 0) (void)sscanf(resp, "HTTP/1.1 %d", &status); + close(s); + CHECK(status == 200); + CHECK(strstr(resp, "{\"n\":3}") != NULL); +} + /* Idle connections hold no worker: four from anyone on the LAN (or a browser's speculative connects) * used to keep the page from answering for as long as they kept coming. A request behind them is * answered at once. */ @@ -516,6 +596,7 @@ int main(void) { garbage_400(); too_big_413(); streamed_body(); + transfers_leave_a_worker(); idle_connections_take_no_worker(); idle_connection_closed_at_deadline(); silent_client_dropped_and_next_served(); From ffacda91355cbf4340483fa56df64b196a80bde3 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:39:22 -0800 Subject: [PATCH 07/27] Docker: pin every base image to its digest The engine, web UI and hub images built FROM a tag only, so a tag moved upstream changed what we ship without any change here. Each FROM now names the same tag plus the digest it points at today (rust 1.99.1-alpine3.24, node 26.13.1-alpine, distroless static-debian12 nonroot); versions are unchanged. FROM scratch has no digest. The convert toolchain image was pinned already. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- engine/Dockerfile | 2 +- engine/Dockerfile.webui | 4 ++-- engine/crates/ps5upload-hub/Dockerfile | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/engine/Dockerfile b/engine/Dockerfile index 89844abc7..a69ae02e7 100644 --- a/engine/Dockerfile +++ b/engine/Dockerfile @@ -47,7 +47,7 @@ # to the LAN interface (e.g. `-p 192.168.1.10:19113:19113`), not 0.0.0.0 on a # public host. -FROM rust:1.99.1-alpine3.24 AS builder +FROM rust:1.99.1-alpine3.24@sha256:44819b27be4c97b0e4d7203bd2e02c4820f97700211b6a37fb4c246a2de59383 AS builder # g++ compiles unrar's bundled C++ (for the ps5upload-unrar helper) against # musl; musl target links static. diff --git a/engine/Dockerfile.webui b/engine/Dockerfile.webui index 68236da1e..83407c9b4 100644 --- a/engine/Dockerfile.webui +++ b/engine/Dockerfile.webui @@ -34,7 +34,7 @@ # ── Stage 1: build the React frontend ──────────────────────────────────────── # Pinned to a release with the October 2026 Node security fixes (Brotli, TLS hostname checks). -FROM node:26.13.1-alpine AS frontend +FROM node:26.13.1-alpine@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5 AS frontend # The client at its repo-relative place: the FAQ and Changelog screens bundle # ../FAQ.md and ../CHANGELOG.md from the repo root. @@ -53,7 +53,7 @@ ENV VITE_BASE_URL=$PS5UPLOAD_BASE_URL RUN npm run build:vite # ── Stage 2: build the Rust engine with embedded web UI ────────────────────── -FROM rust:1.99.1-alpine3.24 AS builder +FROM rust:1.99.1-alpine3.24@sha256:44819b27be4c97b0e4d7203bd2e02c4820f97700211b6a37fb4c246a2de59383 AS builder # g++ compiles unrar's bundled C++ (for the ps5upload-unrar helper) against # musl; musl target links static. diff --git a/engine/crates/ps5upload-hub/Dockerfile b/engine/crates/ps5upload-hub/Dockerfile index c2d83c56a..6684e749c 100644 --- a/engine/crates/ps5upload-hub/Dockerfile +++ b/engine/crates/ps5upload-hub/Dockerfile @@ -5,7 +5,7 @@ # # docker build --platform linux/amd64 -t ps5upload-hub . -FROM rust:1.99.1-alpine3.24 AS build +FROM rust:1.99.1-alpine3.24@sha256:44819b27be4c97b0e4d7203bd2e02c4820f97700211b6a37fb4c246a2de59383 AS build RUN apk add --no-cache musl-dev WORKDIR /src COPY deploy/workspace.toml Cargo.toml @@ -17,7 +17,7 @@ RUN cargo build --release --locked -p ps5upload-hub \ && cp target/release/ps5upload-hub /ps5upload-hub # No shell, no package manager, runs as an unprivileged user. -FROM gcr.io/distroless/static-debian12:nonroot +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /ps5upload-hub /usr/local/bin/ps5upload-hub USER nonroot ENV HUB_HTTP_LISTEN=0.0.0.0:8080 From bb05f8829b5a1dcc4d639cf6ab6165a95504a639 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:44:31 -0800 Subject: [PATCH 08/27] CI: checkouts keep no git token unless the job pushes actions/checkout leaves the job's GITHUB_TOKEN in .git/config by default, where every later step (build scripts, npm and cargo installs, third-party actions) can read it. Every checkout now sets persist-credentials: false, except release-tag.yml, which commits the bump and pushes the tag with it. No other job uses git with credentials: the one later git fetch (engine-ci's merge-queue change list) reads this public repository, and gh, the Pages deploy and the Docker pushes use their own tokens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .github/workflows/ava1-soak.yml | 1 + .github/workflows/ci-runner-retry.yml | 1 + .github/workflows/codeql.yml | 2 ++ .github/workflows/docker-engine.yml | 5 +++++ .github/workflows/engine-ci.yml | 21 +++++++++++++++++++++ .github/workflows/flake-hunter.yml | 1 + .github/workflows/ios.yml | 2 ++ .github/workflows/pages.yml | 1 + .github/workflows/publish.yml | 6 ++++++ .github/workflows/release-cache.yml | 1 + 10 files changed, 41 insertions(+) diff --git a/.github/workflows/ava1-soak.yml b/.github/workflows/ava1-soak.yml index 084dd46cf..ef012529d 100644 --- a/.github/workflows/ava1-soak.yml +++ b/.github/workflows/ava1-soak.yml @@ -29,6 +29,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable diff --git a/.github/workflows/ci-runner-retry.yml b/.github/workflows/ci-runner-retry.yml index 942e8317d..7148b715f 100644 --- a/.github/workflows/ci-runner-retry.yml +++ b/.github/workflows/ci-runner-retry.yml @@ -40,6 +40,7 @@ jobs: # workflow_run runs on the default branch: this is main's classifier, whatever the run was for. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false sparse-checkout: scripts/release/gate-failures.mjs sparse-checkout-cone-mode: false diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 3ab812a65..9905ba2d5 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -66,6 +66,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 if: github.event_name == 'pull_request' with: + persist-credentials: false fetch-depth: 2 sparse-checkout: .github/codeql - name: Pick the languages @@ -110,6 +111,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4 with: diff --git a/.github/workflows/docker-engine.yml b/.github/workflows/docker-engine.yml index 2ae2b40ec..36c5c9e8c 100644 --- a/.github/workflows/docker-engine.yml +++ b/.github/workflows/docker-engine.yml @@ -103,6 +103,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Stage the committed DPI daemon for the embed @@ -149,6 +150,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Stage the committed DPI daemon for the embed @@ -244,6 +246,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ needs.resolve.outputs.tag }} @@ -341,6 +344,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ needs.resolve.outputs.tag }} @@ -461,6 +465,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ needs.resolve.outputs.tag }} diff --git a/.github/workflows/engine-ci.yml b/.github/workflows/engine-ci.yml index bdd5947d7..4079bd4b5 100644 --- a/.github/workflows/engine-ci.yml +++ b/.github/workflows/engine-ci.yml @@ -81,6 +81,7 @@ jobs: # so HEAD^1..HEAD is exactly what the PR changes there. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false fetch-depth: 2 sparse-checkout: .github/scripts @@ -130,6 +131,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: @@ -154,6 +156,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -286,6 +289,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -433,6 +437,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -492,6 +497,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -574,6 +580,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -644,6 +651,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -681,6 +689,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -791,6 +800,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -877,6 +887,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable @@ -1032,6 +1043,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1093,6 +1105,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1148,6 +1161,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1213,6 +1227,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true # gitleaks reads every commit, not only the tip. fetch-depth: 0 @@ -1257,6 +1272,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: @@ -1305,6 +1321,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1379,6 +1396,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1522,6 +1540,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 @@ -1558,6 +1577,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1780,6 +1800,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false sparse-checkout: .github/scripts - name: Every job this change needed succeeded; the others were skipped on purpose diff --git a/.github/workflows/flake-hunter.yml b/.github/workflows/flake-hunter.yml index 8e6e78a22..b706a402b 100644 --- a/.github/workflows/flake-hunter.yml +++ b/.github/workflows/flake-hunter.yml @@ -41,6 +41,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - name: Install Rust stable diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 324354a04..ae30f4d5c 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -27,6 +27,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: @@ -87,6 +88,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 410db5875..9aa1fac15 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -64,6 +64,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: main - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f25614d09..968275a2a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -72,6 +72,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ github.event.inputs.tag || github.ref_name }} @@ -275,6 +276,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ github.event.inputs.tag || github.ref_name }} @@ -756,6 +758,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ github.event.inputs.tag || github.ref_name }} @@ -924,6 +927,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ github.event.inputs.tag || github.ref_name }} @@ -1032,6 +1036,7 @@ jobs: # Only the LICENSE (create-release ships the repo's copy) and the scan scripts. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false ref: ${{ github.event.inputs.tag || github.ref_name }} sparse-checkout: | /LICENSE @@ -1113,6 +1118,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true ref: ${{ github.event.inputs.tag || github.ref_name }} diff --git a/.github/workflows/release-cache.yml b/.github/workflows/release-cache.yml index 8476caac2..109f8ea56 100644 --- a/.github/workflows/release-cache.yml +++ b/.github/workflows/release-cache.yml @@ -89,6 +89,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + persist-credentials: false submodules: true # publish.yml's Node: the build script reads tauri.conf.json with it on macOS. From 818d883f49402138a31d7a793a00783fe286793c Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:42:24 -0800 Subject: [PATCH 09/27] Linux release: the AppImage tools are pinned and checksummed The Linux build ran linuxdeploy and its helpers straight from the network. A diagnose step downloaded linuxdeploy from the moving "continuous" release and ran it, and Tauri's bundler downloads AppRun, linuxdeploy and the appimage plugin on its own, the plugin also from "continuous", none of them checked. scripts/release/appimage-tools.sh now fetches each from a fixed release (Tauri's apprun-old and linuxdeploy-07333c6, plugin 1-alpha-20250213-1), checks its SHA-256 and only then puts it in Tauri's tools cache, where the bundler finds it and downloads nothing. A file that does not match stops the build. The diagnose step runs that verified linuxdeploy (the one the build uses) instead of a fresh download. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .github/workflows/publish.yml | 23 ++++++++-- scripts/release/appimage-tools.sh | 72 +++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 4 deletions(-) create mode 100755 scripts/release/appimage-tools.sh diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 968275a2a..cb9757747 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -522,6 +522,21 @@ jobs: ./scripts/release/azure-sign.ps1 "engine/target/$env:RUST_TARGET/release/ps5upload-engine.exe" ./scripts/release/azure-sign.ps1 "engine/target/$env:RUST_TARGET/release/ps5upload-unrar.exe" + # Tauri downloads these itself with no checksum (the appimage plugin from a moving + # "continuous" release). Pinned URLs and SHA-256s, put in its cache first, so the build + # runs only these files. + - name: Fetch the AppImage tools (pinned, checksummed; Linux only) + if: matrix.platform == 'linux' + env: + ARCH: ${{ matrix.arch }} + run: | + case "$ARCH" in + x64) tools_arch=x86_64 ;; + arm64) tools_arch=aarch64 ;; + *) echo "::error::no AppImage tools for $ARCH"; exit 1 ;; + esac + ./scripts/release/appimage-tools.sh "$tools_arch" + - name: Diagnose linuxdeploy (Linux only) if: matrix.platform == 'linux' env: @@ -530,12 +545,12 @@ jobs: run: | set +e cd "$RUNNER_TEMP" - url="https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous" case "$ARCH" in - x64) asset=linuxdeploy-x86_64.AppImage ;; - arm64) asset=linuxdeploy-aarch64.AppImage ;; + x64) tools_arch=x86_64 ;; + arm64) tools_arch=aarch64 ;; esac - curl --retry 3 --fail -L -o linuxdeploy "$url/$asset" + # The build's own linuxdeploy, verified by the step above (a copy: the bundler patches its file). + cp "${XDG_CACHE_HOME:-$HOME/.cache}/tauri/linuxdeploy-07333c6-$tools_arch.AppImage" linuxdeploy chmod +x linuxdeploy echo "=== linuxdeploy --version (direct) ===" ./linuxdeploy --version diff --git a/scripts/release/appimage-tools.sh b/scripts/release/appimage-tools.sh new file mode 100755 index 000000000..54ae24e4f --- /dev/null +++ b/scripts/release/appimage-tools.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# +# Put the tools `tauri build` uses for the AppImage into its tools cache, each +# from a pinned URL and checked against its SHA-256 before it is kept. Called by +# the Linux legs of .github/workflows/publish.yml before the Tauri build. +# +# Tauri's bundler (tauri-bundler 2.10.5, in @tauri-apps/cli 2.12.5) downloads +# AppRun, linuxdeploy and linuxdeploy-plugin-appimage on its own, without any +# checksum, and the plugin from the moving "continuous" release; it skips a +# download when the file is already in its cache. Filling the cache first means +# the build runs only these files. The names and the linuxdeploy build (07333c6) +# are the bundler's (src/bundle/linux/appimage/linuxdeploy.rs): when the Tauri +# CLI is updated, check that file and update the table below with it. +# +# Usage: appimage-tools.sh [cache dir] +# cache dir defaults to Tauri's: ${XDG_CACHE_HOME:-$HOME/.cache}/tauri +set -euo pipefail + +arch="${1:-}" +dest="${2:-${XDG_CACHE_HOME:-$HOME/.cache}/tauri}" + +gh_dl="https://github.com" +tauri_bin="$gh_dl/tauri-apps/binary-releases/releases/download" +plugin_rel="$gh_dl/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1" + +# name in the cache | URL | SHA-256 +case "$arch" in +x86_64) + tools=( + "AppRun-x86_64|$tauri_bin/apprun-old/AppRun-x86_64|f30140a43a0a59e46db21bdefdf749b9e9f2c6946e92afabbacf98b8ae73fb4f" + "linuxdeploy-07333c6-x86_64.AppImage|$tauri_bin/linuxdeploy-07333c6/linuxdeploy-x86_64.AppImage|36a2d7e274d12e1050d0e9ecfe11d339ed54720b2bec464c286d53f8b07f5c62" + "linuxdeploy-plugin-appimage.AppImage|$plugin_rel/linuxdeploy-plugin-appimage-x86_64.AppImage|992d502a248e14ab185448ddf6f6e7d25558cb84d4623c354c3af350c25fccb3" + ) + ;; +aarch64) + tools=( + "AppRun-aarch64|$tauri_bin/apprun-old/AppRun-aarch64|072f17c0895a85c490282fe5395c5007e5fc75da727e553b3b8fb680feb11578" + "linuxdeploy-07333c6-aarch64.AppImage|$tauri_bin/linuxdeploy-07333c6/linuxdeploy-aarch64.AppImage|556ab80baa98e600aa80f0dcedfb70bca0e1ce7e9f147fb345be3fcc3e91b2b1" + "linuxdeploy-plugin-appimage.AppImage|$plugin_rel/linuxdeploy-plugin-appimage-aarch64.AppImage|83c292149274965a865dcd44c135cfca8ba28c6b7de3eb628d4b8b5f248af17c" + ) + ;; +*) + echo "usage: $0 [cache dir]" >&2 + exit 2 + ;; +esac + +sha256() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" | cut -d' ' -f1 + else + shasum -a 256 "$1" | cut -d' ' -f1 + fi +} + +mkdir -p "$dest" +for entry in "${tools[@]}"; do + IFS='|' read -r name url want <<<"$entry" + part="$dest/.$name.part" + rm -f "$part" + curl --retry 3 --fail --location --silent --show-error -o "$part" "$url" + got="$(sha256 "$part")" + if [ "$got" != "$want" ]; then + rm -f "$part" + echo "::error::$name: SHA-256 $got does not match the pinned $want ($url); not used" >&2 + exit 1 + fi + chmod +x "$part" + # Always replaced: the bundler patches its cached linuxdeploy in place after a run. + mv -f "$part" "$dest/$name" + echo "$name: verified ($want)" +done From e3367fdfdfe2a12f1b9b52981c6c3ded0cb182ac Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:07:37 -0800 Subject: [PATCH 10/27] Play Together with a TV remote (#926) The join page and the joined game now work with a TV remote or a keyboard alone: - The arrows move between buttons on the join page in any browser, OK presses one, and the first useful button has the focus (Open in the app, Join, Cancel, Ask again). - In the game the focus is the game's: the arrows and Enter play. Back (the app's system Back, the browser's Back, Esc) closes the controller check or the guide first, then brings the buttons with the focus on them, then leaves full screen, then goes back as usual. A press on the controller hands the focus back to the game. - Check your controller is a dialog: the focus starts inside and stays there, and goes back to its button when it closes. - A thick white focus ring on the guest screens, bigger on a TV; none on the game itself. - The app on a TV: no on-screen controller, the game starts in full screen and the arrows stay inside it, and a hint says Back brings the buttons. - The app's first screen on a TV (Consoles, Home) offers Join Play Together, focused; Add a PS5 no longer pops up over it on a TV. Phones and computers are unchanged. - verify-android-apk.py also checks android.software.leanback is declared (optional). Tests: e2e/play-together-tv.spec.ts drives the join page and the app on a TV with the keyboard only; vitest for backStep, focusWhere and installArrowNav. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/e2e/play-together-tv.spec.ts | 326 ++++++++++++++++++ client/src/components/OpenInAppGate.tsx | 5 +- client/src/i18n/locales/ar.ts | 4 + client/src/i18n/locales/bn.ts | 4 + client/src/i18n/locales/de.ts | 4 + client/src/i18n/locales/en.ts | 4 + client/src/i18n/locales/es.ts | 4 + client/src/i18n/locales/fa.ts | 4 + client/src/i18n/locales/fr.ts | 4 + client/src/i18n/locales/hi.ts | 4 + client/src/i18n/locales/hu.ts | 4 + client/src/i18n/locales/id.ts | 4 + client/src/i18n/locales/it.ts | 4 + client/src/i18n/locales/ja.ts | 4 + client/src/i18n/locales/ko.ts | 4 + client/src/i18n/locales/pl.ts | 4 + client/src/i18n/locales/pt-BR.ts | 4 + client/src/i18n/locales/ru.ts | 4 + client/src/i18n/locales/th.ts | 4 + client/src/i18n/locales/tr.ts | 4 + client/src/i18n/locales/vi.ts | 4 + client/src/i18n/locales/zh-CN.ts | 4 + client/src/i18n/locales/zh-TW.ts | 4 + client/src/index.css | 16 + client/src/join/JoinFlow.tsx | 15 +- client/src/join/JoinView.test.ts | 34 +- client/src/join/JoinView.tsx | 228 +++++++++++- client/src/join/PadCheck.tsx | 19 + client/src/join/main.tsx | 4 + client/src/lib/systemBack.ts | 4 +- client/src/lib/tvNav.test.ts | 22 +- client/src/lib/tvNav.ts | 29 +- .../Connection/consoles/ConsolesScreen.tsx | 10 +- client/src/screens/Home/index.tsx | 3 + client/src/screens/Play/JoinAFriend.tsx | 16 +- client/src/screens/Play/TvJoinCard.tsx | 61 ++++ client/src/screens/Play/index.tsx | 9 +- .../ps5upload-engine/src/join_page.html | 24 +- .../crates/ps5upload-engine/src/pad_page.html | 4 +- scripts/i18n-source-hashes.json | 4 + scripts/release/verify-android-apk.py | 9 +- site/join/index.html | 24 +- site/pad/index.html | 4 +- 43 files changed, 898 insertions(+), 56 deletions(-) create mode 100644 client/e2e/play-together-tv.spec.ts create mode 100644 client/src/screens/Play/TvJoinCard.tsx diff --git a/client/e2e/play-together-tv.spec.ts b/client/e2e/play-together-tv.spec.ts new file mode 100644 index 000000000..8a6e4d26d --- /dev/null +++ b/client/e2e/play-together-tv.spec.ts @@ -0,0 +1,326 @@ +import { readFile } from "node:fs/promises"; +import { expect, test, type Page, type WebSocketRoute } from "@playwright/test"; +import { routeEngine } from "./fixtures/engine"; + +// #926: Play Together on Android TV, with nothing but the TV's remote: the arrows move from +// button to button, OK (Enter) presses one, Back closes what is open and then goes back. The +// /join page (any browser, a TV's too) and the app on a TV (MainActivity's PS5UploadTv bridge, +// stubbed here) are both driven with the keyboard only; nothing is clicked. + +const INVITE = "00112233445566778899aabbccddeeff"; +const LINK = `http://192.168.1.9:19113/join#i=${INVITE}&n=Ann`; + +/** The guest page as the engine serves it (the committed build, as play-together.spec.ts). */ +async function serveJoinPage(page: Page) { + const html = await readFile( + new URL( + "../../engine/crates/ps5upload-engine/src/join_page.html", + import.meta.url, + ), + "utf8", + ); + await page.route("**/join", (route) => + route.fulfill({ contentType: "text/html", body: html }), + ); +} + +const focusedId = (page: Page) => + page.evaluate( + () => + document.activeElement?.getAttribute("data-testid") ?? + document.activeElement?.tagName ?? + null, + ); + +/** The focused control's ring, in CSS px (0: none). */ +const ringWidth = (page: Page) => + page.evaluate(() => { + const s = getComputedStyle(document.activeElement!); + return s.outlineStyle === "none" ? 0 : parseFloat(s.outlineWidth) || 0; + }); + +/** Whether the focus is inside the element with this test id. */ +const focusInside = (page: Page, id: string) => + page.evaluate( + (id) => !!document.activeElement?.closest(`[data-testid="${id}"]`), + id, + ); + +/** Press `key` until the control `id` has the focus (at most `max` times); the ids passed on the way. */ +async function pressUntil( + page: Page, + key: string, + id: string, + max = 8, +): Promise { + const seen: string[] = []; + for (let i = 0; i < max; i++) { + const at = await focusedId(page); + if (at) seen.push(at); + if (at === id) return seen; + await page.keyboard.press(key); + } + throw new Error(`${key} never reached ${id}: ${seen.join(", ")}`); +} + +/** The buttons a pad frame holds (its little-endian word after the header). */ +const held = (f: number[]) => + new DataView(Uint8Array.from(f).buffer).getUint32(5, true); + +test("the /join page with a TV's remote: arrows, OK and Back reach everything, and the game keeps its arrows", async ({ + page, +}) => { + await serveJoinPage(page); + await page.addInitScript(() => + window.localStorage.setItem("ps5upload.join.name", "Ben"), + ); + const frames: number[][] = []; + const sockets: WebSocketRoute[] = []; + let allow: () => void = () => {}; + await page.routeWebSocket(/\/api\/join\/ws/, (ws) => { + sockets.push(ws); + ws.onMessage((m) => { + if (typeof m !== "string") return void frames.push([...m]); + const v = JSON.parse(m) as { hello?: unknown; ping?: number }; + if (v.ping !== undefined) ws.send(JSON.stringify({ pong: v.ping })); + if (!v.hello) return; + ws.send(JSON.stringify({ stage: "asking" })); + allow = () => { + ws.send( + JSON.stringify({ + stage: "joined", + player: 2, + token: "TOKEN-1", + hevc: false, + }), + ); + ws.send( + JSON.stringify({ + status: { player: 2, state: "playing", rtt_ms: 12, host: "Ann" }, + }), + ); + }; + }); + }); + await page.goto(`/join#i=${INVITE}&n=Ann`, { waitUntil: "domcontentloaded" }); + + // "Open in the app?": the remote starts on the first button, Down goes to the browser. + await expect(page.getByTestId("open-in-app")).toBeFocused({ + timeout: 30_000, + }); + await page.keyboard.press("ArrowDown"); + await expect(page.getByTestId("open-in-browser")).toBeFocused(); + // A ring to see from the couch. + expect(await ringWidth(page)).toBeGreaterThanOrEqual(3); + await page.keyboard.press("Enter"); + + // The name is there from last time: Join has the focus; Up is the name, Down Join again. + await expect(page.getByTestId("join-go")).toBeFocused(); + await page.keyboard.press("ArrowUp"); + await expect(page.getByTestId("join-name")).toBeFocused(); + await page.keyboard.press("ArrowDown"); + await expect(page.getByTestId("join-go")).toBeFocused(); + await page.keyboard.press("Enter"); + + // Waiting: Cancel is the one thing to press, and has the focus. + await expect(page.getByTestId("join-stage")).toHaveText( + "Waiting for Ann to let you in", + { timeout: 30_000 }, + ); + await expect(page.getByTestId("join-cancel")).toBeFocused(); + + allow(); + await expect(page.getByTestId("join-player")).toHaveText("You are Player 2"); + // In the game the focus is the game's: the arrows press the D-pad, they don't move the focus. + await expect(page.getByTestId("join-game")).toBeFocused(); + expect(await ringWidth(page)).toBe(0); + frames.length = 0; + await page.keyboard.down("ArrowUp"); + await expect.poll(() => frames.some((f) => held(f) !== 0)).toBe(true); + await page.keyboard.up("ArrowUp"); + await expect(page.getByTestId("join-game")).toBeFocused(); + + // The first-time guide: Back (Esc here) closes it first, and the game keeps the focus. + await expect(page.getByTestId("join-guide")).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("join-guide")).toHaveCount(0); + await expect(page.getByTestId("join-game")).toBeFocused(); + + // Then the buttons, with the focus on them, every one reachable with the arrows. + await page.keyboard.press("Escape"); + await expect(page.getByTestId("join-bar")).toHaveAttribute("data-shown", "1"); + expect(await focusInside(page, "join-bar")).toBe(true); + expect(await ringWidth(page)).toBeGreaterThanOrEqual(3); + const passed = await pressUntil(page, "ArrowRight", "join-leave"); + expect(passed).toContain("join-full"); + expect(passed).toContain("join-check-open"); + + // Check your controller: opens on OK, the arrows stay inside it, Esc closes it back onto its button. + await pressUntil(page, "ArrowLeft", "join-check-open"); + await page.keyboard.press("Enter"); + await expect(page.getByTestId("join-pad-check")).toBeVisible(); + expect(await focusInside(page, "join-pad-check")).toBe(true); + for (const k of [ + "ArrowUp", + "ArrowLeft", + "ArrowDown", + "ArrowRight", + "ArrowDown", + ]) { + await page.keyboard.press(k); + expect(await focusInside(page, "join-pad-check"), k).toBe(true); + } + await page.keyboard.press("Escape"); + await expect(page.getByTestId("join-pad-check")).toHaveCount(0); + await expect(page.getByTestId("join-check-open")).toBeFocused(); + + // Esc from the buttons is back to the game. + await page.keyboard.press("Escape"); + await expect(page.getByTestId("join-game")).toBeFocused(); + + // The browser's Back (a TV's remote) from the game brings the buttons and stays on the page. + await page.evaluate(() => history.back()); + await expect.poll(() => focusInside(page, "join-bar")).toBe(true); + await expect(page.getByTestId("join-player")).toBeVisible(); + + // Leave, with the remote alone. + await pressUntil(page, "ArrowRight", "join-leave"); + await page.keyboard.press("Enter"); + await expect(page.getByTestId("join-name-step")).toBeVisible(); + await expect(page.getByTestId("join-go")).toBeFocused(); + expect(sockets.length).toBeGreaterThan(0); +}); + +/** The Android app on a TV: MainActivity's bridge says so (scripts/release/android-postinit-patch.sh). */ +async function onATv(page: Page) { + await page.addInitScript(() => { + (window as unknown as { PS5UploadTv: { isTv(): boolean } }).PS5UploadTv = { + isTv: () => true, + }; + window.localStorage.setItem("ps5upload.join.name", "Ben"); + window.localStorage.setItem("ps5upload.join.guided", "1"); + }); +} + +/** The app's system Back (MainActivity asks the page first): whether the page used it. */ +const systemBack = (page: Page) => + page.evaluate( + () => + !!(window as unknown as { __ps5uBack?: () => boolean }).__ps5uBack?.(), + ); + +test("the app on a TV: Join Play Together from the first screen, and play with the remote", async ({ + page, +}) => { + await onATv(page); + await routeEngine(page, (path) => { + if (path === "/api/version") return { version: "12.6.29", caps: {} }; + if (path === "/api/ps5/rp/session") return { host: null }; + return {}; + }); + const frames: number[][] = []; + const hellos: Array> = []; + await page.routeWebSocket(/\/api\/join\/relay/, (ws) => { + ws.onMessage((m) => { + if (typeof m !== "string") return void frames.push([...m]); + const v = JSON.parse(m) as { + hello?: Record; + ping?: number; + }; + if (v.ping !== undefined) ws.send(JSON.stringify({ pong: v.ping })); + if (!v.hello) return; + hellos.push(v.hello); + ws.send( + JSON.stringify({ + stage: "joined", + player: 2, + token: "APP", + hevc: false, + }), + ); + ws.send( + JSON.stringify({ + status: { player: 2, state: "playing", rtt_ms: 12, host: "Ann" }, + }), + ); + }); + }); + + // A new install, no PS5 of its own: the first screen offers joining a friend, focused. + await page.goto("/", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("tv-join-go")).toBeFocused({ timeout: 30_000 }); + // Add a PS5 doesn't open over it on a TV; it is a button away. + await expect(page.getByTestId("consoles-empty-add")).toBeVisible(); + expect(await ringWidth(page)).toBeGreaterThanOrEqual(3); + await page.keyboard.press("Enter"); + + // Join a friend, the remote on the link (the name is there from last time). + await expect(page.getByTestId("join-a-friend")).toBeVisible(); + await expect(page.getByTestId("join-link")).toBeFocused(); + await page.keyboard.type(LINK); + await pressUntil(page, "ArrowDown", "join-app-go"); + await page.keyboard.press("Enter"); + await expect(page.getByTestId("join-player")).toHaveText( + "Playing at Ann's · You are Player 2", + { timeout: 30_000 }, + ); + expect(hellos[0]).toEqual({ name: "Ben", invite: INVITE }); + + // On a TV the game fills the screen at once, and has the focus: the remote's arrows play. + const stage = page.getByTestId("join-stage-view"); + await expect(stage).toHaveClass(/fixed/); + await expect(page.getByTestId("join-game")).toBeFocused(); + await expect(page.getByTestId("join-tv-back")).toHaveText( + "Press Back on the remote for the buttons.", + ); + frames.length = 0; + await page.keyboard.down("ArrowLeft"); + await expect.poll(() => frames.some((f) => held(f) !== 0)).toBe(true); + await page.keyboard.up("ArrowLeft"); + await expect(page.getByTestId("join-game")).toBeFocused(); + + // Back: the buttons, the focus on them. Full screen covers the app: the arrows never leave it + // for the app behind. + expect(await systemBack(page)).toBe(true); + expect(await focusInside(page, "join-bar")).toBe(true); + for (const k of [ + "ArrowUp", + "ArrowLeft", + "ArrowLeft", + "ArrowDown", + "ArrowDown", + "ArrowRight", + "ArrowRight", + "ArrowRight", + ]) { + await page.keyboard.press(k); + expect(await focusInside(page, "join-stage-view"), k).toBe(true); + } + + // Back on the buttons leaves full screen, the focus kept on them; Full screen is reachable and + // OK turns it on again. + await pressUntil(page, "ArrowLeft", "join-full"); + expect(await systemBack(page)).toBe(true); + await expect(stage).not.toHaveClass(/fixed/); + await expect(page.getByTestId("join-full")).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(stage).toHaveClass(/fixed/); + await expect(page.getByTestId("join-full")).toBeFocused(); + + // Then the app's own Back takes over, still in the game. + expect(await systemBack(page)).toBe(true); + await expect(stage).not.toHaveClass(/fixed/); + expect(await systemBack(page)).toBe(false); + await expect(page.getByTestId("join-player")).toBeVisible(); +}); + +test("away from a TV the first screen is as before", async ({ page }) => { + await routeEngine(page, (path) => + path === "/api/version" ? { version: "12.6.29", caps: {} } : {}, + ); + await page.goto("/connection", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("consoles-list")).toBeVisible({ + timeout: 30_000, + }); + await expect(page.getByTestId("tv-join")).toHaveCount(0); +}); diff --git a/client/src/components/OpenInAppGate.tsx b/client/src/components/OpenInAppGate.tsx index 1c0f030a9..80bba9472 100644 --- a/client/src/components/OpenInAppGate.tsx +++ b/client/src/components/OpenInAppGate.tsx @@ -68,7 +68,7 @@ export function OpenInAppGate({ appLink, children }: { appLink: string; children }; return ( -
+
{phase === "ask" ? ( <> @@ -81,6 +81,8 @@ export function OpenInAppGate({ appLink, children }: { appLink: string; children )} -
@@ -492,11 +669,7 @@ export function JoinView({ // Seated in the profile the host chose: nothing to pick on the TV. const playsAs = status?.playsAs ?? null; const leftS = reconnecting ? (stage.deadline - now) / 1000 : 0; - const toggleFull = async () => { - const next = !full; - setFull(next); - await onFullscreen?.(next); - }; + const toggleFull = () => setFullscreen(!full); // A phone in the app, the game in its small box: the buttons go in a bar under the picture // (big, nothing over the game) and turning the phone sideways goes full screen, as the host's // player does. Full screen keeps them over the picture, hidden until asked for. @@ -631,7 +804,8 @@ export function JoinView({ "data-testid": "join-bar", "data-shown": chrome.shown ? "1" : "0", onFocus: (e: React.FocusEvent) => { - if ((e.target as Element).matches?.(":focus-visible")) setBarFocus(true); + // On a TV any focus is the remote's (#926). + if (tv || (e.target as Element).matches?.(":focus-visible")) setBarFocus(true); }, onBlur: (e: React.FocusEvent) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setBarFocus(false); @@ -650,11 +824,16 @@ export function JoinView({ ? "fixed inset-0 z-[200] bg-black" : "relative mx-auto aspect-video w-full max-w-[max(20rem,calc((100dvh_-_22rem)*16/9))] overflow-hidden rounded-[var(--radius-card)] bg-black shadow-[var(--shadow-2)]"; + // Full screen in the app covers the app: the remote's arrows stay inside, as in a dialog. + const fullInApp = inApp && full; return ( -
+
{ if (e.pointerType === "mouse") return poke(); const h = hold.current; @@ -755,7 +934,7 @@ export function JoinView({

)} - {checking && setChecking(false)} />} + {checking && } {showTouch && (chrome.shown ? chrome.hide() : poke())} />} @@ -795,6 +974,12 @@ export function JoinView({ )} + {/* A TV's remote has no pointer: Back is how the buttons come (#926). */} + {tv && ( + + {tr("join_tv_back_hint", undefined, "Press Back on the remote for the buttons.")} + + )}
)} @@ -839,9 +1024,8 @@ export function JoinView({
)} + + {/* The game's own focus spot (#926): with the focus here the arrows and Enter play, as with + none. Last, so Shift+Tab goes back to the buttons; it takes no touches or clicks. */} +
{below && ( // Under the picture on a phone: big, easy to hit, nothing over the game. diff --git a/client/src/join/PadCheck.tsx b/client/src/join/PadCheck.tsx index 9b63741cc..801b4a765 100644 --- a/client/src/join/PadCheck.tsx +++ b/client/src/join/PadCheck.tsx @@ -132,12 +132,27 @@ export function PadCheck({ onClose }: { onClose: () => void }) { const [saved, setSaved] = useState(loadProfiles); const [notice, setNotice] = useState(null); const [current, setCurrent] = useState(null); + const box = useRef(null); useEffect(() => { setPadChecking(true); return () => setPadChecking(false); }, []); + // A TV's remote (#926): the focus starts inside, on the main button (Set up), else on close; the + // arrows stay inside while it is open (role dialog, lib/tvNav). + useEffect(() => { + const main = box.current?.querySelector('[data-testid="join-pad-learn-start"]'); + (main ?? box.current?.querySelector('[data-testid="join-pad-check-close"]'))?.focus({ preventScroll: true }); + }, []); + + // The button pressed went away (Set up, the last step): the focus stays inside, on the first one. + useEffect(() => { + const a = document.activeElement; + if (a && a !== document.body) return; + box.current?.querySelector("button:not([disabled])")?.focus({ preventScroll: true }); + }, [learning, step]); + // Controllers come and go (a browser shows one only after a press on it). useEffect(() => { const update = () => { @@ -195,6 +210,10 @@ export function PadCheck({ onClose }: { onClose: () => void }) { return (
e.stopPropagation()} diff --git a/client/src/join/main.tsx b/client/src/join/main.tsx index e2ab0f311..c247eff2b 100644 --- a/client/src/join/main.tsx +++ b/client/src/join/main.tsx @@ -13,6 +13,10 @@ import { lanPage, lanTarget } from "./lanHint"; import { hostPath } from "./netPath"; import { joinTries, raceTransport } from "./pathRace"; import { fpOf } from "../lib/joinProtocol"; +import { installArrowNav } from "../lib/tvNav"; + +// A TV's remote (#926): the arrows move from button to button, OK presses one. +installArrowNav(); const hash = new URLSearchParams(location.hash.slice(1)); const host = hash.get("n")?.trim() || null; diff --git a/client/src/lib/systemBack.ts b/client/src/lib/systemBack.ts index 5a3788e3e..c7626717d 100644 --- a/client/src/lib/systemBack.ts +++ b/client/src/lib/systemBack.ts @@ -12,6 +12,7 @@ import { useEffect, useRef } from "react"; import { closeTopModal, onModalStackChange, openModalCount, registerBackDismiss } from "./focusTrap"; import { isMobile } from "./platform"; import { isTauriEnv } from "./tauriEnv"; +import { isTvDevice } from "./tvNav"; declare global { interface Window { @@ -86,6 +87,7 @@ let installed = false; export function installSystemBack(): void { if (installed || typeof window === "undefined") return; installed = true; - if (isTauriEnv()) installAppBack(); + // The TV bridge is the Android app's (MainActivity), which asks __ps5uBack too. + if (isTauriEnv() || isTvDevice()) installAppBack(); else if (isMobile()) installBrowserBack(); } diff --git a/client/src/lib/tvNav.test.ts b/client/src/lib/tvNav.test.ts index 1376b2642..8af154d67 100644 --- a/client/src/lib/tvNav.test.ts +++ b/client/src/lib/tvNav.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { FOCUSABLE_SELECTOR } from "./focusTrap"; -import { handleTvKey, installTvNav, isTvDevice, keepsArrow, tvNavActive } from "./tvNav"; +import { handleTvKey, installArrowNav, installTvNav, isTvDevice, keepsArrow, resetTvNavForTest, tvNavActive } from "./tvNav"; /* * Vitest runs in node (no jsdom in the client): a small fake DOM with what tvNav touches — @@ -228,6 +228,7 @@ describe("installTvNav", () => { } afterEach(() => { listeners.length = 0; + resetTvNavForTest(); }); it("is off away from a TV, and when the bridge fails", () => { @@ -252,4 +253,23 @@ describe("installTvNav", () => { expect(installTvNav(w)).toBe(true); expect(listeners).toHaveLength(1); }); + + it("the /join page moves focus with the arrows on any device, but does not mark it a TV", () => { + const { w, doc } = fakeWindow(false); + installArrowNav(w); + expect(tvNavActive(doc as unknown as Document)).toBe(false); + expect(listeners).toHaveLength(1); + listeners[0](new FakeKey("ArrowDown") as unknown as KeyboardEvent); + expect(doc.activeElement?.attrs.name).toBe("files"); + // Once only, with installTvNav too. + installArrowNav(w); + installTvNav(fakeWindow(true).w); + expect(listeners).toHaveLength(1); + }); + + it("the /join page in the TV app is marked a TV (the big focus ring)", () => { + const { w, doc } = fakeWindow(true); + installArrowNav(w); + expect(tvNavActive(doc as unknown as Document)).toBe(true); + }); }); diff --git a/client/src/lib/tvNav.ts b/client/src/lib/tvNav.ts index cf3276ad9..1e4a1233b 100644 --- a/client/src/lib/tvNav.ts +++ b/client/src/lib/tvNav.ts @@ -117,13 +117,38 @@ export function handleTvKey(e: KeyboardEvent, doc: Document = document): boolean } let installed = false; +let listening = false; + +/** Arrows move focus from now on (once per page). */ +function listen(w: Window): void { + if (listening) return; + listening = true; + // Bubble phase: controls that use the arrows themselves have had them first. + w.addEventListener("keydown", (e) => void handleTvKey(e, w.document)); +} /** Once, at start-up: on a TV, arrows move focus. Returns whether it is on. */ export function installTvNav(w: Window | undefined = typeof window === "undefined" ? undefined : window): boolean { if (installed || !w || !isTvDevice(w)) return installed; installed = true; w.document.documentElement.dataset.tv = "1"; - // Bubble phase: controls that use the arrows themselves have had them first. - w.addEventListener("keydown", (e) => void handleTvKey(e, w.document)); + listen(w); return true; } + +/** + * Once, at start-up, on a page that is only a few buttons (the /join page, #926): arrows move + * focus on every device, so a TV's browser and its remote reach every button. The game's own + * part of the page keeps the arrows (data-own-arrows), as text fields keep Left and Right. + */ +export function installArrowNav(w: Window | undefined = typeof window === "undefined" ? undefined : window): void { + if (!w) return; + if (isTvDevice(w)) w.document.documentElement.dataset.tv = "1"; + listen(w); +} + +/** Test hook. */ +export function resetTvNavForTest(): void { + installed = false; + listening = false; +} diff --git a/client/src/screens/Connection/consoles/ConsolesScreen.tsx b/client/src/screens/Connection/consoles/ConsolesScreen.tsx index 238e48be4..6688ccc45 100644 --- a/client/src/screens/Connection/consoles/ConsolesScreen.tsx +++ b/client/src/screens/Connection/consoles/ConsolesScreen.tsx @@ -16,6 +16,8 @@ import { ConsoleCard, ConsoleMeshPoll } from "./ConsoleCard"; import { AddConsoleSheet } from "./AddConsoleSheet"; import { TailnetFound } from "./TailnetFound"; import { parseInvite } from "./model"; +import { TvJoinCard } from "../../Play/TvJoinCard"; +import { tvNavActive } from "../../../lib/tvNav"; /** A link that opens one console's card (`?console=`, maybe `&devices=1`): the console to pick * at the top first (null when it is already picked, or not on the list), and the address without @@ -72,7 +74,11 @@ export default function ConsolesScreen() { const invite = useMemo(() => parseInvite(params.get("invite") ?? ""), [params]); const focusId = params.get("console"); const wantDevices = params.get("devices") === "1"; - const [addOpen, setAddOpen] = useState(() => profiles.length === 0 || !!invite || params.get("add") === "1"); + // A new install opens Add a PS5 at once; not on a TV (#926), where the first thing is usually a + // friend's game (TvJoinCard), and Add a PS5 is one button away. + const [addOpen, setAddOpen] = useState( + () => (profiles.length === 0 && !tvNavActive()) || !!invite || params.get("add") === "1", + ); useEffect(() => { getAppVersion() @@ -145,6 +151,8 @@ export default function ConsolesScreen() { } />
+ {/* A TV (#926): a guest with no PS5 of their own joins a friend's game from here. */} + {profiles.length === 0 ? setAddOpen(true)} /> : null} + {/* A TV (#926): joining a friend's game first. Nothing else changes. */} +
diff --git a/client/src/screens/Play/JoinAFriend.tsx b/client/src/screens/Play/JoinAFriend.tsx index a5dd14d52..124e07697 100644 --- a/client/src/screens/Play/JoinAFriend.tsx +++ b/client/src/screens/Play/JoinAFriend.tsx @@ -9,6 +9,7 @@ import { JoinView } from "../../join/JoinView"; import { lastName, rememberName } from "../../join/guestName"; import { useTr } from "../../state/lang"; import { useJoinPresence } from "../../state/joinPresence"; +import { tvNavActive } from "../../lib/tvNav"; import { activeJoin, useJoinStore } from "../../state/joinSession"; import { useRemotePlayStore } from "../../state/remotePlay"; import { pushNotification } from "../../state/notifications"; @@ -186,6 +187,19 @@ export function JoinAFriend({ pending, onPendingDone }: { pending?: string | nul // eslint-disable-next-line react-hooks/exhaustive-deps }, [inviteShown]); + // On a TV the remote starts in the form (#926): on the link, or on the name while there is none. + const formShown = !invite && !session; + const formBox = useRef(null); + useEffect(() => { + if (!formShown || !tvNavActive()) return; + const a = document.activeElement; + if (a && a !== document.body) return; + const id = name.trim() ? "join-link" : "join-app-name"; + formBox.current?.querySelector(`[data-testid="${id}"]`)?.focus({ preventScroll: true }); + // Only when the form shows, not as the name is typed. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [formShown]); + // An invite opened while in a game shows too: Join asks to leave that game first (okToJoin). if (invite) { const who = linkHost(invite); @@ -257,7 +271,7 @@ export function JoinAFriend({ pending, onPendingDone }: { pending?: string | nul const canScan = scanAvailable(); return ( -
+
{ diff --git a/client/src/screens/Play/TvJoinCard.tsx b/client/src/screens/Play/TvJoinCard.tsx new file mode 100644 index 000000000..1366468cc --- /dev/null +++ b/client/src/screens/Play/TvJoinCard.tsx @@ -0,0 +1,61 @@ +import { useEffect, useRef } from "react"; +import { useNavigate } from "react-router"; +import { LogIn, Users } from "lucide-react"; + +import { Button } from "../../components"; +import { tvNavActive } from "../../lib/tvNav"; +import { useTr } from "../../state/lang"; + +/** + * On a TV only (#926): the app's first screen offers joining a friend's game, the thing a TV is + * mostly used for, with a big button that takes the remote's focus. It opens Play › Join a friend, + * where the link or the short code is typed. Nothing changes anywhere else. + */ +export function TvJoinCard({ className = "" }: { className?: string }) { + const tr = useTr(); + const navigate = useNavigate(); + const tv = tvNavActive(); + const box = useRef(null); + useEffect(() => { + if (!tv) return; + // Not away from what the remote is already on. + const a = document.activeElement; + if (a && a !== document.body) return; + box.current + ?.querySelector('[data-testid="tv-join-go"]') + ?.focus({ preventScroll: true }); + }, [tv]); + if (!tv) return null; + return ( +
+ + + +
+

+ {tr("pt_title", undefined, "Play Together")} +

+

+ {tr( + "tv_join_body", + undefined, + "Got a link or a code from a friend? Play their PS5 on this TV.", + )} +

+
+ +
+ ); +} diff --git a/client/src/screens/Play/index.tsx b/client/src/screens/Play/index.tsx index 22747c82e..944e6f4e7 100644 --- a/client/src/screens/Play/index.tsx +++ b/client/src/screens/Play/index.tsx @@ -45,9 +45,16 @@ export default function PlayScreen() { useEffect(() => { if (receiveParam) navigate(`/share?receive=${encodeURIComponent(receiveParam)}`, { replace: true }); }, [receiveParam, navigate]); + // /play?mode=friend: Join a friend, the form empty (the TV's Join Play Together card, #926). + const friendParam = params.get("mode") === "friend"; const [mode, setMode] = useState(() => - joined || joinParam ? "friend" : "mine", + joined || joinParam || friendParam ? "friend" : "mine", ); + useEffect(() => { + if (!friendParam) return; + setMode("friend"); + setParams({}, { replace: true }); + }, [friendParam, setParams]); // Play together is the same stream as Play my PS5 with its invite panel (StreamPanel stays // mounted between the two, so switching never touches the stream). The stream bar's button // and the menu switch here and back. diff --git a/engine/crates/ps5upload-engine/src/join_page.html b/engine/crates/ps5upload-engine/src/join_page.html index b260f68a4..b5d815491 100644 --- a/engine/crates/ps5upload-engine/src/join_page.html +++ b/engine/crates/ps5upload-engine/src/join_page.html @@ -8,15 +8,15 @@ PS5Upload · Play Together - +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var E={a:v};this.setModule=t=>{e.setModule(bi,t)},this.getModule=()=>e.getModule(bi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,E)).then(e=>{let t=e.exports;y(t),a=t.g,o(),T(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=C,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var xi=o((()=>{}));function Si(e={}){Si.errors||Object.defineProperties(Si,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(Si.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var Ci=o((()=>{yi(),xi()})),wi,Ti=o((()=>{yi(),xi(),Ci(),wi=class extends hi{constructor(e){super(e,`opus-decoder`,Si,bi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ei=c({OpusDecoder:()=>Si,OpusDecoderWebWorker:()=>wi}),Di=o((()=>{Ci(),Ti(),yi(),_i(Si,`OpusDecoder`),_i(wi,`OpusDecoderWebWorker`)})),Oi=[8e3,12e3,16e3,24e3,48e3],ki=null;function Ai(){return ki??=Xn(()=>Promise.resolve().then(()=>(Di(),Ei)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw ki=null,e}),ki}function ji(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function Mi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ni=class{constructor(e,t=Ai){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!ji())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Oi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(Mi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Pi={makeDecoder:e=>new Ni(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Fi(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Ii(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var Li=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ri(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Li)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function zi(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Bi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Vi(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function F(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Hi=(e,t,n,...r)=>Vi(e,F([t,1],[n,3]),...r),Ui=F([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Wi(e){let t=e.handler===`vide`,n=Vi(`ftyp`,new TextEncoder().encode(`isom`),F([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Vi(`moov`,Hi(`mvhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Ui,new Uint8Array(24),F([2,4])),Vi(`trak`,Hi(`tkhd`,0,3,F([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Ui,F([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Vi(`mdia`,Hi(`mdhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Hi(`hdlr`,0,0,F([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),F([0,1])),Vi(`minf`,t?Hi(`vmhd`,0,1,new Uint8Array(8)):Hi(`smhd`,0,0,F([0,4])),Vi(`dinf`,Hi(`dref`,0,0,F([1,4]),Hi(`url `,0,1))),Vi(`stbl`,Hi(`stsd`,0,0,F([1,4]),e.sampleEntry),Hi(`stts`,0,0,F([0,4])),Hi(`stsc`,0,0,F([0,4])),Hi(`stsz`,0,0,F([0,4],[0,4])),Hi(`stco`,0,0,F([0,4])))))),Vi(`mvex`,Hi(`trex`,0,0,F([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Gi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Hi(`trun`,0,1793,F([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Vi(`traf`,Hi(`tfhd`,0,131072,F([1,4])),Hi(`tfdt`,1,0,F([t,8])),o(e)),c=Hi(`mfhd`,0,0,F([e,4])),l=Vi(`moof`,c,s(0)).length,u=Vi(`moof`,c,s(l+8)),d=Vi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Ki(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=zi(e).filter(e=>!r.includes(Bi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var qi=e=>e.toString(16).padStart(2,`0`),Ji=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Yi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Xi(e){let t=zi(e),n=t.filter(e=>Bi(e,!1)===7),r=t.filter(e=>Bi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Yi([F([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(Ji),F([r.length,1]),...r.map(Ji)])}function Zi(e,t,n){let r=zi(e),i=e=>r.filter(n=>Bi(n,t)===e),a=(e,t)=>Vi(e,new Uint8Array(6),F([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),F([24,2],[65535,2]),t);if(!t){let t=i(7),r=Xi(e);return r?{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Vi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${qi(t[0][1])}${qi(t[0][2])}${qi(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Xr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Yi([F([128|e,1],[t.length,2]),...t.map(Ji)]),m=Vi(`hvcC`,F([1,1]),u,F([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Qi(e,t,n,r,i,a){return Gi(e,t,n,Ki(r,i),a)}function $i(e,t){let n=Vi(`dOps`,F([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Wi({handler:`soun`,timescale:48e3,sampleEntry:Vi(`Opus`,new Uint8Array(6),F([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function ea(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function ta(e,t,n){return Gi(e,t,ea(n),n,!0)}var na={watch:30,player:4},ra={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ia={seek:.8,speed:.25,target:.12};function aa(e,t,n){let r=typeof n==`string`?ra[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function oa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ha(e,t,n):new ka(e,t,n)}var sa=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function I(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var L=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ca(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function la(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ua=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+da;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},da=.02;async function fa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var pa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},ma=[`pointerup`,`touchend`,`click`,`keydown`],ha=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():la(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new pa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new sa(n),this.clock=new ua(t===`player`?.05:.08),typeof AudioDecoder>`u`&&va()&&(this.mseSound=new ya(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=ni(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!xa())return!1;let e=new ka(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,ga(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=ni(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await Aa(e):Ii(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Xi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=ri(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Fi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>na[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Ki(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];fa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return va()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new si((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ca(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new ya(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new si((e,n)=>this.play(e,n,t.sampleRate),Pi,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ca(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function ga(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function _a(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function va(){let e=typeof window>`u`?null:xa();return!!e&&(_a(e,`audio/mp4; codecs="Opus"`)||_a(e,`audio/mp4; codecs="opus"`))}var ya=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new L,this.el=n,this.track=new Ta(n,()=>this.fail(),e===`player`?ia:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=I(e);if(!t||!this.order.take(t.index))return;let n=ta(this.track.nextSeq(),this.time,t.packet);this.time+=ea(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=$i(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},ba=class{constructor(e,t,n=Pi){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ua(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,ga();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new si((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ca(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function xa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var Sa=10,Ca=3;function wa(e,t,n,r=Ca){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var Ta=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=xa();if(!n||!_a(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=Ea(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=aa(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>Sa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-Ca;if(this.keys){if(r=wa(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Ca&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function Ea(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Da=1e4,Oa=class{constructor(e=3,t=Da,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ka=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new pa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new sa(n),this.fails=new Oa(3,Da,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new ya(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new Ta(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!va())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ba(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?la(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=ni(e,this.hevc)??{w:1920,h:1080},r=Zi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Fi(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>na[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Qi(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function Aa(e){let t=ii(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ri(1920,1080)}var R={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},ja={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ma(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Na={ArrowUp:{button:R.UP},ArrowDown:{button:R.DOWN},ArrowLeft:{button:R.LEFT},ArrowRight:{button:R.RIGHT},Enter:{button:R.CROSS},Space:{button:R.CROSS},Backspace:{button:R.CIRCLE},Escape:{button:R.CIRCLE},KeyQ:{button:R.SQUARE},KeyE:{button:R.TRIANGLE},KeyZ:{button:R.L1},KeyC:{button:R.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:R.L3},KeyG:{button:R.R3},Tab:{button:R.OPTIONS},Backquote:{button:R.SHARE},KeyH:{button:R.PS},KeyT:{button:R.TOUCHPAD},KeyW:{stick:`ly`,dir:-1},KeyS:{stick:`ly`,dir:1},KeyA:{stick:`lx`,dir:-1},KeyD:{stick:`lx`,dir:1},KeyI:{stick:`ry`,dir:-1},KeyK:{stick:`ry`,dir:1},KeyJ:{stick:`rx`,dir:-1},KeyL:{stick:`rx`,dir:1}};R.UP,R.DOWN,R.LEFT,R.RIGHT,R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD;var Pa=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Fa(e,t=Na){let n={...ja};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Pa(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Ia=[R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,0,0,R.SHARE,R.OPTIONS,R.L3,R.R3,R.UP,R.DOWN,R.LEFT,R.RIGHT,R.PS,R.TOUCHPAD];function La(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Ra=[0,1,1,1,0,-1,-1,-1],za=[-1,-1,0,1,1,1,0,-1];function Ba(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=La(n);return e===null?0:(t.hat===`x`?Ra:za)[e]}return t.inv?-n:n}var Va={buttons:Ia.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function Ha(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=La(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ua(e){if(e.mapping===`standard`)return Va;let t=Wa.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Va;let r={...Va,buttons:[...Va.buttons,[R.UP,{h:n,at:0}],[R.RIGHT,{h:n,at:2}],[R.DOWN,{h:n,at:4}],[R.LEFT,{h:n,at:6}]]};return Wa.set(e.id,r),r}var Wa=new Map;function Ga(e,t=Ua){let n={...ja},r=e=>Math.abs(e)<.08?0:Pa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(Ba(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Ha(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Ha(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Ha(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Ka(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Pa(e.lx+t.lx),ly:Pa(e.ly+t.ly),rx:Pa(e.rx+t.rx),ry:Pa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function qa(e,t,n,r=()=>globalThis.navigator?.getGamepads?.()??[]){let i=e=>e?.vibrationActuator;for(let a of e.some(i)?e:r()){let e=i(a);e&&(t===0&&n===0?e.reset?.():e.playEffect?.(`dual-rumble`,{duration:1e3,strongMagnitude:t/255,weakMagnitude:n/255}))}}var Ja=new Map;function Ya(e,t){return{id:`${e.id} (app)`,index:3+e.slot,connected:!0,mapping:`standard`,timestamp:0,axes:e.axes,buttons:e.buttons.map(e=>({pressed:e>.5,touched:e>0,value:e})),vibrationActuator:t?.vibrationActuator??null,hapticActuators:t?.hapticActuators??[]}}function Xa(e){let t=e?.getGamepads?.()??[];return Ja.size===0||t.some(e=>!!e?.connected)?[...t]:[...Ja.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ya(e))}var Za=`b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,,,,,,,a0,a1(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,,,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b3,b0,b1,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1(b1,b0,b2,b3,,b7,a3,a4,,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,b4,b5,,b9,,,b12,b14,b15,b13,,,a0,a1,a5~,a2~(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,,,b7,b5,b4,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b3,b4,b6,b5,b7,b2,b8,,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b9,b10,b2,b8,,,h0.1,h0.4,h0.8,h0.2,b5,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b5,b7,b2,,b8,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b12,b13,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b14,b13,b15,b12,b10,b11,b8,b9,b0,b3,b1,b2,b4,b6,b7,b5,b16,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,a2,a5,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,,,b8,b9,,,b12,b13,b15,b14,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,b11,b12,b13,b14,b15,b16,b10,,a0,a1,a2,a3(b0,b1,b3,b2,,b6,a2,a5,,b7,,,b8,b9,b10,b11,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,,,b8,b9,,,b10,b11,b12,b13,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,,,b13,b8,b10,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,,,b12,b9,b11,,,,,,,,hx,hy(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,b14,b15,b16,b17,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,,,,b2,,b4,,b5,,,h0.1,h0.4,h0.8,h0.2,b6(b0,b1,b2,b3,b12,b4,b13,b5,b14,b6,b15,b7,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b1,b3,b0,b2,b13,b5,b12,b4,,b6,,,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b33,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b16,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b15,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,,,,,b8,,a0,a1,a3,a4(b1,b0,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,,h0.1,h0.4,h0.8,h0.2,b12,b13(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b12,b13,b14,b15,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b14,b13,b14,b13,,,a0,a1,a3,a4(b1,b0,b2,b3,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b2,b3,b1,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b10(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,+a2,+a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,a2,a5,b6,b7,,,h0.1,h0.4,h0.8,h0.2,b8(b1,b2,,,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b21,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,b13,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,a5,a4,,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b7,b6,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b7,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a5,a4,b9,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b22,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a3,b6,b7,b9,,b12,b14,b15,b13,b8,,a0,a1(b3,b4,b5,b6,b7,b8,a9,a8,b11,b12,b14,b15,b16,b17,b18,b19,b13,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b7,b9,b6,b8,b10,b11,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b4,b3,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b3,b1,b4,,b10,a5,a4,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,,,,,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b10,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a4,+a4,-a3,+a3(b4,b8,b0,b12,b16,b20,b24,b28,b32,b36,b40,b44,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a8,a12(b8,b12,b0,b4,b16,b20,b24,b28,b32,b36,,,h0.1,h0.4,h0.8,h0.2,b44,,a0,a4,a8,a12(b4,b0,b8,b12,,b28,a12,a16,,b36,,,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a20,a8(b1,b2,b0,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b4,b0,b8,b12,,b28,a12,a16,,b36,,,b48,b56,b60,b52,,,a0,a4,a20,a8(b1,b2,,,b7,b5,a3,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a5,b9,b8,b6,b7,b11,b12,b13,b14,b10,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,,,b5,b8,,,-a1,+a1,-a0,+a0,b2(b0,b1,b2,b3,b4,b5,b6,b15,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b13,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,a5,a4,b12,b13,b15,b16,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,-a1,+a1,-a0,+a0,b2(b0,b1,b3,b4,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,b8,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a31(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,b6,b7,b16,b15,b8,b9,b10,b11,b13,b12,b17,,a0,a1~,a2,a3~(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a4(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b33,b5,,,b6,b7,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b2,,,,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b2,,,b6,,b9,b7,,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a2(b2,b1,b3,b0,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b4,,b6,,b2,b7,b9,,,b2,b14,b15,b13(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b5,b7,b2,b10,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,a5~,a2~,b2,b8,b8,b5,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b4,,b9,b10,b6,b7,b8,,b5,b2,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b5,b4,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b2,b6,b7,b4,b5,b8,b9,b11,b12,b13,b14,b15,b16,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b16,b19,b17,b18,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b8,b9,b6,b7,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b10,b5,b11,b7,b8,b9,b4,b6,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b5,b7,b4,b6,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b13,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b0,b4,b2,b1,b3,b6,,,b11,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a2,a5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b9,b10,a4,a5,b4,b6,b7,b8,b11,b12,b13,b14,,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b3,b2,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,b11,b14,b12,b13,b10,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,a4,a3,,,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b6,b7,b9,b10,b12,b13,b14,b15,b16,b17,b19,b20,h0.1,h0.4,h0.8,h0.2,b18,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,,,,,,,b7,b6,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,a0,a1(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a5(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a3,a4(b1,b0,b4,b3,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a5`.split(`(`),Qa={l00790006:0,l00790011:1,l00790016:2,l00790122:3,l00790126:4,l00791800:5,l00791803:6,l0079181a:7,l0079181b:8,l0079181c:9,l00791830:10,l00791843:11,l00791844:12,l00791845:11,l00791846:13,l007918d2:7,l007918d4:14,l0079954e:15,l046dc20a:16,l046dc211:17,l046dc216:5,l046dc218:5,l046dc219:5,l046dc21a:18,l046dc21d:14,l046dc21e:14,l046dc21f:14,l046dcad1:5,l046dcad2:5,l04b4010a:19,l04b42411:20,l04b42412:21,l054c0268:22,l054c05c4:23,l054c09cc:24,l054c0ba0:24,l054c0cda:25,l054c0ce6:24,l054c0df2:24,l054c0e5f:24,l054c1337:26,l057e0330:27,l057e0337:28,l057e1337:29,l057e2006:30,l057e2007:31,l057e2008:32,l057e2009:33,l057e2017:34,l057e201e:35,l057e2069:36,l057e2073:37,l05ac022d:38,l05ac055b:39,l05ac057a:40,l05ac061a:41,l0e6f0109:42,l0e6f011e:7,l0e6f011f:14,l0e6f0128:5,l0e6f012f:7,l0e6f0130:7,l0e6f0131:14,l0e6f0139:14,l0e6f0146:43,l0e6f0164:14,l0e6f0180:7,l0e6f0181:7,l0e6f0184:7,l0e6f0185:44,l0e6f0187:7,l0e6f0188:7,l0e6f0203:45,l0e6f0207:46,l0e6f0213:14,l0e6f0214:7,l0e6f02a7:14,l0e6f02a8:47,l0e6f02b2:48,l0e6f02b8:14,l0e6f02c8:14,l0e6f02d7:49,l0e6f02d8:14,l0e6f02da:14,l0e6f02ef:14,l0e6f02f1:14,l0e6f0301:14,l0e6f0315:14,l0e6f0401:14,l0e6f0413:14,l0e6f1112:50,l0e6f1113:51,l0e6ff501:14,l0f0d0009:7,l0f0d0010:42,l0f0d0011:7,l0f0d0016:52,l0f0d0022:42,l0f0d004d:7,l0f0d005e:53,l0f0d005f:54,l0f0d0066:24,l0f0d0067:14,l0f0d006a:8,l0f0d006b:7,l0f0d006d:55,l0f0d006e:7,l0f0d0084:8,l0f0d0085:7,l0f0d0086:47,l0f0d0087:56,l0f0d0088:57,l0f0d0092:58,l0f0d00aa:39,l0f0d00c1:7,l0f0d00ee:59,l0f0d00f6:60,l0f0d00fb:39,l0f0d0137:61,l0f0d0138:62,l0f0d0150:14,l0f0d0185:14,l0f0d0196:63,l0f0d01ab:63,l15320401:24,l15320402:7,l15320705:64,l15320900:65,l15320a03:14,l15320a14:14,l15320a29:14,l15321000:8,l15321008:66,l1532100a:59,l1532100b:24,l15321100:24,l18d19400:65,l20d60dad:67,l20d62002:68,l20d62005:14,l20d6200b:14,l20d6200f:69,l20d62065:14,l20d62802:14,l20d64001:70,l20d64002:70,l20d64005:14,l20d66271:71,l20d6792a:24,l20d689e5:71,l20d6a710:5,l20d6a711:7,l20d6a712:7,l20d6a713:7,l20d6a714:7,l20d6ca6d:7,l24c65300:14,l24c6531a:14,l24c6541a:14,l24c6543a:14,l24c6581a:14,l24c65b02:14,l24c65d04:14,l24c6891a:63,l24c6891b:63,l24c6892a:72,l24c6892b:63,l24c6fafe:14,l27f80bbf:63,l28de1102:73,l28de1105:73,l28de1106:73,l28de1142:73,l28de11fc:43,l28de11ff:14,l28de1201:73,l28de1202:73,l28de1205:74,l2dc80651:75,l2dc81003:76,l2dc81080:76,l2dc82000:14,l2dc82003:14,l2dc8200a:77,l2dc82019:14,l2dc82025:14,l2dc82101:63,l2dc82830:78,l2dc82862:79,l2dc82865:79,l2dc82869:80,l2dc8286a:81,l2dc83010:82,l2dc83011:63,l2dc83012:63,l2dc83013:63,l2dc83015:63,l2dc83016:63,l2dc83017:63,l2dc83019:83,l2dc8301b:63,l2dc8301d:63,l2dc83100:84,l2dc83101:85,l2dc83102:85,l2dc83103:85,l2dc83104:85,l2dc83106:14,l2dc8310a:14,l2dc8310b:14,l2dc83230:86,l2dc83810:79,l2dc83820:87,l2dc85006:88,l2dc85101:89,l2dc85103:86,l2dc85104:90,l2dc85107:91,l2dc85108:91,l2dc85109:90,l2dc85111:92,l2dc85112:82,l2dc86000:92,l2dc86001:93,l2dc86002:92,l2dc86006:82,l2dc86007:94,l2dc86009:82,l2dc86012:63,l2dc86100:87,l2dc86101:93,l2dc86102:92,l2dc86728:95,l2dc89000:96,l2dc89001:96,l2dc89012:93,l2dc89015:79,l2dc89018:78,l2dc89020:97,l2dc89025:98,l2dc8ab21:78,l35371004:14,l35371007:63,l3537100b:14,l35371046:63,l35371058:63,l35371094:63,l35371097:63,l358a0102:63,l358a0202:63,l358a0203:63,l358a0204:63,m00790006:99,m00790011:100,m00791800:101,m00791803:102,m0079181c:41,m00791843:103,m00791844:104,m00791846:105,m007918d2:39,m0079954e:106,m046dc216:5,m046dc218:5,m046dc219:5,m046dc21a:18,m046dc21f:107,m04b4010a:108,m04b42411:20,m04b42412:20,m054c0268:22,m054c05c4:24,m054c09cc:24,m054c0ba0:24,m054c0cda:25,m054c0ce6:24,m054c0df2:24,m054c0e5f:24,m054c1337:26,m057e2006:30,m057e2007:31,m057e2009:60,m057e2017:109,m057e2069:36,m057e2073:37,m05ac061a:41,m0e6f0109:42,m0e6f0184:110,m0e6f0187:5,m0e6f0201:107,m0e6f0203:45,m0e6f0207:46,m0e6f0401:107,m0f0d002d:54,m0f0d004d:7,m0f0d005e:111,m0f0d005f:7,m0f0d0066:24,m0f0d006e:7,m0f0d0084:8,m0f0d0085:7,m0f0d0087:112,m0f0d0088:57,m0f0d0092:58,m0f0d00aa:39,m0f0d00c1:7,m0f0d00ee:113,m0f0d00f6:3,m0f0d0138:62,m0f0d0200:7,m15320401:24,m15320402:7,m15320705:64,m15320900:65,m15320a03:107,m15321000:8,m15321100:24,m18d19400:65,m20d66271:71,m20d6792a:24,m20d6a710:7,m20d6a711:44,m20d6ca6d:7,m24c6543a:107,m24c65d04:107,m24c6891a:114,m24c6891b:63,m24c6892a:64,m24c6892b:63,m24c6fafe:107,m2dc80651:115,m2dc82820:116,m2dc82830:78,m2dc82840:78,m2dc82865:87,m2dc82869:80,m2dc8286a:81,m2dc83011:63,m2dc83012:63,m2dc83013:63,m2dc83015:117,m2dc83016:63,m2dc83017:118,m2dc83019:83,m2dc8301b:63,m2dc8301d:63,m2dc83100:9,m2dc83101:85,m2dc83102:85,m2dc83103:85,m2dc83104:85,m2dc83105:84,m2dc83230:119,m2dc83810:94,m2dc85006:120,m2dc85101:89,m2dc85103:86,m2dc85104:90,m2dc85107:121,m2dc85108:122,m2dc85109:90,m2dc85111:82,m2dc85112:82,m2dc86001:79,m2dc86002:85,m2dc86006:82,m2dc86009:123,m2dc86101:85,m2dc86102:85,m2dc86728:95,m2dc89000:96,m2dc89001:79,m2dc89012:78,m2dc89015:124,m2dc89018:78,m2dc89020:125,m2dc89025:126,m2dc89026:127,m2dc8ab12:116,m35371022:63,m35371041:63,m35371046:63,m35371104:63,m358a0102:63,m358a0201:128,m358a0202:128,m358a0203:128,m358a0204:63,w00790002:129,w00790007:129,w0079000a:129,w00790016:18,w00790122:99,w00790126:130,w00791804:131,w0079181a:7,w0079181b:113,w00791824:132,w00791830:133,w00791845:11,w00791847:12,w0079184f:134,w00791879:135,w0079188f:136,w007918ae:137,w007918d4:138,w046dc209:139,w046dc20a:16,w046dc20b:140,w046dc211:141,w046dc21d:138,w046dc21e:142,w046dc242:142,w046dca84:143,w046dca88:143,w046dcad1:5,w046dcad2:7,w04b42410:144,w04b4c681:130,w054c05c5:145,w057e0330:146,w05ac022d:144,w05ac033d:147,w05ac044d:147,w05ac055b:39,w05ac057a:148,w0e6f0003:149,w0e6f0111:7,w0e6f0114:7,w0e6f0119:7,w0e6f011a:7,w0e6f011e:7,w0e6f011f:150,w0e6f0124:42,w0e6f0128:7,w0e6f012f:7,w0e6f0130:7,w0e6f0132:7,w0e6f0146:138,w0e6f0164:151,w0e6f0180:7,w0e6f0181:7,w0e6f0185:44,w0e6f0188:7,w0e6f0189:7,w0e6f0214:7,w0e6f0301:138,w0e6f1113:51,w0e6f6302:7,w0f0d0009:7,w0f0d000a:152,w0f0d000c:153,w0f0d000d:154,w0f0d0010:155,w0f0d0011:57,w0f0d0013:155,w0f0d001b:152,w0f0d0021:155,w0f0d0022:54,w0f0d0025:42,w0f0d0026:155,w0f0d0027:42,w0f0d0032:155,w0f0d003d:156,w0f0d0040:157,w0f0d0042:155,w0f0d0049:7,w0f0d004b:155,w0f0d0051:155,w0f0d0054:7,w0f0d0055:8,w0f0d005b:113,w0f0d005c:7,w0f0d0064:155,w0f0d0067:70,w0f0d006a:8,w0f0d006b:7,w0f0d006f:158,w0f0d0070:57,w0f0d007b:155,w0f0d008a:8,w0f0d008b:7,w0f0d008c:138,w0f0d009c:8,w0f0d00a0:159,w0f0d00a5:160,w0f0d00a6:111,w0f0d00ad:161,w0f0d00ae:142,w0f0d00af:162,w0f0d00c0:138,w0f0d00c9:5,w0f0d00d8:163,w0f0d00dc:138,w0f0d0101:5,w0f0d0104:142,w0f0d0123:144,w0f0d0137:164,w0f0d0162:165,w0f0d0164:166,w0f0d0196:134,w0f0d0202:167,w0f0d1011:168,w153202a6:169,w15320300:170,w15320707:147,w15320a14:138,w15321004:145,w15321007:145,w15321009:145,w1532100a:5,w18d12c40:171,w20d60060:7,w20d60dad:142,w20d6319f:7,w20d64026:134,w20d64033:134,w20d6571d:7,w20d6576d:7,w20d65795:7,w20d657c7:7,w20d657e5:7,w20d689e5:172,w20d6a712:7,w20d6a713:7,w20d6a714:7,w20d6a720:7,w24c6531a:153,w24c65b02:138,w27f80bbf:173,w28de11fc:70,w28de11ff:174,w2dc802e0:175,w2dc81003:176,w2dc81080:176,w2dc82100:144,w2dc82810:177,w2dc82862:78,w2dc83000:78,w2dc83001:178,w2dc8301c:134,w2dc8310a:134,w2dc83820:179,w2dc85001:180,w2dc86000:79,w2dc86003:123,w2dc86012:134,w2dc86100:85,w2dc86103:123,w2dc8ab11:179,w2dc8ab20:178,w2dc8ab21:78,w35371004:138,w35371007:134,w35371094:134,w35371116:134},$a=e=>e.toLowerCase().padStart(4,`0`);function eo(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:$a(t[2]),product:$a(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:$a(n[1]),product:$a(n[2]),name:n[3].trim()}:null}function to(e){return(eo(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function no(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function ro(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Qa[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Za[n]??null}return null}function io(e){return e.mapping!==`standard`&&eo(e.id)?.vendor===`2dc8`}var ao={6003:`switch`,6006:`switch`,6103:`switch`,3010:`switch`,6001:`startx`,6002:`startx`,6101:`startx`,6102:`startx`,3011:`receiver`,3012:`receiver`,3013:`receiver`,3015:`receiver`,3016:`receiver`,3017:`receiver`,"301b":`receiver`,"301c":`receiver`,"301d":`receiver`,6012:`receiver`,5112:`none`,9020:`none`};function oo(e){let t=eo(e);return t&&ao[t.product]||`manual`}var so={1:0,2:2,4:4,8:6};function co(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function lo(e,t,n){let{n:r,hat:i}=co(t),a=Ia.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function uo(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=so[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function fo(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function po(e,t,n){let r=e.split(`,`),i=lo(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&_o(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(_o)}function yo(){try{let e=Lt(go),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>vo(e[1])))}catch{return{}}}function bo(e,t){let n=yo();return t?n[e]=t:delete n[e],It(go,JSON.stringify(n)),xo=n,n}var xo=null;function So(e){return xo??=yo(),xo[e.id]??To(xo,e.id)??ho(e)??Ua(e)}function Co(e){return xo??=yo(),xo[e.id]?`saved`:e.mapping===`standard`?`standard`:ho(e)?`known`:`guess`}function wo(e){return ho(e)??Ua(e)}function To(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(xo=bo(t,e[i]),e[i]):null}function Eo(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Do(e,t){let n=null;if(t.buttons.forEach((t,r)=>{let i=t-(e.buttons[r]??0);t>.5&&i>.5&&(!n||i>n.amount)&&(n={src:{b:r},amount:i})}),n)return n.src;for(let n=0;n1.05?La(t.axes[n]):null;if(r!==null)return{h:n,at:r}}return t.axes.forEach((t,r)=>{let i=e.axes[r]??0,a=t-i;if(!(Math.abs(a)<.6)&&(!n||Math.abs(a)>n.amount)){let e=a>0?1:-1;n={src:Math.abs(i)>.5?{a:r,d:e,rest:i}:{a:r,d:e},amount:Math.abs(a)}}}),n?n.src:null}function Oo(e,t){let n=null;if(t.axes.forEach((t,r)=>{let i=t-(e.axes[r]??0);Math.abs(i)>=.6&&(!n||Math.abs(i)>Math.abs(n.moved))&&(n={a:r,moved:i})}),!n)return null;let r=n;return r.moved>0?{a:r.a}:{a:r.a,inv:!0}}var ko=[{kind:`button`,bit:R.CROSS,name:`✕`},{kind:`button`,bit:R.CIRCLE,name:`○`},{kind:`button`,bit:R.SQUARE,name:`□`},{kind:`button`,bit:R.TRIANGLE,name:`△`},{kind:`button`,bit:R.UP,name:`↑`},{kind:`button`,bit:R.DOWN,name:`↓`},{kind:`button`,bit:R.LEFT,name:`←`},{kind:`button`,bit:R.RIGHT,name:`→`},{kind:`button`,bit:R.L1,name:`L1`},{kind:`button`,bit:R.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:R.L3,name:`L3`},{kind:`button`,bit:R.R3,name:`R3`},{kind:`button`,bit:R.OPTIONS,name:`Options`},{kind:`button`,bit:R.SHARE,name:`Create`},{kind:`button`,bit:R.PS,name:`PS`},{kind:`button`,bit:R.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}];function Ao(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function jo(e,t,n){return t.kind===`button`?{...e,buttons:[...e.buttons.filter(([e])=>e!==t.bit),[t.bit,n]]}:(t.kind,{...e,[t.which]:n})}function Mo(e,t=Va){let n=new Set(e.buttons.map(([e])=>e)),r=e=>`b`in e?`b${e.b}`:`h`in e?`h${e.h}.${e.at}`:`a${e.a}${e.d}`,i=new Set([...e.buttons.map(([,e])=>r(e)),...[e.l2,e.r2].filter(e=>!!e).map(r)]);return{buttons:[...e.buttons,...t.buttons.filter(([e,t])=>!n.has(e)&&!i.has(r(t)))],l2:e.l2??t.l2,r2:e.r2??t.r2,lx:e.lx??t.lx,ly:e.ly??t.ly,rx:e.rx??t.rx,ry:e.ry??t.ry}}var No=ko.filter(e=>e.kind!==`button`||![R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD].includes(e.bit));function Po(e,t){return t.buttons.every((t,n)=>Math.abs(t-(e.buttons[n]??0))<.3)&&t.axes.every((t,n)=>Math.abs(t-(e.axes[n]??0))<.3)}var Fo=class{constructor(e=ko){this.steps=e,this.step=0,this.prof=Ao(),this.rest=null,this.waiting=!0}get done(){return this.step>=this.steps.length}get current(){return this.steps[this.step]??null}feed(e){if(this.done)return!1;if(!this.rest)return this.rest=e,this.waiting=!1,!1;if(this.waiting)return Po(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Oo(this.rest,e):Do(this.rest,e);return n?(this.prof=jo(this.prof,t,n),this.go(this.step+1),!0):!1}skip(){this.go(this.step+1)}back(){this.step>0&&this.go(this.step-1)}go(e){this.waiting=!0,this.step=Math.min(e,this.steps.length)}profile(e=Va){return Mo(this.prof,e)}};function Io(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}function Lo(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Ro=e=>`ps5upload.join.token.${e??`app`}`,zo=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...ja},this.lastSent=0,this.neutral=!1,this.stopped=!1,this.attempt=0,this.deadline=0,this.raf=0,this.keepalive=null,this.pinger=null,this.retry=null,this.lastHeard=0,this.hostAway=!1,this.pings=0,this.now=e.now??(()=>Date.now()),this.storage=e.storage===void 0?Lo():e.storage,this.WS=e.WebSocketImpl??WebSocket,this.seq=this.now()>>>0;try{this.token=this.storage?.getItem(this.key)??null}catch{this.token=null}}get key(){return Ro(this.o.invite??this.o.code??null)}get current(){return this.stage}get socket(){return this.ws}get resumeToken(){return this.token}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.stopped=!1,this.setStage({kind:`connecting`}),this.connect(),this.stopped)return;let e=()=>{this.sendPad(!1),this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e)};this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e),this.keepalive=setInterval(()=>this.sendPad(!1),100),this.pinger=setInterval(()=>this.ping(),1e3)}connect(){let e;try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,e.onopen=()=>{if(this.ws!==e)return;this.lastHeard=this.now();let t={name:this.o.name};this.o.invite&&(t.invite=this.o.invite),this.o.code&&(t.code=this.o.code),this.token&&(t.resume=this.token),e.send(JSON.stringify({hello:t}))},e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),typeof t.data==`string`?this.onText(t.data):t.data instanceof ArrayBuffer&&this.stage.kind===`joined`&&this.o.onFrame?.(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Ue(t);n===`mismatch`?(this.forgetToken(),this.finish({kind:`ended`,why:n})):n&&this.stage.kind!==`joined`&&this.stage.kind!==`reconnecting`?this.finish({kind:`ended`,why:n}):this.dropped()},e.onerror=()=>{}}onText(e){let t=Je(e);if(t)switch(t.kind){case`pong`:{let e=this.now()-t.t;e>=0&&e<6e4&&this.o.onRtt?.(e);return}case`asking`:this.stage.kind!==`reconnecting`&&this.setStage({kind:`asking`});return;case`waiting`:this.hostAway||(this.hostAway=!0,this.deadline=this.now()+et),this.attempt=0,this.setStage(this.reconnectingStage());return;case`joined`:this.token=t.token,this.player=t.player,this.attempt=0,this.hostAway=!1;try{this.storage?.setItem(this.key,t.token)}catch{}{let e=t.track&&this.ws?.media||null;this.o.onCodec?.(t.hevc,e,!!e&&t.audio&&!!e.audio)}this.setStage({kind:`joined`,player:t.player,hevc:t.hevc}),this.sendPad(!0);return;case`refused`:this.forgetToken(),this.hostAway&&t.why!==`seat_taken`?this.finish({kind:`ended`,why:`host_stopped`}):this.finish({kind:`refused`,why:t.why});return;case`bye`:if(t.why===`host_stopped`&&this.token){this.hostWait();return}this.forgetToken(),this.finish({kind:`ended`,why:t.why});return;case`status`:this.stage.kind===`joined`&&t.status.player>0&&t.status.player!==this.stage.player&&(this.player=t.status.player,this.setStage({...this.stage,player:t.status.player})),this.o.onStatus?.(t.status);return;case`feedback`:t.rumble&&this.o.onRumble?.(t.rumble[0],t.rumble[1]),t.light&&this.o.onLight?.(t.light);return}}hostWait(){this.hostAway=!0,this.deadline=this.now()+et,this.attempt=0;let e=this.ws;this.ws=null;try{e?.close()}catch{}this.scheduleRetry()}reconnectingStage(){return{kind:`reconnecting`,player:this.player,attempt:this.attempt,deadline:this.deadline,...this.hostAway?{hostStopped:!0}:{}}}giveUp(){this.forgetToken(),this.finish({kind:`ended`,why:this.hostAway?`host_stopped`:`gave_up`})}dropped(){if(this.stopped)return;let e=this.stage;e.kind===`joined`||e.kind===`reconnecting`&&this.token?(e.kind===`joined`&&(this.deadline=this.now()+$e),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Qe(this.attempt);this.setStage(this.reconnectingStage()),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.stopped||(this.now()>=this.deadline?this.giveUp():this.connect())},e)}forgetToken(){this.token=null;try{this.storage?.removeItem(this.key)}catch{}}ping(){if(this.hostAway&&!this.stopped&&this.now()>=this.deadline+5e3||!this.stopped&&this.stage.kind===`reconnecting`&&this.now()>=this.deadline+5e3){this.giveUp();return}let e=this.ws;if(e&&e.readyState===this.WS.OPEN){if(this.stage.kind===`joined`&&this.now()-this.lastHeard>3500){this.ws=null;try{e.close()}catch{}this.dropped()}else if(e.send(JSON.stringify({ping:this.now()})),this.stage.kind===`joined`&&this.o.readStats&&++this.pings%2==0){let t=this.o.readStats();t&&e.send(JSON.stringify({stats:t}))}}}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.sendPad(!0))}sendPad(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||this.stage.kind!==`joined`)return;let n=this.neutral?{...ja,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Io(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Ze(this.seq,n)))}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.pinger&&clearInterval(this.pinger),this.retry&&clearTimeout(this.retry),this.keepalive=this.pinger=this.retry=null}finish(e){this.stopped=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&e.send(JSON.stringify({keyframe:!0}))}leave(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&(this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),e.send(JSON.stringify({leave:1}))),this.forgetToken(),this.finish({kind:`ended`,why:`left`})}stop(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},Bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),z=s(((e,t)=>{t.exports=Bo()}))(),Vo=`ps5upload.openIn`,Ho=`ps5upload.openIn.tab`;function Uo(){try{return sessionStorage.getItem(Ho)===`browser`}catch{return!1}}function B(){try{sessionStorage.setItem(Ho,`browser`)}catch{}}function V(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Wo({appLink:e,children:t}){let n=Ie(),[r,i]=(0,D.useState)(()=>Uo()?`browser`:V(Lt(Vo))),[a,o]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,z.jsx)(z.Fragment,{children:t});let s=()=>{a&&It(Vo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?It(Vo,`browser`):r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&Rt(Vo),B(),i(`browser`)};return(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,z.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,z.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}var Go=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type='hidden'])`,`select:not([disabled])`,`textarea:not([disabled])`,`summary`,`[contenteditable='true']`,`[tabindex]`].map(e=>`${e}:not([tabindex='-1'])`).join(`, `),Ko=new Set,qo=[];function Jo(){for(let e of Ko)e()}function Yo(){return qo.length}function Xo(e){return qo.push(e),Jo(),()=>{let t=qo.lastIndexOf(e);t!==-1&&qo.splice(t,1),Jo()}}function Zo(e,t,n){switch(n){case`down`:return t.top-e.bottom;case`up`:return e.top-t.bottom;case`right`:return t.left-e.right;case`left`:return e.left-t.right}}function H(e,t,n){let r=(e.left+e.right)/2,i=(e.top+e.bottom)/2,a=(t.left+t.right)/2,o=(t.top+t.bottom)/2;switch(n){case`down`:return o>i&&t.top>=e.top+1;case`up`:return or&&t.left>=e.left+1;case`left`:return a0?{gap:0,overlap:c}:{gap:-c,overlap:0}}function $o(e,t,n){let r=null,i=1/0,a=!1;for(let o of t){if(!H(e,o.rect,n))continue;let t=Math.max(0,Zo(e,o.rect,n)),s=Qo(e,o.rect,n),c=s.overlap>0;if(a&&!c)continue;let l=c?t-s.overlap/1e6:Math.hypot(t,2*s.gap);(c&&!a||l`u`?void 0:window){try{return!!e?.PS5UploadTv?.isTv()}catch{return!1}}function rs(e=typeof document>`u`?void 0:document){return e?.documentElement.dataset.tv===`1`}function is(e,t){if(!e)return!1;if(e.closest(`[data-own-arrows]`))return!0;let n=e.tagName;if(n===`TEXTAREA`||e.isContentEditable)return!0;let r=t===`left`||t===`right`;if(n===`INPUT`){let t=(e.type||`text`).toLowerCase();if(t===`range`||ts.test(t))return r}return!1}var as=`[aria-modal="true"], [role="dialog"], [role="alertdialog"]`;function os(e){let t=e.activeElement?.closest(as);if(t)return t;if(Yo()>0){let t=e.querySelectorAll(as);if(t.length)return t[t.length-1]}return e}function ss(e){let t=[];return e.querySelectorAll(Go).forEach(e=>{if(e.closest(`[inert], [aria-hidden='true']`)||e.disabled)return;let n=e.getBoundingClientRect();n.width<=0||n.height<=0||t.push({el:e,rect:n})}),t}function cs(e){return(e.find(e=>e.el.getAttribute(`aria-current`)===`page`)??e[0])?.el??null}function ls(e,t=document){let n=es[e.key];if(!n||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return!1;let r=t.activeElement;if(is(r,n))return!1;let i=ss(os(t));if(!i.length)return!1;let a=i.find(e=>e.el===r),o=a?$o(a.rect,i.filter(e=>e!==a),n):cs(i);return o?(e.preventDefault(),o.focus(),typeof o.scrollIntoView==`function`&&o.scrollIntoView({block:`nearest`,inline:`nearest`}),!0):!1}var us=!1;function ds(e){us||(us=!0,e.addEventListener(`keydown`,t=>void ls(t,e.document)))}function fs(e=typeof window>`u`?void 0:window){e&&(ns(e)&&(e.document.documentElement.dataset.tv=`1`),ds(e))}function ps({id:e,className:t}){let n=Ie(),r=oo(e);if(r===`none`)return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_no_xinput`,void 0,`This 8BitDo has no X-input mode. If a button is wrong, check the controller.`)});let i=r===`switch`?n(`pad_8bitdo_how_switch`,void 0,`set the switch on the back to X, then press Start`):r===`startx`?n(`pad_8bitdo_how_startx`,void 0,`turn it off, then hold Start + X to turn it on`):r===`receiver`?n(`pad_8bitdo_how_receiver`,void 0,`use its 2.4G receiver or a USB cable`):n(`pad_8bitdo_how_manual`,void 0,`its manual says how`);return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_xinput`,{how:i},`For the best result, switch your 8BitDo to X-input mode: ${i}.`)})}var ms=new Set,hs={held:new Set,touch:null,touchPad:ja,mapping:!1,get paused(){return ms.size>0},motion:null},gs={s:.85,m:1,l:1.15},_s=.25;function vs(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(_s,e))}var ys={overlay:{width:844,height:390},deck:{width:390,height:480}},bs=.7,xs=1.4;function Ss(e,t,n,r){let i=gs[e]??1;if(!(t>0)||!(n>0))return i;let a=r?ys.deck:ys.overlay,o=Math.min(xs,Math.max(bs,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var Cs=34;function ws(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+Cs>t}function Ts(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var Es=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,Ds=32767,Os=12;function ks({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Ie(),s=(0,D.useRef)(new Map),c=(0,D.useRef)({...ja}),[l,u]=(0,D.useState)({...ja}),[d,f]=(0,D.useState)({l:!1,r:!1,touchpad:!1}),p=(0,D.useRef)(null),[m,h]=(0,D.useState)({width:0,height:0});(0,D.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,D.useEffect)(()=>()=>{hs.touchPad={...ja}},[]);let g=()=>{let t={...ja,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=R.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,hs.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*Ds),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*Ds)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ma((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ma((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Os&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,C=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,w=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,T={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},E=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),te=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ne={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},re=(e,t,n,r)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${te} ${n}`,style:ne,children:r}),ie=(e,t,n,r)=>(0,z.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${w} ${C(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),ae=(e,t,n,r)=>re(e,t,`h-[44px] w-[84px]`,ie(e,ee(t),n,r)),oe=(e,t,n)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${te} h-[44px] w-[84px]`,style:ne,children:ie(e,l[t]>0,n,!0)}),se=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:(0,z.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...E(ee(t)),children:[(0,z.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,z.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ce=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:[(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...E(ee(t))}),(0,z.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),le=(e,t)=>re(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,z.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${w} ${C(ee(t))}`,children:e})),ue=(e,t)=>re(e,t,`h-[44px] w-[44px]`,(0,z.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),de=e=>{let{dx:t,dy:n}=Ts(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,z.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,z.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${C(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},O=t===`deck`,fe=Ss(r,m.width,m.height,O),pe=e=>`${e}px * var(--k)`,k=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=O?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${pe(t)}, ${n}px))`:`calc(${e} + ${pe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=O&&ws(fe,m.height),A=O?void 0:`58%`,j=e=>O?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?k:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?k:me},xe=e=>({bottom:be?he:_e(he,O?56:0,44),[e]:be?`calc(${e===`left`?k:me} + 8px + max(${pe(80)}, 44px))`:_e(e===`left`?k:me,O?40:168)}),Se=!!a&&!O;return(0,z.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${O?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:O?i:void 0,"--k":fe},"data-testid":`rp-touch`,"data-layout":t,"data-scale":fe,onContextMenu:e=>e.preventDefault(),children:[(0,z.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:vs(n)},children:[(0,z.jsx)(`div`,{style:ye(`top left`,{top:ge,left:k}),children:(0,z.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:O?void 0:`6deg`,transformOrigin:`top left`},children:[oe(`L2`,`l2`,`l`),ae(`L1`,R.L1,`l`,!1)]})}),(0,z.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,z.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:O?void 0:`-6deg`,transformOrigin:`top right`},children:[oe(`R2`,`r2`,`r`),ae(`R1`,R.R1,`r`,!1)]})}),(0,z.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:O?{top:_e(ge,6),left:_e(k,104),right:_e(me,104),height:`max(44px, calc(${pe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${pe(250)}), 34vw)`,height:`max(44px, calc(${pe(56)}))`}}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top left`:`left center`,j(`left`)),children:[(0,z.jsx)(`span`,{}),se(`↑`,R.UP,0),(0,z.jsx)(`span`,{}),se(`←`,R.LEFT,-90),(0,z.jsx)(`span`,{}),se(`→`,R.RIGHT,90),(0,z.jsx)(`span`,{}),se(`↓`,R.DOWN,180),(0,z.jsx)(`span`,{})]}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top right`:`right center`,j(`right`)),children:[(0,z.jsx)(`span`,{}),ce(`△`,R.TRIANGLE,(0,z.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,z.jsx)(`span`,{}),ce(`□`,R.SQUARE,(0,z.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,z.jsx)(`span`,{}),ce(`○`,R.CIRCLE,(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,z.jsx)(`span`,{}),ce(`✕`,R.CROSS,(0,z.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:de(`l`)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:de(`r`)}),(0,z.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:k}),children:le(`Create`,R.SHARE)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:le(`Options`,R.OPTIONS)}),(0,z.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:Es,translate:`-50% 0`}),children:ue(`PS`,R.PS)})]}),Se&&(0,z.jsx)(`div`,{style:{...ye(`bottom center`,{bottom:he,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,vs(n))},children:(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${te} h-[44px] w-[56px]`,style:ne,"data-testid":`rp-menu-handle`,children:(0,z.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,z.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var As=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,js=null,Ms=null;function Ns(e){e.play().catch(()=>{if(Ms||js!==e)return;let t=()=>{Ps(),js===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),Ms=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Ps(){Ms?.(),Ms=null}function Fs(){if(typeof document<`u`){if(!js){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=As,document.body.appendChild(e),js=e}Ns(js)}}function Is(){Ps(),js&&=(js.pause(),js.removeAttribute(`src`),js.remove(),null)}function Ls(){return typeof navigator>`u`?null:navigator.wakeLock??null}function Rs(){return dt()||!Pn()}var zs=new Set,Bs=null,Vs=Promise.resolve(),Hs=!1;async function Us(){if(zs.size===0||Bs&&!Bs.released)return;let e=Ls();if(!e)dt()&&Fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{Bs===t&&(Bs=null)}),Bs=t}catch{}}async function Ws(){Is();let e=Bs;if(Bs=null,e&&!e.released)try{await e.release()}catch{}}function Gs(){Hs||typeof document>`u`||(Hs=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&zs.size>0&&(Vs=Vs.then(Us))}))}function Ks(e,t){if(!Rs())return;Gs();let n=zs.size>0;t?zs.add(e):zs.delete(e);let r=zs.size>0;n!==r&&(Vs=Vs.then(r?Us:Ws))}var qs=new Set;function Js(){if(typeof window<`u`)return window.PS5UploadPad}function Ys(e,t){let n=qs.size>0;t?qs.add(e):qs.delete(e);let r=qs.size>0;if(n!==r)try{Js()?.setActive(r)}catch{}}var Xs=class e{constructor(e){this.receiver=e,this.last=null,this.was={}}get frames(){return Number(this.last?.frames??0)}static report(e,t){let n=t=>e[t]??0,r=e=>n(e)-(t[e]??0),i=(e,t)=>r(t)>0?Math.round(r(e)/r(t)*1e4)/10:0;return{frames:n(`framesDecoded`),dropped:n(`framesDropped`),stalls:n(`freezeCount`),stall_ms:Math.round(n(`totalFreezesDuration`)*1e3),decode_ms:i(`totalDecodeTime`,`framesDecoded`),jitter_ms:i(`jitterBufferDelay`,`jitterBufferEmittedCount`),nacks:n(`nackCount`),plis:n(`pliCount`),decoder:`track`}}snapshot(){return this.receiver.getStats().then(t=>{t.forEach(t=>{t.type===`inbound-rtp`&&t.kind===`video`&&(this.last=e.report(t,this.was),this.was={...t})})}).catch(()=>{}),this.last}},Zs=class{constructor(e){this.inner=e,this.video=document.createElement(`video`),this.wrap=document.createElement(`div`),this.media=null,this.trackStats=null,this.audio=!1,this.soundOn=!1,this.muted=!1;let t=this.video;t.muted=t.autoplay=t.playsInline=!0,t.className=`block h-full w-full object-contain`,t.dataset.testid=`track-video`,this.wrap.className=`h-full w-full`,this.wrap.append(t,e.element),this.setTrack(null)}get element(){return this.wrap}get stats(){return this.trackStats??this.inner.stats}setTrack(e,t=!1){this.media=e,this.audio=!!e&&t,this.applySound(),this.trackStats=e?new Xs(e.receiver):null,this.video.style.display=e?``:`none`,this.inner.element.style.display=e?`none`:``,this.video.srcObject!==(e?.stream??null)&&(this.video.srcObject=e?.stream??null),e&&this.play()}play(){try{this.video.play()?.catch?.(()=>{})}catch{}}onMessage(e){let t=new Uint8Array(e)[0];this.media&&t<=1||(!this.audio||t!==3&&t!==4)&&this.inner.onMessage(e)}applySound(){this.video.muted=!(this.audio&&this.soundOn&&!this.muted)}setHevc(e){this.inner.setHevc(e)}set onSoundFail(e){this.inner.onSoundFail=e}soundReport(){return this.inner.soundReport()}startSound(){this.inner.startSound(),this.soundOn=!0,this.applySound(),this.media&&this.play()}setMuted(e){this.inner.setMuted(e),this.muted=e,this.applySound()}resumeSound(){this.inner.resumeSound(),this.media&&this.video.paused&&this.play()}stop(){this.inner.stop(),this.video.srcObject=null}},Qs=`ps5upload.join.muted`,$s=5e3,ec=Object.fromEntries(Object.entries(Na).filter(([e])=>e!==`Escape`)),tc=new Set;function nc(e){if(!(e.code in ec)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||rc(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||rc(t))}function rc(e){let t=e?.tagName;if(t===`BUTTON`||t===`A`)return!0;let n=e?.getAttribute?.(`role`);return n===`button`||n===`link`||n===`menuitem`||n===`tab`||n===`switch`}var ic=!1;function ac(e){ic=e}function oc(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function sc(){if(ic)return{...ja};let e=Ga(Xa(typeof navigator>`u`?void 0:navigator),So),t=hs.touchPad;return{...Ka(Ka(e,Fa(tc,ec)),t),touch:t.touch??null,motion:hs.motion??null}}var cc=class{constructor(e){this.opts=e,this.player=null,this.listeners=new Set,this.cleanups=[],this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.snap={stage:{kind:`connecting`},status:null,rttMs:null,light:null,problem:null,sound:!1,noSound:!1,host:e.host,muted:uc(),path:null},this.client=new zo({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:sc,onStage:e=>{this.set({stage:e}),e.kind===`joined`&&this.readPath(),(e.kind===`refused`||e.kind===`ended`)&&this.teardown()},onStatus:e=>this.set({status:e,host:e.host??this.snap.host}),onRtt:e=>this.set({rttMs:e}),onFrame:e=>this.picture().onMessage(e),readStats:()=>oc(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Zs&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Xa(typeof navigator>`u`?void 0:navigator);qa(n,e,t),n.some(e=>e?.connected)||navigator.vibrate?.(e||t?200:0)},onLight:e=>this.set({light:e})})}picture(){if(!this.player){let e=oa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Zs(e):e,this.player.onSoundFail=()=>this.set({noSound:!0}),this.player.setMuted(this.snap.muted)}return this.player}async readPath(){let e=this.client.socket,t=this.opts.path??null;if(e?.netPath)try{t=await e.netPath()??this.opts.path??null}catch{t=null}t!==this.snap.path&&this.set({path:t})}get element(){return this.picture().element}start(){let e=()=>{document.visibilityState===`hidden`?tc.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{tc.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&nc(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),tc.add(e.code))},r=e=>{tc.delete(e.code)&&nc(e)&&e.preventDefault()};window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r);let i=()=>{this.client.setNeutral(document.visibilityState===`hidden`),document.visibilityState!==`hidden`&&this.player?.resumeSound()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`blur`,t),window.addEventListener(`focus`,i);let a=setInterval(()=>{this.client.current.kind===`joined`&&this.readPath()},$s);this.cleanups.push(()=>{clearInterval(a),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`blur`,t),window.removeEventListener(`focus`,i),window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),tc.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(Qs,e?`1`:`0`)}catch{}this.set({muted:e})}startSound(){this.snap.sound||(this.picture().startSound(),this.set({sound:!0}))}leave(){this.client.leave(),this.teardown()}stop(){this.client.stop(),this.teardown()}teardown(){for(let e of this.cleanups.splice(0))e();hs.touchPad={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};let e=this.player;this.player=null,e&&(e.stop(),e.element.remove())}sendPad(){this.client.sendPad(!1)}get snapshot(){return this.snap}set(e){this.snap={...this.snap,...e};for(let e of this.listeners)e()}};function lc(e){return(0,D.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function uc(){try{return typeof localStorage<`u`&&localStorage.getItem(Qs)===`1`}catch{return!1}}function dc(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Ks(`play-together`,n),Ys(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Ks(`play-together`,!1),Ys(`play-together`,!1)}}var fc=3e3,pc=class{constructor(e,t=fc){this.onChange=e,this.delay=t,this.enabled=!1,this.pinned=!1,this.sticky=!1,this.shown=!0,this.timer=null}get visible(){return!this.enabled||this.pinned||this.shown}set(e,t,n=!1){let r=this.enabled&&!this.pinned,i=this.enabled,a=this.sticky;this.enabled=e,this.pinned=t,this.sticky=n,!e||t?(this.stop(),this.show(!0)):n?(this.stop(),!i||!a?this.show(!1):r||this.show(!0)):(!r||a)&&(this.show(!0),this.arm())}poke(){this.show(!0),this.enabled&&!this.pinned&&!this.sticky&&this.arm()}toggle(){this.visible?this.hide():this.poke()}hide(){this.enabled&&!this.pinned&&(this.stop(),this.show(!1))}dispose(){this.stop()}arm(){this.stop(),this.timer=setTimeout(()=>{this.timer=null,this.show(!1)},this.delay)}stop(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}show(e){this.shown!==e&&(this.shown=e,this.onChange(e))}};function mc(e,t,n=!1){let[r,i]=(0,D.useState)(!0),a=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=new pc(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,D.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,D.useCallback)(()=>a.current?.poke(),[]),s=(0,D.useCallback)(()=>a.current?.hide(),[]),c=(0,D.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var hc=3e4,gc=class{constructor(e,t=hc){this.onChange=e,this.ms=t,this.picking=!1,this.over=!1,this.timer=null}get shown(){return this.picking&&!this.over}set(e){e!==this.picking&&(this.picking=e,this.over=!1,this.stop(),e&&(this.timer=setTimeout(()=>{this.timer=null,this.over=!0,this.onChange()},this.ms)))}stop(){this.timer&&clearTimeout(this.timer),this.timer=null}reset(){this.stop(),this.picking=!1,this.over=!1}};function _c(e){let[,t]=(0,D.useState)(0),[n]=(0,D.useState)(()=>new gc(()=>t(e=>e+1)));return(0,D.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,D.useEffect)(()=>()=>n.reset(),[n]),n.shown}var vc=()=>Xa(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function yc(e,t){if(t.kind===`axis`)return t.which===`lx`?e(`rp_pad_step_lx`,void 0,`Push the left stick right`):t.which===`ly`?e(`rp_pad_step_ly`,void 0,`Push the left stick down`):t.which===`rx`?e(`rp_pad_step_rx`,void 0,`Push the right stick right`):e(`rp_pad_step_ry`,void 0,`Push the right stick down`);if(t.kind===`button`){if(t.bit===R.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===R.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===R.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===R.TRIANGLE)return e(`join_check_top`,void 0,`Press the top face button (△)`)}return e(`rp_pad_press`,{name:t.name},`Press ${t.name}`)}function bc(e,t){let n=(0,D.useRef)(t);(0,D.useEffect)(()=>{n.current=t}),(0,D.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(vc().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var xc=[[R.CROSS,`✕`],[R.CIRCLE,`○`],[R.SQUARE,`□`],[R.TRIANGLE,`△`],[R.UP,`↑`],[R.DOWN,`↓`],[R.LEFT,`←`],[R.RIGHT,`→`],[R.L1,`L1`],[R.R1,`R1`],[R.L3,`L3`],[R.R3,`R3`],[R.SHARE,`Create`],[R.OPTIONS,`Options`],[R.PS,`PS`],[R.TOUCHPAD,`Touchpad`]];function Sc({pad:e}){let t=e=>`flex h-8 min-w-8 items-center justify-center rounded-md px-1.5 text-xs font-medium ${e?`bg-white text-black`:`bg-white/10 text-white/70`}`,n=(e,t,n)=>(0,z.jsxs)(`span`,{className:`relative flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-[10px] text-white/50`,children:[n,(0,z.jsx)(`span`,{className:`absolute h-3 w-3 rounded-full bg-white`,style:{left:`calc(50% + ${e/32767*18}px - 6px)`,top:`calc(50% + ${t/32767*18}px - 6px)`}})]});return(0,z.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[xc.map(([n,r])=>(0,z.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,z.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,z.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,z.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function Cc({onClose:e}){let t=Ie(),[n,r]=(0,D.useState)(()=>vc().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,D.useState)(()=>vc()[0]?.index??null),[o,s]=(0,D.useState)(ja),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(yo),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useRef)(null);(0,D.useEffect)(()=>(ac(!0),()=>ac(!1)),[]),(0,D.useEffect)(()=>{(v.current?.querySelector(`[data-testid="join-pad-learn-start"]`)??v.current?.querySelector(`[data-testid="join-pad-check-close"]`))?.focus({preventScroll:!0})},[]),(0,D.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||v.current?.querySelector(`button:not([disabled])`)?.focus({preventScroll:!0})},[c,u]),(0,D.useEffect)(()=>{let e=()=>{let e=vc();r(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n].id&&t.index===e[n].index)?t:e.map(e=>({index:e.index,id:e.id}))),a(t=>t!==null&&e.some(e=>e.index===t)?t:e[0]?.index??null)},t=window.setInterval(e,500);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(t),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),bc(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(Eo(e))&&y(c,e);return}let t=Ga([e],So);s(e=>e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry?e:t)});let y=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(bo(r,e.profile(n?wo(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},b=()=>{h(null),d(0),l(new Fo(No))},x=g,S=x?Co(x):null,ee=!!(x&&f[x.id]);return(0,z.jsx)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":t(`join_check_title`,void 0,`Check your controller`),className:`absolute inset-0 z-40 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm`,"data-testid":`join-pad-check`,onPointerDown:e=>e.stopPropagation(),children:(0,z.jsxs)(`div`,{className:`w-[min(26rem,100%)] space-y-3 rounded-2xl border border-white/10 bg-neutral-900/95 p-4 text-sm text-white shadow-2xl`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(me,{size:16,className:`text-white/70`}),(0,z.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t(`join_done`,void 0,`Done`),className:`flex h-8 w-8 items-center justify-center rounded-full bg-white/10 hover:bg-white/20`,"data-testid":`join-pad-check-close`,children:(0,z.jsx)(De,{size:15})})]}),x?(0,z.jsxs)(z.Fragment,{children:[n.length>1&&(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,z.jsx)(`button`,{type:`button`,disabled:!!c,onClick:()=>a(e.index),className:`rounded-full px-2.5 py-1 text-xs ${e.index===i?`bg-white text-black`:`bg-white/10`}`,children:to(e.id)},`${e.index}-${e.id}`))}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:to(x.id)}),(0,z.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":S??``,children:S===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):S===`guess`?t(`join_check_unknown`,void 0,`This controller isn't on our list, so its buttons may be mixed up. Setting it up takes a few seconds.`):t(`rp_pad_standard`,void 0,`Recognized`)}),io(x)&&(0,z.jsx)(ps,{id:x.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`rp_pad_progress`,{n:u+1,total:c.steps.length},`${u+1} of ${c.steps.length}`)}),(0,z.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?yc(t,c.current):``}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),y(c,x)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-learn-skip`,children:t(`rp_pad_skip`,void 0,`Skip`)}),u>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.back(),d(c.step)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,children:t(`rp_pad_back`,void 0,`Back`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>l(null),className:`rounded-full px-3 py-1.5 text-xs text-white/70 hover:bg-white/10`,children:t(`rp_pad_cancel`,void 0,`Cancel`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`join_check_try`,void 0,`Press buttons and move the sticks: what you press lights up.`)}),(0,z.jsx)(Sc,{pad:o}),m&&(0,z.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:b,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:ee?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),ee&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{p(bo(x.id,null)),h(null)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-reset`,children:t(`rp_pad_reset`,void 0,`Reset`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-check-done`,children:t(`join_done`,void 0,`Done`)})]})]})]}):(0,z.jsx)(`p`,{className:`text-white/70`,children:t(`rp_pads_none`,void 0,`No controller seen yet. Connect one and press any button on it.`)})]})})}function wc(e,t){let[n,r]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(!e||!t)return;let n=!0;return Be(e,Le).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function Tc({href:e}){let t=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,z.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function Ec(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var Dc=`ps5upload.join.guided`,Oc=1;function kc(e){return e.player!==Oc&&(!e.guided||e.movedOff)&&!e.reconnecting}function Ac(e,t){switch(t){case`lan`:return e(`join_path_lan`,void 0,`Home network`);case`tailscale`:return e(`join_path_tailscale`,void 0,`Tailscale`);default:return e(`join_path_internet`,void 0,`Internet`)}}function jc(e,t){return e(`join_seat_taken`,{host:t},`${t} needed their controller back and no other controller was free on the PS5, so you're out of the game. Ask ${t} to let you in again.`)}function Mc(e,t,n,r=!1){if(t.kind===`refused`)switch(t.why){case`key`:return e(`join_refused_key`,{host:n},`This invite has expired. Ask ${n} for a new link.`);case`expired`:return e(`join_refused_expired`,{host:n},`Your place in the game was lost. Ask ${n} to let you in again.`);case`full`:return e(`join_refused_full`,void 0,`The game is full: four players already.`);case`denied`:return e(`join_refused_denied`,{host:n},`${n} didn't let you in this time.`);case`no_answer`:return e(`join_refused_no_answer`,{host:n},`${n} didn't answer in time. Tell ${n}, then try again.`);case`closed`:return e(`join_refused_closed`,{host:n},`${n} isn't hosting Play Together right now.`);case`old_helper`:return e(`join_refused_old_helper`,{host:n},`${n}'s PS5 needs an updated helper for Play Together.`);case`not_playing`:return e(`join_refused_not_playing`,{host:n},`${n} isn't playing right now. Ask ${n} to start Play first.`);case`unreachable`:return e(`join_refused_unreachable`,{host:n},`${n}'s computer couldn't reach their PS5. Try again in a moment.`);case`slow_down`:return e(`join_refused_slow_down`,void 0,`Too many wrong codes. Wait a minute, then try again.`);case`address`:return e(`join_refused_address`,{host:n},`This link's address is outside your home network, so the app will not use it. Ask ${n} for a link with their computer's IP address.`);case`seat_taken`:return jc(e,n);default:return e(`join_refused_other`,{host:n},`${n} didn't let you in.`)}if(t.kind===`ended`)switch(t.why){case`kicked`:return e(`join_ended_kicked`,{host:n},`${n} took you out of the game.`);case`closed`:return e(`join_ended_closed`,{host:n},`${n} closed Play Together.`);case`host_stopped`:return e(`join_ended_host_stopped`,void 0,`The host stopped playing.`);case`replaced`:return e(`join_ended_replaced`,void 0,`This game was opened in another tab or on another device, so it stopped here.`);case`pad_lost`:return e(`join_ended_pad_lost`,{host:n},`The PS5 lost your controller, so you're out of the game. Ask ${n} to let you in again.`);case`gave_up`:return e(`join_ended_gave_up`,{host:n},`The connection to ${n} didn't come back in time.`);case`lost`:return r?e(`join_net_lost`,{host:n},`The connection to ${n} dropped. Check your internet connection, then ask again.`):e(`join_ended_lost`,{host:n},`Couldn't reach ${n}. Check that you're on the same network.`);case`left`:return e(`join_ended_left`,void 0,`You left the game.`);case`seat_taken`:return jc(e,n);case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`join_net_no_room`,{host:n},`This invite isn't open any more. Ask ${n} for a new link.`);case`net_full`:return e(`join_net_full`,{host:n},`${n}'s game has no room for another friend right now. Try again in a moment.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:return e(`join_net_offer`,{host:n},`${n}'s computer couldn't connect to this browser. Try another browser.`);case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`)}return``}function Nc(e){let[t,n]=(0,D.useState)(()=>Date.now());return(0,D.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function Pc(){let[e,t]=(0,D.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,D.useEffect)(()=>{let e=()=>{let e=Xa(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?sc():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?Co(e):null,s=!!e&&io(e);t(e=>e.ready===n&&e.pressed===i&&e.id===a&&e.kind===o&&e.weak8BitDo===s?e:{ready:n,pressed:i,id:a,kind:o,weak8BitDo:s})};e();let n=window.setInterval(e,120);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(n),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),e}function Fc(e){return!!e?.closest?.(`[data-testid="rp-touch"]`)}var Ic=14,Lc=()=>typeof window<`u`&&!rs()&&!!window.matchMedia?.(`(pointer: coarse)`).matches;function Rc(e,t,n){return!e||e===t||e.closest?.(`[data-join-game]`)?`game`:n?.contains(e)?`controls`:`page`}function zc(e){return e.checking?`close-check`:e.guide?`close-guide`:e.where===`game`?`show-controls`:e.full?`leave-full`:null}var Bc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function Vc({text:e,body:t,onCancel:n}){let r=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,z.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,z.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,z.jsx)(Se,{size:26})})]}),(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!0,className:`rounded-full bg-white/15 px-4 py-2 text-sm hover:bg-white/25`,"data-testid":`join-cancel`,children:r(`join_cancel`,void 0,`Cancel`)})]})}function Hc({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Ie(),c=lc(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,D.useRef)(null),p=(0,D.useRef)(null),m=(0,D.useRef)(null),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(()=>Lt(Dc)===`1`),[y,b]=(0,D.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),x=Pc(),[S,ee]=(0,D.useState)(!1),C=l.kind===`reconnecting`,w=Nc(C),T=l.kind===`joined`||C,E=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[ne,re]=(0,D.useState)(!1),ie=(0,D.useRef)(te);(0,D.useEffect)(()=>{ie.current===Oc&&te>Oc&&re(!0),te&&(ie.current=te)},[te]);let[ae,oe]=(0,D.useState)(!1),[se,ce]=(0,D.useState)(!1),le=T&&(h||!t),de=Lc(),fe=_c(E),k=mc(le,C||fe&&!de||ae||se,de),{poke:he}=k,_e=(0,D.useRef)(null),ve=()=>{_e.current&&clearTimeout(_e.current.timer),_e.current=null};(0,D.useEffect)(()=>ve,[]);let[ye,A]=(0,D.useState)(!1),xe=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(!le||!de||k.shown||!_||xe.current)return;xe.current=!0,A(!0);let e=setTimeout(()=>A(!1),6e3);return()=>clearTimeout(e)},[le,de,k.shown,_]),(0,D.useEffect)(()=>{if(!T)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[T,e]),(0,D.useEffect)(()=>{if(!T||c.sound)return;let t=()=>e.startSound(),n=[`pointerup`,`touchend`,`click`,`keydown`];for(let e of n)window.addEventListener(e,t,!0);return()=>{for(let e of n)window.removeEventListener(e,t,!0)}},[T,c.sound,e]),(0,D.useEffect)(()=>{let e=()=>b(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,D.useEffect)(()=>{if(h)return()=>void i?.(!1)},[h,i]);let Ce=(0,D.useRef)(h);(0,D.useEffect)(()=>{Ce.current=h},[h]),(0,D.useEffect)(()=>{if(!t||!T||!Lc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!Ce.current&&(g(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,T,i]),(0,D.useEffect)(()=>{t&&T&&rs()&&!Ce.current&&(g(!0),i?.(!0))},[t,T,i]),(0,D.useEffect)(()=>{if(!T)return;let e=e=>{if(e.key!==`Escape`)return;if(S)return void Le.current();if(he(),h)return g(!1);let t=Rc(document.activeElement,document.body,p.current);t===`game`?Le.current():t===`controls`&&m.current?.focus({preventScroll:!0})};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[T,h,he,S]),(0,D.useEffect)(()=>{if(!h||!Lc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,g(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[h]),(0,D.useEffect)(()=>{if(!h||typeof document>`u`)return;let e=()=>{document.fullscreenElement||Lc()||g(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[h]);let Te=rs(),Ee=T&&kc({player:te,guided:_,movedOff:ne,reconnecting:C})&&!u?.playsAs,De=async e=>{g(e),await i?.(e)},Oe=()=>m.current?.focus({preventScroll:!0}),ke=()=>{It(Dc,`1`),v(!0),re(!1)},Ae=()=>{he();let e=C?`[data-testid="join-reconnecting-leave"]`:`[data-testid="join-bar"] button`;p.current?.querySelector(e)?.focus({preventScroll:!0})},je=()=>{let e=p.current?.querySelector(`[data-testid="join-check-open"]`);e?e.focus({preventScroll:!0}):Oe(),ee(!1)},Me=()=>Rc(document.activeElement,document.body,p.current),[Ne,Pe]=(0,D.useState)(`game`);(0,D.useEffect)(()=>{if(!T)return;let e=()=>Pe(Me()),t=()=>window.setTimeout(e,0);return e(),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t)}},[T]);let Fe=()=>{switch(T?zc({checking:S,guide:Ee,where:Me(),full:h}):null){case`close-check`:return je(),!0;case`close-guide`:return ke(),Oe(),!0;case`show-controls`:return Ae(),!0;case`leave-full`:return De(!1),!0;default:return!1}},Le=(0,D.useRef)(Fe);(0,D.useEffect)(()=>{Le.current=Fe});let Re=t&&!de&&T&&zc({checking:S,guide:Ee,where:Ne,full:h})!==null;(0,D.useEffect)(()=>{if(Re)return Xo(()=>void Le.current())},[Re]);let ze=!t&&T&&!de;(0,D.useEffect)(()=>{if(!ze)return;let e=window.location.href;window.history.pushState(window.history.state,``);let t=!0,n=()=>{if(t=!1,!Le.current())return window.history.back();window.history.pushState(window.history.state,``),t=!0};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),t&&window.location.href===e&&window.history.back()}},[ze]);let Be=l.kind===`joined`;(0,D.useEffect)(()=>{if(!Be)return;let e=document.activeElement;if(e&&e!==document.body)return;let t=Te&&Ee?p.current?.querySelector(`[data-testid="join-guide-ok"]`):null;t?t.focus({preventScroll:!0}):Oe()},[Be]),(0,D.useEffect)(()=>{x.pressed&&T&&!S&&Me()===`controls`&&Oe()},[x.pressed]);let Ve=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,z.jsxs)(`div`,{className:t?`rounded-[var(--radius-card)] bg-neutral-900 text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black text-white`,"data-join-ui":``,children:[l.kind===`connecting`&&o&&a&&(0,z.jsx)(Tc,{href:a}),(0,z.jsx)(Vc,{text:l.kind===`connecting`?s(`join_connecting`,{host:d},`Connecting to ${d}…`):s(`join_waiting`,{host:d},`Waiting for ${d} to let you in`),body:l.kind===`asking`?s(`join_waiting_body`,{host:d},`${d} sees your name on their screen and taps Allow.`):void 0,onCancel:Ve})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,z.jsxs)(`div`,{className:t?`flex flex-col items-center gap-4 rounded-[var(--radius-card)] bg-neutral-900 px-6 py-10 text-center text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black px-6 text-center text-white`,"data-testid":`join-ended`,"data-why":l.why,"data-join-ui":``,children:[(0,z.jsx)(Se,{size:28,className:`text-white/60`}),(0,z.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:Mc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,z.jsx)(Tc,{href:a}),(0,z.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,z.jsx)(`button`,{type:`button`,onClick:r,autoFocus:!0,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`join-again`,children:l.kind===`refused`&&l.why===`not_playing`?s(`join_retry`,void 0,`Try again`):s(`join_again`,void 0,`Ask to join again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!i,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let He=l.player,Ue=c.light??at(He),We=c.rttMs??u?.rttMs??null,Ge=it(We),Ke=Lc(),qe=T&&!C&&!x.ready&&Ke&&(!t||h),Je=kc({player:He,guided:_,movedOff:ne,reconnecting:C}),Ye=He===Oc,Xe=u?.playsAs??null,Ze=C?(l.deadline-w)/1e3:0,Qe=()=>De(!h),$e=t&&!h&&Ke&&T,et=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`span`,{className:`flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 font-medium`,"data-testid":`join-player`,children:[(0,z.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`}}),t&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:He},`You are Player ${He}`)]}),We!=null&&(0,z.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:Bc[Ge]},"data-testid":`join-delay`,"data-tone":Ge,"data-path":c.path??void 0,children:[c.path&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[Ac(s,c.path),` · `]}),Math.round(We),` ms`]}),Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-stream`,children:s(`join_seat_stream`,{host:d},`You're playing as ${d}'s PS5 user. No need to pick one.`)}),Xe&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-plays-as`,children:s(`join_plays_as`,{profile:Xe},`You're playing as ${Xe}. No need to pick one.`)}),E&&!Ye&&u?.seatNote&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-note`,children:s(`join_seat_tv_asks`,{host:d},`${d} chose a profile for you, but it couldn't be used. The TV will ask who you are.`)}),E&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-picking`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)})]}),tt=(0,z.jsxs)(z.Fragment,{children:[le&&de&&k.shown&&!C&&(0,z.jsxs)(`button`,{type:`button`,onClick:k.hide,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 font-medium`,"data-testid":`join-hide-controls`,children:[(0,z.jsx)(pe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex items-center gap-1 rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-sound`,children:[(0,z.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-mute`,children:[c.muted?(0,z.jsx)(M,{size:13}):(0,z.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,z.jsxs)(`span`,{className:`flex items-center gap-1 rounded-full bg-black/60 px-2.5 py-1 text-white/80`,"data-testid":`join-no-sound`,children:[(0,z.jsx)(M,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>void Qe(),"aria-label":h?s(`join_exit_fullscreen`,void 0,`Leave full screen`):s(`pad_fill`,void 0,`Full screen`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-full`,children:h?(0,z.jsx)(be,{size:13}):(0,z.jsx)(O,{size:13})}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),"aria-label":s(`join_check_title`,void 0,`Check your controller`),title:s(`join_check_title`,void 0,`Check your controller`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-check-open`,children:(0,z.jsx)(me,{size:13})}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex items-center gap-1 rounded-full bg-[var(--color-danger,#dc2626)] px-3 py-1 font-medium`,"data-testid":`join-leave`,children:[(0,z.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),nt=k.shown?`opacity-100`:`pointer-events-none opacity-0`,rt={"data-testid":`join-bar`,"data-shown":k.shown?`1`:`0`,onFocus:e=>{(Te||e.target.matches?.(`:focus-visible`))&&ce(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||ce(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&oe(!0)},onPointerLeave:()=>oe(!1)},ot=h||!t?`fixed inset-0 z-[200] bg-black`:`relative mx-auto aspect-video w-full max-w-[max(20rem,calc((100dvh_-_22rem)*16/9))] overflow-hidden rounded-[var(--radius-card)] bg-black shadow-[var(--shadow-2)]`,st=t&&h;return(0,z.jsxs)(`div`,{className:`space-y-2`,ref:p,"data-join-ui":``,children:[(0,z.jsxs)(`div`,{className:`${ot} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},role:st?`dialog`:void 0,"aria-modal":st?!0:void 0,"aria-label":st?s(`pad_fill`,void 0,`Full screen`):void 0,onPointerMove:e=>{if(e.pointerType===`mouse`)return he();let t=_e.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>Ic&&ve()},onPointerDown:e=>{if(Fc(e.target))return;if(e.pointerType===`mouse`||!de)return he();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;ve();let{pointerId:t,clientX:n,clientY:r}=e;_e.current={id:t,x:n,y:r,timer:setTimeout(()=>{_e.current=null,navigator.vibrate?.(15),k.toggle()},450)}},onPointerUp:ve,onPointerCancel:ve,onPointerLeave:ve,"data-testid":`join-stage-view`,children:[(0,z.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),le&&!k.shown&&!C&&We!=null&&(0,z.jsxs)(`span`,{className:`pointer-events-none absolute z-10 rounded-full bg-black/40 px-1.5 py-0.5 text-[10px] leading-none tabular-nums`,style:{color:Bc[Ge],top:`max(0.5rem, env(safe-area-inset-top))`,right:`max(0.5rem, env(safe-area-inset-right))`},"data-testid":`join-delay-corner`,children:[Math.round(We),` ms`]}),qe?(0,z.jsxs)(`div`,{className:`absolute left-1/2 top-1/2 z-20 flex w-max max-w-[min(24rem,calc(100%-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-2 rounded-2xl bg-black/70 p-3 text-xs backdrop-blur-sm transition-opacity duration-300 ${nt}`,...rt,children:[(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:et}),(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:tt})]}):$e?null:(0,z.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex flex-wrap items-center gap-2 bg-gradient-to-b from-black/70 to-transparent px-3 pb-5 pt-[max(8px,env(safe-area-inset-top))] text-xs transition-opacity duration-300 ${nt}`,...rt,children:[et,(0,z.jsx)(`span`,{className:`flex-1`}),tt]}),!k.shown&&!qe&&(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},"aria-label":s(`join_show_controls`,void 0,`Show controls`),className:`absolute left-1/2 top-[max(6px,env(safe-area-inset-top))] z-20 flex h-7 w-11 -translate-x-1/2 items-center justify-center rounded-full bg-black/40 text-white/70 opacity-60 hover:opacity-100 focus-visible:opacity-100`,"data-testid":`join-show-controls`,children:(0,z.jsx)(ue,{size:16,"aria-hidden":!0})}),ye&&!k.shown&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-[max(10px,env(safe-area-inset-top))] z-20 -translate-x-1/2 rounded-full bg-black/60 px-3 py-1 text-xs text-white/85`,"data-testid":`join-hold-hint`,children:s(`join_hold_hint`,void 0,`Press and hold the picture to show the buttons`)}),c.problem&&(0,z.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`join-problem`,children:c.problem===`no_hevc`?s(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):s(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),S&&(0,z.jsx)(Cc,{onClose:je}),qe&&(0,z.jsx)(ks,{stream:e,layout:`overlay`,onMenu:()=>k.shown?k.hide():he()}),!qe&&!C&&(0,z.jsxs)(`div`,{className:`absolute bottom-3 left-3 z-20 flex items-center gap-2 rounded-2xl bg-black/70 px-3 py-1.5 text-xs transition-opacity duration-300 ${nt}`,"data-testid":`join-pad`,children:[(0,z.jsx)(me,{size:14,style:{color:x.pressed?`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`:void 0}}),x.ready?(0,z.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),x.weak8BitDo&&x.id&&(0,z.jsx)(ps,{id:x.id,className:`text-amber-200/90`}),x.kind===`guess`&&no()&&(0,z.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2 text-white/75`,"data-testid":`join-pad-unknown`,children:[s(`join_check_unknown_short`,void 0,`Not on our list: buttons may be mixed up.`),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),className:`rounded-full bg-white px-2.5 py-0.5 font-medium text-black`,"data-testid":`join-pad-unknown-check`,children:s(`join_check_title`,void 0,`Check your controller`)})]})]}):Ke&&t&&!h?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,z.jsxs)(`span`,{className:`flex flex-col`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,z.jsx)(`span`,{className:`text-white/60`,"data-testid":`join-pad-keys`,children:s(`join_pad_keys`,void 0,`Or use the keyboard: WASD move, arrows D-pad, Enter ✕, Backspace ○, Q □, E △, Tab Options.`)})]}),Te&&(0,z.jsx)(`span`,{className:`max-w-[14rem] border-l border-white/20 pl-2 text-white/70`,"data-testid":`join-tv-back`,children:s(`join_tv_back_hint`,void 0,`Press Back on the remote for the buttons.`)})]}),u?.blockSystem&&u.state===`playing`&&!qe&&(0,z.jsx)(`p`,{className:`absolute bottom-3 right-3 z-20 rounded-full bg-black/60 px-3 py-1 text-[11px] text-white/70 transition-opacity duration-300 ${nt}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),fe&&!Ye&&de&&!k.shown&&!C&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-2 z-20 -translate-x-1/2 whitespace-nowrap rounded-full bg-white/90 px-2.5 py-1 text-xs font-medium text-black`,"data-testid":`join-picking-note`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)}),Je&&!Xe&&(0,z.jsxs)(`div`,{className:`absolute bottom-14 left-1/2 z-30 w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-2xl border border-white/10 bg-neutral-900/90 p-4 text-sm shadow-2xl backdrop-blur-md`,"data-testid":`join-guide`,children:[(0,z.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/75`,children:s(`join_guide_body`,void 0,`On your controller, press PS once. The TV asks "Who's using this controller?". Pick Quick Play or your own user. The host doesn't need to do anything.`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/60`,children:s(`join_guide_menus`,void 0,`On the PS5's home screen only the host controls the menus; your controller plays inside games.`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>{ke(),Oe()},className:`mt-3 rounded-full bg-white px-3 py-1 text-xs font-medium text-black`,"data-testid":`join-guide-ok`,children:s(`join_guide_ok`,void 0,`Got it`)})]}),C&&(0,z.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-black/70 px-6 text-center`,"data-testid":`join-reconnecting`,children:[(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`absolute right-3 top-[max(10px,env(safe-area-inset-top))] flex items-center gap-1 rounded-full bg-white/15 px-3 py-1.5 text-sm font-medium hover:bg-white/25`,"data-testid":`join-reconnecting-leave`,children:[(0,z.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,z.jsx)(`span`,{className:`h-7 w-7 animate-spin rounded-full border-2 border-white/30 border-t-white`,"aria-hidden":!0}),l.hostStopped?(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:Ec(Ze)},`The host stopped playing — waiting for them to start again (${Ec(Ze)})`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:Ec(Ze)},`Your place is kept for ${Ec(Ze)}.`)})]})]}),!t&&T&&y&&Ke&&(0,z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,z.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,z.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})}),(0,z.jsx)(`div`,{ref:m,tabIndex:0,"data-own-arrows":``,"data-join-game":``,"aria-label":s(`join_game_label`,{host:d},`${d}'s game`),className:`pointer-events-none absolute inset-0 outline-none`,"data-testid":`join-game`})]}),$e&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-[var(--radius-card)] bg-neutral-900 px-3 py-2 text-xs text-white`,"data-testid":`join-bar`,"data-shown":`1`,"data-below":`1`,children:[(0,z.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:et}),(0,z.jsxs)(`button`,{type:`button`,onClick:()=>void Qe(),className:`flex h-11 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full bg-white/15 px-3 text-sm font-medium hover:bg-white/25`,"data-testid":`join-fullscreen-below`,children:[(0,z.jsx)(O,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,z.jsx)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,"aria-label":c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`),className:`flex h-11 w-11 items-center justify-center rounded-full bg-white/15 hover:bg-white/25`,children:c.muted?(0,z.jsx)(M,{size:16}):(0,z.jsx)(we,{size:16})}):c.sound?null:(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-white px-3 text-sm font-medium text-black`,children:[(0,z.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-[var(--color-danger,#dc2626)] px-4 text-sm font-medium`,"data-testid":`join-leave-below`,children:[(0,z.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var Uc=`ps5upload.join.name`;function Wc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function Gc(e){return e.trim().slice(0,32)}function Kc(e=``){return Gc(Lt(`ps5upload.join.name`)??``)||e}function qc(e){let t=Gc(e);return t&&It(Uc,t),t}function Jc(e){try{return!!sessionStorage.getItem(Ro(e))}catch{return!1}}async function Yc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Xc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Ie(),c=wc(r&&o!==!1?e:null,i),[l,u]=(0,D.useState)(()=>Kc(Wc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(0),h=(0,D.useCallback)(e=>{if(!e)return;let t=typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,n=e.querySelector(`[data-testid="join-name"]`)?.value.trim()?`join-go`:t?null:`join-name`;n&&e.querySelector(`[data-testid="${n}"]`)?.focus({preventScroll:!0})},[]),g=i=>{let s=qc(i);if(!s)return;let c=new cc({url:e,invite:t,name:s,host:n,transport:r,path:a,...o===void 0?{}:{internet:o}});f(c),m(e=>e+1),c.start()};if((0,D.useEffect)(()=>{!d&&Jc(t)&&l.trim()&&g(l)},[]),(0,D.useEffect)(()=>d?dc(d):void 0,[d]),(0,D.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,z.jsx)(Hc,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),g(l)},onFullscreen:Yc},p);let _=n??s(`join_host_fallback`,void 0,`your friend`),v=(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,"data-join-ui":``,children:(0,z.jsxs)(`form`,{ref:h,className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),g(l)},children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,z.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,z.jsx)(Se,{size:20})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:_},`Play on ${_}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,z.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,z.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,z.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),maxLength:32,autoComplete:`nickname`,className:`block w-full rounded-lg border border-white/15 bg-black px-3 py-2 text-base outline-none focus:border-white/50`,"data-testid":`join-name`}),(0,z.jsx)(`span`,{className:`block text-xs text-white/50`,children:s(`join_name_hint`,void 0,`Your friend sees this when you ask to join.`)})]}),(0,z.jsx)(`button`,{type:`submit`,disabled:!l.trim(),className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black disabled:opacity-40`,"data-testid":`join-go`,children:s(`join_button`,void 0,`Join`)}),c&&i&&(0,z.jsx)(Tc,{href:i})]})});return t?(0,z.jsx)(Wo,{appLink:rt(location.href),children:v}):v}function Zc(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Qc(e,t){let n=Zc(e),r=Zc(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function $c(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Zc(t);return n===0?`lan`:n===1?`tailscale`:null}function el(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Qc(a(i.localCandidateId),a(i.remoteCandidateId))}function tl(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function nl(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function rl(e,t){let n=nl(e);return n!==null&&n===t.toUpperCase()}var il=16777216;function al(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function sl(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var cl=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],ll=1500,ul=2e4;function dl(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var fl=null;function pl(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function ml(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||fl)return;let r=tl(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};fl=a;let o=()=>{fl===a&&(fl=null,a.timer&&clearTimeout(a.timer),pl(i))};i.onopen=()=>i.send(JSON.stringify({v:1,t:`join`,room:e.room})),i.onmessage=e=>{if(typeof e.data==`string`)try{a.msgs.push(JSON.parse(e.data))}catch{}},i.onclose=o,i.onerror=()=>{},a.timer=setTimeout(o,t.keepMs??6e4)}function hl(e,t){let n=fl;return n?(fl=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(pl(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function gl(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new ol,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??tl(e.hub),a=t.signalUrl||t.lan?null:hl(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:cl}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=dl(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!rl(t.sdp,e.fp):nl(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(sl(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return el(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of al(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+ul,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},ll),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(He,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}var _l=3e3;function vl(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var U=e=>vl(e,`api/join/signal`);function yl(e){let t=[];if(e.rtc){let n=e.net??{room:``,key:``,fp:e.fp??``,hub:``};for(let[r,i]of[[`lan`,e.lan],[`tailscale`,e.ts]]){let a=i?U(i):null;if(!a)continue;let o=e.rtcMake(n,{signalUrl:e.reach(a),...e.net?{}:{lan:!0}});t.push({via:r,make:()=>new o(``),pinned:!!n.fp})}if(e.net){let n=e.rtcMake(e.net,{});t.push({via:`hub`,make:()=>new n(``),pinned:!0})}}let n=e.lan?vl(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var bl=new Map;function xl(e,t,n=300,r=_l){let i=e.some(e=>e===`lan`||e===`tailscale`),a=e.some(e=>e!==`socket`);return e.map(e=>e===t?0:e===`hub`&&i?n:e===`socket`&&a?r:0)}function Sl(e){let t=e.find(e=>e.via===`hub`),n=e.find(e=>(e.via===`lan`||e.via===`tailscale`)&&[`no_direct`,`net_full`,`offer`].includes(Ue(e.e)??``));return t&&(Ue(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function Cl(e,t){var n;let r=t.log??(()=>{}),i=t.headStartMs??300,a=t.socketAfterMs??3e3;class o{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.live=[],this.waiting=[],this.pinned=new Set,this.t0=0,this.closes=[],this.winner=null,setTimeout(()=>this.begin(),0)}get via(){return this.winner?.via??null}get media(){return this.winner?.s?.media??null}async netPath(){let e=this.winner?.s;return e?.netPath?e.netPath():null}begin(){if(this.readyState!==0)return;let n=e();if(!n.length){this.end({type:`close`,code:1006,reason:``,wasClean:!1});return}this.t0=Date.now();for(let e of n)e.pinned&&this.pinned.add(e.via);let r=xl(n.map(e=>e.via),bl.get(t.room)??null,i,a);n.forEach((e,t)=>{r[t]===0?this.launch(e.via,e.make):this.waiting.push({via:e.via,make:e.make,timer:setTimeout(()=>this.startWaiting(e.via),r[t])})})}startWaiting(e){let t=this.waiting.findIndex(t=>t.via===e);if(t<0)return;let[n]=this.waiting.splice(t,1);clearTimeout(n.timer),this.launch(n.via,n.make)}launch(e,t){if(this.readyState!==0)return;let n;try{n=t()}catch{this.tryClosed(e,{type:`close`,code:1006,reason:``,wasClean:!1});return}r(`path: trying ${e}`);let i={via:e,s:n};this.live.push(i),n.binaryType=this.binaryType,n.onopen=e=>this.won(i,e),n.onclose=t=>{this.live=this.live.filter(e=>e!==i),this.tryClosed(e,t)},n.onerror=()=>{},n.onmessage=null}tryClosed(e,t){if(this.readyState===0){if(r(`path: ${e} failed after ${Date.now()-this.t0} ms${t?.reason?` (${t.reason})`:``}`),this.closes.push({via:e,e:t}),this.pinned.has(e)&&Ue(t)===`mismatch`){for(let e of this.waiting.filter(e=>e.via===`socket`))clearTimeout(e.timer);this.waiting=this.waiting.filter(e=>e.via!==`socket`)}!this.live.length&&this.waiting.length?this.startWaiting(this.waiting[0].via):!this.live.length&&!this.waiting.length&&this.end(Sl(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,bl.set(t.room,e.via),r(`path: playing by ${e.via} after ${Date.now()-this.t0} ms`);for(let e of this.waiting.splice(0))clearTimeout(e.timer);for(let t of this.live.splice(0))if(t!==e){t.s.onopen=t.s.onclose=t.s.onmessage=t.s.onerror=null;try{t.s.close()}catch{}}let i=e.s;i.onmessage=e=>this.onmessage?.(e),i.onerror=e=>this.onerror?.(e),i.onclose=e=>{this.readyState!==3&&(this.readyState=3,this.onclose?.(e))},this.readyState=1,t.onWin?.(e.via),this.onopen?.(n)}send(e){if(this.readyState!==1||!this.winner)throw Error(`not open`);this.winner.s.send(e)}close(e,t){if(this.readyState===3)return;let n=this.readyState===1;this.readyState=3;for(let e of this.waiting.splice(0))clearTimeout(e.timer);let r=this.winner?[this.winner,...this.live]:this.live.splice(0);for(let n of r){n.s.onopen=n.s.onclose=n.s.onmessage=n.s.onerror=null;try{n.s.close(e,t)}catch{}}let i=this.onclose;if(i){let r={type:`close`,code:e??1e3,reason:t??``,wasClean:n};setTimeout(()=>i(r),0)}}end(e){if(this.readyState===3)return;this.readyState=3;let t=this.onclose,n=e??{type:`close`,code:1006,reason:``,wasClean:!1};t&&setTimeout(()=>t(n),0)}}return n=o,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,o}fs();var wl=new URLSearchParams(location.hash.slice(1)),Tl=wl.get(`n`)?.trim()||null,El=nt(location.hash);El&&ml(El);var Dl=(0,x.createRoot)(document.getElementById(`root`));if(El){let e=gl(El,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Re(location.hash,`join`);Dl.render((0,z.jsx)(Xc,{url:tl(El.hub),invite:El.key,host:Tl,transport:e,lanUrl:t?ze(t,{key:El.key}):null}))}else{let e=wl.get(`i`)||null,t=location.pathname.replace(/\/join\/?$/,``),n=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${t}/api/join/ws`,r=e=>console.info(`[join] ${e}`),i=`${location.origin}${t}/join`,a=typeof RTCPeerConnection>`u`?void 0:Cl(()=>yl({net:null,lan:i,ts:null,fp:tt(wl.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>gl(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});Dl.render((0,z.jsx)(Xc,{url:n,invite:e,host:Tl,path:$c(location.hostname),transport:a,internet:!1}))} diff --git a/engine/crates/ps5upload-engine/src/pad_page.html b/engine/crates/ps5upload-engine/src/pad_page.html index c35b03638..a59852b02 100644 --- a/engine/crates/ps5upload-engine/src/pad_page.html +++ b/engine/crates/ps5upload-engine/src/pad_page.html @@ -268,9 +268,9 @@ ã/¸Äyf"Ÿ5TàyÊ0îEê²Þ—€m6ëÞè6ðÏâ§9ž¬„k=}¼àt<ž‚¦Mdžç6"p_î3, oO3p"pw÷´/(1ñøs.íA/&ÏUÃ_X™ÍpÕ1hÌ80E’Qö„ ow÷!x.™AÜ"¢j+惡¦¶®ä“R–ow÷!xꔊpn…â#ðù z AÍp\Ž0N˜HJê´ªØ^U -I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index 820312b86..15707e037 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -4758,6 +4758,7 @@ "join_ended_replaced": "9229e45b IsX565t86JTr87Jb0nBwcJKFn4Q0zkPQ--1PM3nl2hIar19NVA9OOh-WN1F4", "join_exit_fullscreen": "b3b31f18 Y87a-8bZ-LebgFGNkXPLhcru0egfc6QGsS_nhuDy-UzCB9YXrdXNiMDxUoxS", "join_full_to_play": "9ffbb089 e0B1Cg6awUbMZvLodTNW7gu-cqE38_dNbH5KApGlH60C2AdQ9Oj9pIqQIOU7", + "join_game_label": "6f7698ba 40ro4hvp--ovxLH80bM_KPRr8wCYiarHl30doTPWfVgao1wXTBCWMjHbXYMO", "join_guide_body": "f7b89291 T6mkeSXVtk1v8yKoFcidzJKoxOYvEuPhTsaJQo-_8fFx1CRyXLBNoThqOnjr", "join_guide_menus": "ff8c5650 8TIxtgrwHz3POwae0ra8jxfORGxe0K5iVNLzdg4aUbzQhd6xviUH5md6aIbd", "join_guide_ok": "5ad3dbd1 GeV0jiD7oPz9uQ_S1m6wDjguZi92W1VlMOvJD-vn5N4s6tKzUv0m7g3jL3jL", @@ -4823,6 +4824,7 @@ "join_sound": "cc67901b xXPBWBHH0vmu3cqedBCP5EGYs3zF7urRz1VT2SRfj1qhpF0AC7H9Z3vfvBd1", "join_title": "1a92e990 qAT2LWXTzYac-e-J8UTR4vkIwHMsJCQuLVs8WknPblqlzbcDAOXuL8XqK3xR", "join_title_body": "04329d8d -Za5RfMvdVwBfsnJCPWLj4z-Yachf2cUMy0gucG74jfFLhYW17XFgGtId20Z", + "join_tv_back_hint": "8d52d5c5 Eb4MzXPSuxf6QofTRMNs1mVFlZnWvuzSnWrQC1wms7540twKNNBBHxbL8VPW", "join_waiting": "49b80efe Hh4oDjMeKT_vroXnFD8OYlA-A_Ewg8zXQ0gm0c1y2ORenWNT4hniKh49RnKE", "join_waiting_body": "c3e95aa3 KZKGX1qk8fbSWH3z7XnG4vJoHJhILaix11wh_Rx87wuSQbpsWVOvb1cwlqVT", "join_you_are": "f69497d1 rlT5awbjSaa9VaIDiVUFdvhr28Jks3V-NpqCAhx09mYk1Ogg29rSLSA6AA6A", @@ -8510,6 +8512,8 @@ "tray_show": "bb65146e ptXirKKDncl_xL7VvNgbxego30caEcKb9ja8QT3cl_zSz1Wm7C0ujATsR2Ki", "tray_unavailable": "e38256e0 b29kgV6505fUvfwn3cK4FkyKvuZsVb5zxAet2KND3R4W_prQZPju27gsyXm4", "try_again": "29cc3339 Bg_Ev08DPyIhd1VZPxs0Fp8PddoSSgEI69s7LrKyrtTNpDNDDZuDVnXduORE", + "tv_join_body": "952e82a4 ZdOkboPOiKxpAxF2_8uRyiNeMTY_ush3RT0RrB0Y8qEFF7fEInY1sguFB8tf", + "tv_join_button": "d0ae7bc1 YfChxRANGUobVwRF0aZwzIZyDv42yjLCl5lIVfivly2Gjlj4c3Z4LJuX5uya", "unmount": "2ad51f6d Y0T14SbawXM8uk3xs3lJ5ggbFYyC4AiA4tP4KIgXM8w6DXnb_vl051Brw5kv", "update_apk_busy": "db49c962 LqZF5fQPDjXH6pTgmuGKNzk_2ARM4TDQgv3x2ZYkDeV73AGIaTLn71ntlNVV", "update_apk_busy_confirm": "d94343f8 tOhXqI_je2IG6GgZ766Qfubm3beqLKjwl7yTWjLDJC1tDMNaIOoSsNn33n33", diff --git a/scripts/release/verify-android-apk.py b/scripts/release/verify-android-apk.py index 3b9651be2..f83f98cfe 100755 --- a/scripts/release/verify-android-apk.py +++ b/scripts/release/verify-android-apk.py @@ -68,7 +68,10 @@ def problems(tree: str) -> list[str]: features = feature_requirements(tree) if "android.hardware.touchscreen" not in features: out.append("touchscreen not declared optional: a TV refuses the app") - out += [f"requires {f}: a TV without it refuses the app" for f, required in sorted(features.items()) if required] + # #926: declared (optional), so a store lists the app for TVs as well as phones. + if "android.software.leanback" not in features: + out.append("android.software.leanback not declared: the app would not be offered on a TV") + out +=[f"requires {f}: a TV without it refuses the app" for f, required in sorted(features.items()) if required] return out @@ -119,6 +122,9 @@ def self_test() -> None: "E: uses-feature (line=3)", f'{a}name(0x01010003)="android.hardware.touchscreen" (Raw: "android.hardware.touchscreen")', f"{a}required(0x0101028e)=false", + "E: uses-feature (line=5)", + f'{a}name(0x01010003)="android.software.leanback" (Raw: "android.software.leanback")', + f"{a}required(0x0101028e)=false", "E: uses-feature (line=4)", f'{a}name(0x01010003)="android.hardware.camera" (Raw: "android.hardware.camera")', f"{a}required(0x0101028e)=false", @@ -135,6 +141,7 @@ def self_test() -> None: ("LEANBACK_LAUNCHER", "no LEANBACK_LAUNCHER"), ("banner(", "no banner"), ("hardware.touchscreen", "touchscreen not declared optional"), + ("software.leanback", "android.software.leanback not declared"), ): tree = "\n".join(l for l in lines if needle not in l) assert any(p.startswith(expected) for p in problems(tree)), (needle, problems(tree)) diff --git a/site/join/index.html b/site/join/index.html index b260f68a4..b5d815491 100644 --- a/site/join/index.html +++ b/site/join/index.html @@ -8,15 +8,15 @@ PS5Upload · Play Together - +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var E={a:v};this.setModule=t=>{e.setModule(bi,t)},this.getModule=()=>e.getModule(bi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,E)).then(e=>{let t=e.exports;y(t),a=t.g,o(),T(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=C,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var xi=o((()=>{}));function Si(e={}){Si.errors||Object.defineProperties(Si,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(Si.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var Ci=o((()=>{yi(),xi()})),wi,Ti=o((()=>{yi(),xi(),Ci(),wi=class extends hi{constructor(e){super(e,`opus-decoder`,Si,bi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ei=c({OpusDecoder:()=>Si,OpusDecoderWebWorker:()=>wi}),Di=o((()=>{Ci(),Ti(),yi(),_i(Si,`OpusDecoder`),_i(wi,`OpusDecoderWebWorker`)})),Oi=[8e3,12e3,16e3,24e3,48e3],ki=null;function Ai(){return ki??=Xn(()=>Promise.resolve().then(()=>(Di(),Ei)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw ki=null,e}),ki}function ji(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function Mi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ni=class{constructor(e,t=Ai){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!ji())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Oi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(Mi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Pi={makeDecoder:e=>new Ni(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Fi(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Ii(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var Li=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ri(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Li)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function zi(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Bi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Vi(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function F(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Hi=(e,t,n,...r)=>Vi(e,F([t,1],[n,3]),...r),Ui=F([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Wi(e){let t=e.handler===`vide`,n=Vi(`ftyp`,new TextEncoder().encode(`isom`),F([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Vi(`moov`,Hi(`mvhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Ui,new Uint8Array(24),F([2,4])),Vi(`trak`,Hi(`tkhd`,0,3,F([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Ui,F([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Vi(`mdia`,Hi(`mdhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Hi(`hdlr`,0,0,F([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),F([0,1])),Vi(`minf`,t?Hi(`vmhd`,0,1,new Uint8Array(8)):Hi(`smhd`,0,0,F([0,4])),Vi(`dinf`,Hi(`dref`,0,0,F([1,4]),Hi(`url `,0,1))),Vi(`stbl`,Hi(`stsd`,0,0,F([1,4]),e.sampleEntry),Hi(`stts`,0,0,F([0,4])),Hi(`stsc`,0,0,F([0,4])),Hi(`stsz`,0,0,F([0,4],[0,4])),Hi(`stco`,0,0,F([0,4])))))),Vi(`mvex`,Hi(`trex`,0,0,F([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Gi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Hi(`trun`,0,1793,F([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Vi(`traf`,Hi(`tfhd`,0,131072,F([1,4])),Hi(`tfdt`,1,0,F([t,8])),o(e)),c=Hi(`mfhd`,0,0,F([e,4])),l=Vi(`moof`,c,s(0)).length,u=Vi(`moof`,c,s(l+8)),d=Vi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Ki(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=zi(e).filter(e=>!r.includes(Bi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var qi=e=>e.toString(16).padStart(2,`0`),Ji=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Yi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Xi(e){let t=zi(e),n=t.filter(e=>Bi(e,!1)===7),r=t.filter(e=>Bi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Yi([F([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(Ji),F([r.length,1]),...r.map(Ji)])}function Zi(e,t,n){let r=zi(e),i=e=>r.filter(n=>Bi(n,t)===e),a=(e,t)=>Vi(e,new Uint8Array(6),F([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),F([24,2],[65535,2]),t);if(!t){let t=i(7),r=Xi(e);return r?{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Vi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${qi(t[0][1])}${qi(t[0][2])}${qi(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Xr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Yi([F([128|e,1],[t.length,2]),...t.map(Ji)]),m=Vi(`hvcC`,F([1,1]),u,F([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Qi(e,t,n,r,i,a){return Gi(e,t,n,Ki(r,i),a)}function $i(e,t){let n=Vi(`dOps`,F([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Wi({handler:`soun`,timescale:48e3,sampleEntry:Vi(`Opus`,new Uint8Array(6),F([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function ea(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function ta(e,t,n){return Gi(e,t,ea(n),n,!0)}var na={watch:30,player:4},ra={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ia={seek:.8,speed:.25,target:.12};function aa(e,t,n){let r=typeof n==`string`?ra[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function oa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ha(e,t,n):new ka(e,t,n)}var sa=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function I(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var L=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ca(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function la(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ua=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+da;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},da=.02;async function fa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var pa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},ma=[`pointerup`,`touchend`,`click`,`keydown`],ha=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():la(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new pa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new sa(n),this.clock=new ua(t===`player`?.05:.08),typeof AudioDecoder>`u`&&va()&&(this.mseSound=new ya(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=ni(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!xa())return!1;let e=new ka(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,ga(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=ni(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await Aa(e):Ii(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Xi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=ri(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Fi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>na[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Ki(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];fa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return va()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new si((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ca(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new ya(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new si((e,n)=>this.play(e,n,t.sampleRate),Pi,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ca(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function ga(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function _a(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function va(){let e=typeof window>`u`?null:xa();return!!e&&(_a(e,`audio/mp4; codecs="Opus"`)||_a(e,`audio/mp4; codecs="opus"`))}var ya=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new L,this.el=n,this.track=new Ta(n,()=>this.fail(),e===`player`?ia:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=I(e);if(!t||!this.order.take(t.index))return;let n=ta(this.track.nextSeq(),this.time,t.packet);this.time+=ea(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=$i(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},ba=class{constructor(e,t,n=Pi){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ua(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,ga();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new si((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ca(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function xa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var Sa=10,Ca=3;function wa(e,t,n,r=Ca){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var Ta=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=xa();if(!n||!_a(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=Ea(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=aa(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>Sa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-Ca;if(this.keys){if(r=wa(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Ca&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function Ea(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Da=1e4,Oa=class{constructor(e=3,t=Da,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ka=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new pa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new sa(n),this.fails=new Oa(3,Da,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new ya(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new Ta(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!va())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ba(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?la(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=ni(e,this.hevc)??{w:1920,h:1080},r=Zi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Fi(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>na[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Qi(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function Aa(e){let t=ii(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ri(1920,1080)}var R={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},ja={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ma(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Na={ArrowUp:{button:R.UP},ArrowDown:{button:R.DOWN},ArrowLeft:{button:R.LEFT},ArrowRight:{button:R.RIGHT},Enter:{button:R.CROSS},Space:{button:R.CROSS},Backspace:{button:R.CIRCLE},Escape:{button:R.CIRCLE},KeyQ:{button:R.SQUARE},KeyE:{button:R.TRIANGLE},KeyZ:{button:R.L1},KeyC:{button:R.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:R.L3},KeyG:{button:R.R3},Tab:{button:R.OPTIONS},Backquote:{button:R.SHARE},KeyH:{button:R.PS},KeyT:{button:R.TOUCHPAD},KeyW:{stick:`ly`,dir:-1},KeyS:{stick:`ly`,dir:1},KeyA:{stick:`lx`,dir:-1},KeyD:{stick:`lx`,dir:1},KeyI:{stick:`ry`,dir:-1},KeyK:{stick:`ry`,dir:1},KeyJ:{stick:`rx`,dir:-1},KeyL:{stick:`rx`,dir:1}};R.UP,R.DOWN,R.LEFT,R.RIGHT,R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD;var Pa=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Fa(e,t=Na){let n={...ja};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Pa(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Ia=[R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,0,0,R.SHARE,R.OPTIONS,R.L3,R.R3,R.UP,R.DOWN,R.LEFT,R.RIGHT,R.PS,R.TOUCHPAD];function La(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Ra=[0,1,1,1,0,-1,-1,-1],za=[-1,-1,0,1,1,1,0,-1];function Ba(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=La(n);return e===null?0:(t.hat===`x`?Ra:za)[e]}return t.inv?-n:n}var Va={buttons:Ia.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function Ha(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=La(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ua(e){if(e.mapping===`standard`)return Va;let t=Wa.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Va;let r={...Va,buttons:[...Va.buttons,[R.UP,{h:n,at:0}],[R.RIGHT,{h:n,at:2}],[R.DOWN,{h:n,at:4}],[R.LEFT,{h:n,at:6}]]};return Wa.set(e.id,r),r}var Wa=new Map;function Ga(e,t=Ua){let n={...ja},r=e=>Math.abs(e)<.08?0:Pa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(Ba(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Ha(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Ha(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Ha(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Ka(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Pa(e.lx+t.lx),ly:Pa(e.ly+t.ly),rx:Pa(e.rx+t.rx),ry:Pa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function qa(e,t,n,r=()=>globalThis.navigator?.getGamepads?.()??[]){let i=e=>e?.vibrationActuator;for(let a of e.some(i)?e:r()){let e=i(a);e&&(t===0&&n===0?e.reset?.():e.playEffect?.(`dual-rumble`,{duration:1e3,strongMagnitude:t/255,weakMagnitude:n/255}))}}var Ja=new Map;function Ya(e,t){return{id:`${e.id} (app)`,index:3+e.slot,connected:!0,mapping:`standard`,timestamp:0,axes:e.axes,buttons:e.buttons.map(e=>({pressed:e>.5,touched:e>0,value:e})),vibrationActuator:t?.vibrationActuator??null,hapticActuators:t?.hapticActuators??[]}}function Xa(e){let t=e?.getGamepads?.()??[];return Ja.size===0||t.some(e=>!!e?.connected)?[...t]:[...Ja.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ya(e))}var Za=`b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,,,,,,,a0,a1(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,,,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b3,b0,b1,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1(b1,b0,b2,b3,,b7,a3,a4,,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,b4,b5,,b9,,,b12,b14,b15,b13,,,a0,a1,a5~,a2~(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,,,b7,b5,b4,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b3,b4,b6,b5,b7,b2,b8,,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b9,b10,b2,b8,,,h0.1,h0.4,h0.8,h0.2,b5,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b5,b7,b2,,b8,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b12,b13,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b14,b13,b15,b12,b10,b11,b8,b9,b0,b3,b1,b2,b4,b6,b7,b5,b16,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,a2,a5,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,,,b8,b9,,,b12,b13,b15,b14,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,b11,b12,b13,b14,b15,b16,b10,,a0,a1,a2,a3(b0,b1,b3,b2,,b6,a2,a5,,b7,,,b8,b9,b10,b11,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,,,b8,b9,,,b10,b11,b12,b13,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,,,b13,b8,b10,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,,,b12,b9,b11,,,,,,,,hx,hy(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,b14,b15,b16,b17,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,,,,b2,,b4,,b5,,,h0.1,h0.4,h0.8,h0.2,b6(b0,b1,b2,b3,b12,b4,b13,b5,b14,b6,b15,b7,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b1,b3,b0,b2,b13,b5,b12,b4,,b6,,,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b33,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b16,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b15,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,,,,,b8,,a0,a1,a3,a4(b1,b0,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,,h0.1,h0.4,h0.8,h0.2,b12,b13(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b12,b13,b14,b15,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b14,b13,b14,b13,,,a0,a1,a3,a4(b1,b0,b2,b3,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b2,b3,b1,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b10(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,+a2,+a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,a2,a5,b6,b7,,,h0.1,h0.4,h0.8,h0.2,b8(b1,b2,,,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b21,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,b13,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,a5,a4,,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b7,b6,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b7,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a5,a4,b9,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b22,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a3,b6,b7,b9,,b12,b14,b15,b13,b8,,a0,a1(b3,b4,b5,b6,b7,b8,a9,a8,b11,b12,b14,b15,b16,b17,b18,b19,b13,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b7,b9,b6,b8,b10,b11,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b4,b3,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b3,b1,b4,,b10,a5,a4,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,,,,,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b10,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a4,+a4,-a3,+a3(b4,b8,b0,b12,b16,b20,b24,b28,b32,b36,b40,b44,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a8,a12(b8,b12,b0,b4,b16,b20,b24,b28,b32,b36,,,h0.1,h0.4,h0.8,h0.2,b44,,a0,a4,a8,a12(b4,b0,b8,b12,,b28,a12,a16,,b36,,,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a20,a8(b1,b2,b0,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b4,b0,b8,b12,,b28,a12,a16,,b36,,,b48,b56,b60,b52,,,a0,a4,a20,a8(b1,b2,,,b7,b5,a3,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a5,b9,b8,b6,b7,b11,b12,b13,b14,b10,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,,,b5,b8,,,-a1,+a1,-a0,+a0,b2(b0,b1,b2,b3,b4,b5,b6,b15,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b13,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,a5,a4,b12,b13,b15,b16,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,-a1,+a1,-a0,+a0,b2(b0,b1,b3,b4,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,b8,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a31(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,b6,b7,b16,b15,b8,b9,b10,b11,b13,b12,b17,,a0,a1~,a2,a3~(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a4(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b33,b5,,,b6,b7,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b2,,,,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b2,,,b6,,b9,b7,,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a2(b2,b1,b3,b0,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b4,,b6,,b2,b7,b9,,,b2,b14,b15,b13(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b5,b7,b2,b10,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,a5~,a2~,b2,b8,b8,b5,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b4,,b9,b10,b6,b7,b8,,b5,b2,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b5,b4,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b2,b6,b7,b4,b5,b8,b9,b11,b12,b13,b14,b15,b16,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b16,b19,b17,b18,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b8,b9,b6,b7,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b10,b5,b11,b7,b8,b9,b4,b6,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b5,b7,b4,b6,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b13,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b0,b4,b2,b1,b3,b6,,,b11,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a2,a5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b9,b10,a4,a5,b4,b6,b7,b8,b11,b12,b13,b14,,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b3,b2,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,b11,b14,b12,b13,b10,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,a4,a3,,,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b6,b7,b9,b10,b12,b13,b14,b15,b16,b17,b19,b20,h0.1,h0.4,h0.8,h0.2,b18,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,,,,,,,b7,b6,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,a0,a1(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a5(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a3,a4(b1,b0,b4,b3,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a5`.split(`(`),Qa={l00790006:0,l00790011:1,l00790016:2,l00790122:3,l00790126:4,l00791800:5,l00791803:6,l0079181a:7,l0079181b:8,l0079181c:9,l00791830:10,l00791843:11,l00791844:12,l00791845:11,l00791846:13,l007918d2:7,l007918d4:14,l0079954e:15,l046dc20a:16,l046dc211:17,l046dc216:5,l046dc218:5,l046dc219:5,l046dc21a:18,l046dc21d:14,l046dc21e:14,l046dc21f:14,l046dcad1:5,l046dcad2:5,l04b4010a:19,l04b42411:20,l04b42412:21,l054c0268:22,l054c05c4:23,l054c09cc:24,l054c0ba0:24,l054c0cda:25,l054c0ce6:24,l054c0df2:24,l054c0e5f:24,l054c1337:26,l057e0330:27,l057e0337:28,l057e1337:29,l057e2006:30,l057e2007:31,l057e2008:32,l057e2009:33,l057e2017:34,l057e201e:35,l057e2069:36,l057e2073:37,l05ac022d:38,l05ac055b:39,l05ac057a:40,l05ac061a:41,l0e6f0109:42,l0e6f011e:7,l0e6f011f:14,l0e6f0128:5,l0e6f012f:7,l0e6f0130:7,l0e6f0131:14,l0e6f0139:14,l0e6f0146:43,l0e6f0164:14,l0e6f0180:7,l0e6f0181:7,l0e6f0184:7,l0e6f0185:44,l0e6f0187:7,l0e6f0188:7,l0e6f0203:45,l0e6f0207:46,l0e6f0213:14,l0e6f0214:7,l0e6f02a7:14,l0e6f02a8:47,l0e6f02b2:48,l0e6f02b8:14,l0e6f02c8:14,l0e6f02d7:49,l0e6f02d8:14,l0e6f02da:14,l0e6f02ef:14,l0e6f02f1:14,l0e6f0301:14,l0e6f0315:14,l0e6f0401:14,l0e6f0413:14,l0e6f1112:50,l0e6f1113:51,l0e6ff501:14,l0f0d0009:7,l0f0d0010:42,l0f0d0011:7,l0f0d0016:52,l0f0d0022:42,l0f0d004d:7,l0f0d005e:53,l0f0d005f:54,l0f0d0066:24,l0f0d0067:14,l0f0d006a:8,l0f0d006b:7,l0f0d006d:55,l0f0d006e:7,l0f0d0084:8,l0f0d0085:7,l0f0d0086:47,l0f0d0087:56,l0f0d0088:57,l0f0d0092:58,l0f0d00aa:39,l0f0d00c1:7,l0f0d00ee:59,l0f0d00f6:60,l0f0d00fb:39,l0f0d0137:61,l0f0d0138:62,l0f0d0150:14,l0f0d0185:14,l0f0d0196:63,l0f0d01ab:63,l15320401:24,l15320402:7,l15320705:64,l15320900:65,l15320a03:14,l15320a14:14,l15320a29:14,l15321000:8,l15321008:66,l1532100a:59,l1532100b:24,l15321100:24,l18d19400:65,l20d60dad:67,l20d62002:68,l20d62005:14,l20d6200b:14,l20d6200f:69,l20d62065:14,l20d62802:14,l20d64001:70,l20d64002:70,l20d64005:14,l20d66271:71,l20d6792a:24,l20d689e5:71,l20d6a710:5,l20d6a711:7,l20d6a712:7,l20d6a713:7,l20d6a714:7,l20d6ca6d:7,l24c65300:14,l24c6531a:14,l24c6541a:14,l24c6543a:14,l24c6581a:14,l24c65b02:14,l24c65d04:14,l24c6891a:63,l24c6891b:63,l24c6892a:72,l24c6892b:63,l24c6fafe:14,l27f80bbf:63,l28de1102:73,l28de1105:73,l28de1106:73,l28de1142:73,l28de11fc:43,l28de11ff:14,l28de1201:73,l28de1202:73,l28de1205:74,l2dc80651:75,l2dc81003:76,l2dc81080:76,l2dc82000:14,l2dc82003:14,l2dc8200a:77,l2dc82019:14,l2dc82025:14,l2dc82101:63,l2dc82830:78,l2dc82862:79,l2dc82865:79,l2dc82869:80,l2dc8286a:81,l2dc83010:82,l2dc83011:63,l2dc83012:63,l2dc83013:63,l2dc83015:63,l2dc83016:63,l2dc83017:63,l2dc83019:83,l2dc8301b:63,l2dc8301d:63,l2dc83100:84,l2dc83101:85,l2dc83102:85,l2dc83103:85,l2dc83104:85,l2dc83106:14,l2dc8310a:14,l2dc8310b:14,l2dc83230:86,l2dc83810:79,l2dc83820:87,l2dc85006:88,l2dc85101:89,l2dc85103:86,l2dc85104:90,l2dc85107:91,l2dc85108:91,l2dc85109:90,l2dc85111:92,l2dc85112:82,l2dc86000:92,l2dc86001:93,l2dc86002:92,l2dc86006:82,l2dc86007:94,l2dc86009:82,l2dc86012:63,l2dc86100:87,l2dc86101:93,l2dc86102:92,l2dc86728:95,l2dc89000:96,l2dc89001:96,l2dc89012:93,l2dc89015:79,l2dc89018:78,l2dc89020:97,l2dc89025:98,l2dc8ab21:78,l35371004:14,l35371007:63,l3537100b:14,l35371046:63,l35371058:63,l35371094:63,l35371097:63,l358a0102:63,l358a0202:63,l358a0203:63,l358a0204:63,m00790006:99,m00790011:100,m00791800:101,m00791803:102,m0079181c:41,m00791843:103,m00791844:104,m00791846:105,m007918d2:39,m0079954e:106,m046dc216:5,m046dc218:5,m046dc219:5,m046dc21a:18,m046dc21f:107,m04b4010a:108,m04b42411:20,m04b42412:20,m054c0268:22,m054c05c4:24,m054c09cc:24,m054c0ba0:24,m054c0cda:25,m054c0ce6:24,m054c0df2:24,m054c0e5f:24,m054c1337:26,m057e2006:30,m057e2007:31,m057e2009:60,m057e2017:109,m057e2069:36,m057e2073:37,m05ac061a:41,m0e6f0109:42,m0e6f0184:110,m0e6f0187:5,m0e6f0201:107,m0e6f0203:45,m0e6f0207:46,m0e6f0401:107,m0f0d002d:54,m0f0d004d:7,m0f0d005e:111,m0f0d005f:7,m0f0d0066:24,m0f0d006e:7,m0f0d0084:8,m0f0d0085:7,m0f0d0087:112,m0f0d0088:57,m0f0d0092:58,m0f0d00aa:39,m0f0d00c1:7,m0f0d00ee:113,m0f0d00f6:3,m0f0d0138:62,m0f0d0200:7,m15320401:24,m15320402:7,m15320705:64,m15320900:65,m15320a03:107,m15321000:8,m15321100:24,m18d19400:65,m20d66271:71,m20d6792a:24,m20d6a710:7,m20d6a711:44,m20d6ca6d:7,m24c6543a:107,m24c65d04:107,m24c6891a:114,m24c6891b:63,m24c6892a:64,m24c6892b:63,m24c6fafe:107,m2dc80651:115,m2dc82820:116,m2dc82830:78,m2dc82840:78,m2dc82865:87,m2dc82869:80,m2dc8286a:81,m2dc83011:63,m2dc83012:63,m2dc83013:63,m2dc83015:117,m2dc83016:63,m2dc83017:118,m2dc83019:83,m2dc8301b:63,m2dc8301d:63,m2dc83100:9,m2dc83101:85,m2dc83102:85,m2dc83103:85,m2dc83104:85,m2dc83105:84,m2dc83230:119,m2dc83810:94,m2dc85006:120,m2dc85101:89,m2dc85103:86,m2dc85104:90,m2dc85107:121,m2dc85108:122,m2dc85109:90,m2dc85111:82,m2dc85112:82,m2dc86001:79,m2dc86002:85,m2dc86006:82,m2dc86009:123,m2dc86101:85,m2dc86102:85,m2dc86728:95,m2dc89000:96,m2dc89001:79,m2dc89012:78,m2dc89015:124,m2dc89018:78,m2dc89020:125,m2dc89025:126,m2dc89026:127,m2dc8ab12:116,m35371022:63,m35371041:63,m35371046:63,m35371104:63,m358a0102:63,m358a0201:128,m358a0202:128,m358a0203:128,m358a0204:63,w00790002:129,w00790007:129,w0079000a:129,w00790016:18,w00790122:99,w00790126:130,w00791804:131,w0079181a:7,w0079181b:113,w00791824:132,w00791830:133,w00791845:11,w00791847:12,w0079184f:134,w00791879:135,w0079188f:136,w007918ae:137,w007918d4:138,w046dc209:139,w046dc20a:16,w046dc20b:140,w046dc211:141,w046dc21d:138,w046dc21e:142,w046dc242:142,w046dca84:143,w046dca88:143,w046dcad1:5,w046dcad2:7,w04b42410:144,w04b4c681:130,w054c05c5:145,w057e0330:146,w05ac022d:144,w05ac033d:147,w05ac044d:147,w05ac055b:39,w05ac057a:148,w0e6f0003:149,w0e6f0111:7,w0e6f0114:7,w0e6f0119:7,w0e6f011a:7,w0e6f011e:7,w0e6f011f:150,w0e6f0124:42,w0e6f0128:7,w0e6f012f:7,w0e6f0130:7,w0e6f0132:7,w0e6f0146:138,w0e6f0164:151,w0e6f0180:7,w0e6f0181:7,w0e6f0185:44,w0e6f0188:7,w0e6f0189:7,w0e6f0214:7,w0e6f0301:138,w0e6f1113:51,w0e6f6302:7,w0f0d0009:7,w0f0d000a:152,w0f0d000c:153,w0f0d000d:154,w0f0d0010:155,w0f0d0011:57,w0f0d0013:155,w0f0d001b:152,w0f0d0021:155,w0f0d0022:54,w0f0d0025:42,w0f0d0026:155,w0f0d0027:42,w0f0d0032:155,w0f0d003d:156,w0f0d0040:157,w0f0d0042:155,w0f0d0049:7,w0f0d004b:155,w0f0d0051:155,w0f0d0054:7,w0f0d0055:8,w0f0d005b:113,w0f0d005c:7,w0f0d0064:155,w0f0d0067:70,w0f0d006a:8,w0f0d006b:7,w0f0d006f:158,w0f0d0070:57,w0f0d007b:155,w0f0d008a:8,w0f0d008b:7,w0f0d008c:138,w0f0d009c:8,w0f0d00a0:159,w0f0d00a5:160,w0f0d00a6:111,w0f0d00ad:161,w0f0d00ae:142,w0f0d00af:162,w0f0d00c0:138,w0f0d00c9:5,w0f0d00d8:163,w0f0d00dc:138,w0f0d0101:5,w0f0d0104:142,w0f0d0123:144,w0f0d0137:164,w0f0d0162:165,w0f0d0164:166,w0f0d0196:134,w0f0d0202:167,w0f0d1011:168,w153202a6:169,w15320300:170,w15320707:147,w15320a14:138,w15321004:145,w15321007:145,w15321009:145,w1532100a:5,w18d12c40:171,w20d60060:7,w20d60dad:142,w20d6319f:7,w20d64026:134,w20d64033:134,w20d6571d:7,w20d6576d:7,w20d65795:7,w20d657c7:7,w20d657e5:7,w20d689e5:172,w20d6a712:7,w20d6a713:7,w20d6a714:7,w20d6a720:7,w24c6531a:153,w24c65b02:138,w27f80bbf:173,w28de11fc:70,w28de11ff:174,w2dc802e0:175,w2dc81003:176,w2dc81080:176,w2dc82100:144,w2dc82810:177,w2dc82862:78,w2dc83000:78,w2dc83001:178,w2dc8301c:134,w2dc8310a:134,w2dc83820:179,w2dc85001:180,w2dc86000:79,w2dc86003:123,w2dc86012:134,w2dc86100:85,w2dc86103:123,w2dc8ab11:179,w2dc8ab20:178,w2dc8ab21:78,w35371004:138,w35371007:134,w35371094:134,w35371116:134},$a=e=>e.toLowerCase().padStart(4,`0`);function eo(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:$a(t[2]),product:$a(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:$a(n[1]),product:$a(n[2]),name:n[3].trim()}:null}function to(e){return(eo(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function no(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function ro(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Qa[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Za[n]??null}return null}function io(e){return e.mapping!==`standard`&&eo(e.id)?.vendor===`2dc8`}var ao={6003:`switch`,6006:`switch`,6103:`switch`,3010:`switch`,6001:`startx`,6002:`startx`,6101:`startx`,6102:`startx`,3011:`receiver`,3012:`receiver`,3013:`receiver`,3015:`receiver`,3016:`receiver`,3017:`receiver`,"301b":`receiver`,"301c":`receiver`,"301d":`receiver`,6012:`receiver`,5112:`none`,9020:`none`};function oo(e){let t=eo(e);return t&&ao[t.product]||`manual`}var so={1:0,2:2,4:4,8:6};function co(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function lo(e,t,n){let{n:r,hat:i}=co(t),a=Ia.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function uo(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=so[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function fo(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function po(e,t,n){let r=e.split(`,`),i=lo(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&_o(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(_o)}function yo(){try{let e=Lt(go),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>vo(e[1])))}catch{return{}}}function bo(e,t){let n=yo();return t?n[e]=t:delete n[e],It(go,JSON.stringify(n)),xo=n,n}var xo=null;function So(e){return xo??=yo(),xo[e.id]??To(xo,e.id)??ho(e)??Ua(e)}function Co(e){return xo??=yo(),xo[e.id]?`saved`:e.mapping===`standard`?`standard`:ho(e)?`known`:`guess`}function wo(e){return ho(e)??Ua(e)}function To(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(xo=bo(t,e[i]),e[i]):null}function Eo(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Do(e,t){let n=null;if(t.buttons.forEach((t,r)=>{let i=t-(e.buttons[r]??0);t>.5&&i>.5&&(!n||i>n.amount)&&(n={src:{b:r},amount:i})}),n)return n.src;for(let n=0;n1.05?La(t.axes[n]):null;if(r!==null)return{h:n,at:r}}return t.axes.forEach((t,r)=>{let i=e.axes[r]??0,a=t-i;if(!(Math.abs(a)<.6)&&(!n||Math.abs(a)>n.amount)){let e=a>0?1:-1;n={src:Math.abs(i)>.5?{a:r,d:e,rest:i}:{a:r,d:e},amount:Math.abs(a)}}}),n?n.src:null}function Oo(e,t){let n=null;if(t.axes.forEach((t,r)=>{let i=t-(e.axes[r]??0);Math.abs(i)>=.6&&(!n||Math.abs(i)>Math.abs(n.moved))&&(n={a:r,moved:i})}),!n)return null;let r=n;return r.moved>0?{a:r.a}:{a:r.a,inv:!0}}var ko=[{kind:`button`,bit:R.CROSS,name:`✕`},{kind:`button`,bit:R.CIRCLE,name:`○`},{kind:`button`,bit:R.SQUARE,name:`□`},{kind:`button`,bit:R.TRIANGLE,name:`△`},{kind:`button`,bit:R.UP,name:`↑`},{kind:`button`,bit:R.DOWN,name:`↓`},{kind:`button`,bit:R.LEFT,name:`←`},{kind:`button`,bit:R.RIGHT,name:`→`},{kind:`button`,bit:R.L1,name:`L1`},{kind:`button`,bit:R.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:R.L3,name:`L3`},{kind:`button`,bit:R.R3,name:`R3`},{kind:`button`,bit:R.OPTIONS,name:`Options`},{kind:`button`,bit:R.SHARE,name:`Create`},{kind:`button`,bit:R.PS,name:`PS`},{kind:`button`,bit:R.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}];function Ao(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function jo(e,t,n){return t.kind===`button`?{...e,buttons:[...e.buttons.filter(([e])=>e!==t.bit),[t.bit,n]]}:(t.kind,{...e,[t.which]:n})}function Mo(e,t=Va){let n=new Set(e.buttons.map(([e])=>e)),r=e=>`b`in e?`b${e.b}`:`h`in e?`h${e.h}.${e.at}`:`a${e.a}${e.d}`,i=new Set([...e.buttons.map(([,e])=>r(e)),...[e.l2,e.r2].filter(e=>!!e).map(r)]);return{buttons:[...e.buttons,...t.buttons.filter(([e,t])=>!n.has(e)&&!i.has(r(t)))],l2:e.l2??t.l2,r2:e.r2??t.r2,lx:e.lx??t.lx,ly:e.ly??t.ly,rx:e.rx??t.rx,ry:e.ry??t.ry}}var No=ko.filter(e=>e.kind!==`button`||![R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD].includes(e.bit));function Po(e,t){return t.buttons.every((t,n)=>Math.abs(t-(e.buttons[n]??0))<.3)&&t.axes.every((t,n)=>Math.abs(t-(e.axes[n]??0))<.3)}var Fo=class{constructor(e=ko){this.steps=e,this.step=0,this.prof=Ao(),this.rest=null,this.waiting=!0}get done(){return this.step>=this.steps.length}get current(){return this.steps[this.step]??null}feed(e){if(this.done)return!1;if(!this.rest)return this.rest=e,this.waiting=!1,!1;if(this.waiting)return Po(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Oo(this.rest,e):Do(this.rest,e);return n?(this.prof=jo(this.prof,t,n),this.go(this.step+1),!0):!1}skip(){this.go(this.step+1)}back(){this.step>0&&this.go(this.step-1)}go(e){this.waiting=!0,this.step=Math.min(e,this.steps.length)}profile(e=Va){return Mo(this.prof,e)}};function Io(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}function Lo(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Ro=e=>`ps5upload.join.token.${e??`app`}`,zo=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...ja},this.lastSent=0,this.neutral=!1,this.stopped=!1,this.attempt=0,this.deadline=0,this.raf=0,this.keepalive=null,this.pinger=null,this.retry=null,this.lastHeard=0,this.hostAway=!1,this.pings=0,this.now=e.now??(()=>Date.now()),this.storage=e.storage===void 0?Lo():e.storage,this.WS=e.WebSocketImpl??WebSocket,this.seq=this.now()>>>0;try{this.token=this.storage?.getItem(this.key)??null}catch{this.token=null}}get key(){return Ro(this.o.invite??this.o.code??null)}get current(){return this.stage}get socket(){return this.ws}get resumeToken(){return this.token}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.stopped=!1,this.setStage({kind:`connecting`}),this.connect(),this.stopped)return;let e=()=>{this.sendPad(!1),this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e)};this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e),this.keepalive=setInterval(()=>this.sendPad(!1),100),this.pinger=setInterval(()=>this.ping(),1e3)}connect(){let e;try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,e.onopen=()=>{if(this.ws!==e)return;this.lastHeard=this.now();let t={name:this.o.name};this.o.invite&&(t.invite=this.o.invite),this.o.code&&(t.code=this.o.code),this.token&&(t.resume=this.token),e.send(JSON.stringify({hello:t}))},e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),typeof t.data==`string`?this.onText(t.data):t.data instanceof ArrayBuffer&&this.stage.kind===`joined`&&this.o.onFrame?.(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Ue(t);n===`mismatch`?(this.forgetToken(),this.finish({kind:`ended`,why:n})):n&&this.stage.kind!==`joined`&&this.stage.kind!==`reconnecting`?this.finish({kind:`ended`,why:n}):this.dropped()},e.onerror=()=>{}}onText(e){let t=Je(e);if(t)switch(t.kind){case`pong`:{let e=this.now()-t.t;e>=0&&e<6e4&&this.o.onRtt?.(e);return}case`asking`:this.stage.kind!==`reconnecting`&&this.setStage({kind:`asking`});return;case`waiting`:this.hostAway||(this.hostAway=!0,this.deadline=this.now()+et),this.attempt=0,this.setStage(this.reconnectingStage());return;case`joined`:this.token=t.token,this.player=t.player,this.attempt=0,this.hostAway=!1;try{this.storage?.setItem(this.key,t.token)}catch{}{let e=t.track&&this.ws?.media||null;this.o.onCodec?.(t.hevc,e,!!e&&t.audio&&!!e.audio)}this.setStage({kind:`joined`,player:t.player,hevc:t.hevc}),this.sendPad(!0);return;case`refused`:this.forgetToken(),this.hostAway&&t.why!==`seat_taken`?this.finish({kind:`ended`,why:`host_stopped`}):this.finish({kind:`refused`,why:t.why});return;case`bye`:if(t.why===`host_stopped`&&this.token){this.hostWait();return}this.forgetToken(),this.finish({kind:`ended`,why:t.why});return;case`status`:this.stage.kind===`joined`&&t.status.player>0&&t.status.player!==this.stage.player&&(this.player=t.status.player,this.setStage({...this.stage,player:t.status.player})),this.o.onStatus?.(t.status);return;case`feedback`:t.rumble&&this.o.onRumble?.(t.rumble[0],t.rumble[1]),t.light&&this.o.onLight?.(t.light);return}}hostWait(){this.hostAway=!0,this.deadline=this.now()+et,this.attempt=0;let e=this.ws;this.ws=null;try{e?.close()}catch{}this.scheduleRetry()}reconnectingStage(){return{kind:`reconnecting`,player:this.player,attempt:this.attempt,deadline:this.deadline,...this.hostAway?{hostStopped:!0}:{}}}giveUp(){this.forgetToken(),this.finish({kind:`ended`,why:this.hostAway?`host_stopped`:`gave_up`})}dropped(){if(this.stopped)return;let e=this.stage;e.kind===`joined`||e.kind===`reconnecting`&&this.token?(e.kind===`joined`&&(this.deadline=this.now()+$e),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Qe(this.attempt);this.setStage(this.reconnectingStage()),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.stopped||(this.now()>=this.deadline?this.giveUp():this.connect())},e)}forgetToken(){this.token=null;try{this.storage?.removeItem(this.key)}catch{}}ping(){if(this.hostAway&&!this.stopped&&this.now()>=this.deadline+5e3||!this.stopped&&this.stage.kind===`reconnecting`&&this.now()>=this.deadline+5e3){this.giveUp();return}let e=this.ws;if(e&&e.readyState===this.WS.OPEN){if(this.stage.kind===`joined`&&this.now()-this.lastHeard>3500){this.ws=null;try{e.close()}catch{}this.dropped()}else if(e.send(JSON.stringify({ping:this.now()})),this.stage.kind===`joined`&&this.o.readStats&&++this.pings%2==0){let t=this.o.readStats();t&&e.send(JSON.stringify({stats:t}))}}}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.sendPad(!0))}sendPad(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||this.stage.kind!==`joined`)return;let n=this.neutral?{...ja,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Io(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Ze(this.seq,n)))}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.pinger&&clearInterval(this.pinger),this.retry&&clearTimeout(this.retry),this.keepalive=this.pinger=this.retry=null}finish(e){this.stopped=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&e.send(JSON.stringify({keyframe:!0}))}leave(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&(this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),e.send(JSON.stringify({leave:1}))),this.forgetToken(),this.finish({kind:`ended`,why:`left`})}stop(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},Bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),z=s(((e,t)=>{t.exports=Bo()}))(),Vo=`ps5upload.openIn`,Ho=`ps5upload.openIn.tab`;function Uo(){try{return sessionStorage.getItem(Ho)===`browser`}catch{return!1}}function B(){try{sessionStorage.setItem(Ho,`browser`)}catch{}}function V(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Wo({appLink:e,children:t}){let n=Ie(),[r,i]=(0,D.useState)(()=>Uo()?`browser`:V(Lt(Vo))),[a,o]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,z.jsx)(z.Fragment,{children:t});let s=()=>{a&&It(Vo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?It(Vo,`browser`):r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&Rt(Vo),B(),i(`browser`)};return(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,z.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,z.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}var Go=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type='hidden'])`,`select:not([disabled])`,`textarea:not([disabled])`,`summary`,`[contenteditable='true']`,`[tabindex]`].map(e=>`${e}:not([tabindex='-1'])`).join(`, `),Ko=new Set,qo=[];function Jo(){for(let e of Ko)e()}function Yo(){return qo.length}function Xo(e){return qo.push(e),Jo(),()=>{let t=qo.lastIndexOf(e);t!==-1&&qo.splice(t,1),Jo()}}function Zo(e,t,n){switch(n){case`down`:return t.top-e.bottom;case`up`:return e.top-t.bottom;case`right`:return t.left-e.right;case`left`:return e.left-t.right}}function H(e,t,n){let r=(e.left+e.right)/2,i=(e.top+e.bottom)/2,a=(t.left+t.right)/2,o=(t.top+t.bottom)/2;switch(n){case`down`:return o>i&&t.top>=e.top+1;case`up`:return or&&t.left>=e.left+1;case`left`:return a0?{gap:0,overlap:c}:{gap:-c,overlap:0}}function $o(e,t,n){let r=null,i=1/0,a=!1;for(let o of t){if(!H(e,o.rect,n))continue;let t=Math.max(0,Zo(e,o.rect,n)),s=Qo(e,o.rect,n),c=s.overlap>0;if(a&&!c)continue;let l=c?t-s.overlap/1e6:Math.hypot(t,2*s.gap);(c&&!a||l`u`?void 0:window){try{return!!e?.PS5UploadTv?.isTv()}catch{return!1}}function rs(e=typeof document>`u`?void 0:document){return e?.documentElement.dataset.tv===`1`}function is(e,t){if(!e)return!1;if(e.closest(`[data-own-arrows]`))return!0;let n=e.tagName;if(n===`TEXTAREA`||e.isContentEditable)return!0;let r=t===`left`||t===`right`;if(n===`INPUT`){let t=(e.type||`text`).toLowerCase();if(t===`range`||ts.test(t))return r}return!1}var as=`[aria-modal="true"], [role="dialog"], [role="alertdialog"]`;function os(e){let t=e.activeElement?.closest(as);if(t)return t;if(Yo()>0){let t=e.querySelectorAll(as);if(t.length)return t[t.length-1]}return e}function ss(e){let t=[];return e.querySelectorAll(Go).forEach(e=>{if(e.closest(`[inert], [aria-hidden='true']`)||e.disabled)return;let n=e.getBoundingClientRect();n.width<=0||n.height<=0||t.push({el:e,rect:n})}),t}function cs(e){return(e.find(e=>e.el.getAttribute(`aria-current`)===`page`)??e[0])?.el??null}function ls(e,t=document){let n=es[e.key];if(!n||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return!1;let r=t.activeElement;if(is(r,n))return!1;let i=ss(os(t));if(!i.length)return!1;let a=i.find(e=>e.el===r),o=a?$o(a.rect,i.filter(e=>e!==a),n):cs(i);return o?(e.preventDefault(),o.focus(),typeof o.scrollIntoView==`function`&&o.scrollIntoView({block:`nearest`,inline:`nearest`}),!0):!1}var us=!1;function ds(e){us||(us=!0,e.addEventListener(`keydown`,t=>void ls(t,e.document)))}function fs(e=typeof window>`u`?void 0:window){e&&(ns(e)&&(e.document.documentElement.dataset.tv=`1`),ds(e))}function ps({id:e,className:t}){let n=Ie(),r=oo(e);if(r===`none`)return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_no_xinput`,void 0,`This 8BitDo has no X-input mode. If a button is wrong, check the controller.`)});let i=r===`switch`?n(`pad_8bitdo_how_switch`,void 0,`set the switch on the back to X, then press Start`):r===`startx`?n(`pad_8bitdo_how_startx`,void 0,`turn it off, then hold Start + X to turn it on`):r===`receiver`?n(`pad_8bitdo_how_receiver`,void 0,`use its 2.4G receiver or a USB cable`):n(`pad_8bitdo_how_manual`,void 0,`its manual says how`);return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_xinput`,{how:i},`For the best result, switch your 8BitDo to X-input mode: ${i}.`)})}var ms=new Set,hs={held:new Set,touch:null,touchPad:ja,mapping:!1,get paused(){return ms.size>0},motion:null},gs={s:.85,m:1,l:1.15},_s=.25;function vs(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(_s,e))}var ys={overlay:{width:844,height:390},deck:{width:390,height:480}},bs=.7,xs=1.4;function Ss(e,t,n,r){let i=gs[e]??1;if(!(t>0)||!(n>0))return i;let a=r?ys.deck:ys.overlay,o=Math.min(xs,Math.max(bs,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var Cs=34;function ws(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+Cs>t}function Ts(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var Es=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,Ds=32767,Os=12;function ks({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Ie(),s=(0,D.useRef)(new Map),c=(0,D.useRef)({...ja}),[l,u]=(0,D.useState)({...ja}),[d,f]=(0,D.useState)({l:!1,r:!1,touchpad:!1}),p=(0,D.useRef)(null),[m,h]=(0,D.useState)({width:0,height:0});(0,D.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,D.useEffect)(()=>()=>{hs.touchPad={...ja}},[]);let g=()=>{let t={...ja,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=R.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,hs.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*Ds),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*Ds)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ma((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ma((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Os&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,C=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,w=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,T={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},E=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),te=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ne={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},re=(e,t,n,r)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${te} ${n}`,style:ne,children:r}),ie=(e,t,n,r)=>(0,z.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${w} ${C(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),ae=(e,t,n,r)=>re(e,t,`h-[44px] w-[84px]`,ie(e,ee(t),n,r)),oe=(e,t,n)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${te} h-[44px] w-[84px]`,style:ne,children:ie(e,l[t]>0,n,!0)}),se=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:(0,z.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...E(ee(t)),children:[(0,z.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,z.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ce=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:[(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...E(ee(t))}),(0,z.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),le=(e,t)=>re(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,z.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${w} ${C(ee(t))}`,children:e})),ue=(e,t)=>re(e,t,`h-[44px] w-[44px]`,(0,z.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),de=e=>{let{dx:t,dy:n}=Ts(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,z.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,z.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${C(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},O=t===`deck`,fe=Ss(r,m.width,m.height,O),pe=e=>`${e}px * var(--k)`,k=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=O?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${pe(t)}, ${n}px))`:`calc(${e} + ${pe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=O&&ws(fe,m.height),A=O?void 0:`58%`,j=e=>O?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?k:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?k:me},xe=e=>({bottom:be?he:_e(he,O?56:0,44),[e]:be?`calc(${e===`left`?k:me} + 8px + max(${pe(80)}, 44px))`:_e(e===`left`?k:me,O?40:168)}),Se=!!a&&!O;return(0,z.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${O?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:O?i:void 0,"--k":fe},"data-testid":`rp-touch`,"data-layout":t,"data-scale":fe,onContextMenu:e=>e.preventDefault(),children:[(0,z.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:vs(n)},children:[(0,z.jsx)(`div`,{style:ye(`top left`,{top:ge,left:k}),children:(0,z.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:O?void 0:`6deg`,transformOrigin:`top left`},children:[oe(`L2`,`l2`,`l`),ae(`L1`,R.L1,`l`,!1)]})}),(0,z.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,z.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:O?void 0:`-6deg`,transformOrigin:`top right`},children:[oe(`R2`,`r2`,`r`),ae(`R1`,R.R1,`r`,!1)]})}),(0,z.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:O?{top:_e(ge,6),left:_e(k,104),right:_e(me,104),height:`max(44px, calc(${pe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${pe(250)}), 34vw)`,height:`max(44px, calc(${pe(56)}))`}}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top left`:`left center`,j(`left`)),children:[(0,z.jsx)(`span`,{}),se(`↑`,R.UP,0),(0,z.jsx)(`span`,{}),se(`←`,R.LEFT,-90),(0,z.jsx)(`span`,{}),se(`→`,R.RIGHT,90),(0,z.jsx)(`span`,{}),se(`↓`,R.DOWN,180),(0,z.jsx)(`span`,{})]}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top right`:`right center`,j(`right`)),children:[(0,z.jsx)(`span`,{}),ce(`△`,R.TRIANGLE,(0,z.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,z.jsx)(`span`,{}),ce(`□`,R.SQUARE,(0,z.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,z.jsx)(`span`,{}),ce(`○`,R.CIRCLE,(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,z.jsx)(`span`,{}),ce(`✕`,R.CROSS,(0,z.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:de(`l`)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:de(`r`)}),(0,z.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:k}),children:le(`Create`,R.SHARE)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:le(`Options`,R.OPTIONS)}),(0,z.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:Es,translate:`-50% 0`}),children:ue(`PS`,R.PS)})]}),Se&&(0,z.jsx)(`div`,{style:{...ye(`bottom center`,{bottom:he,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,vs(n))},children:(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${te} h-[44px] w-[56px]`,style:ne,"data-testid":`rp-menu-handle`,children:(0,z.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,z.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var As=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,js=null,Ms=null;function Ns(e){e.play().catch(()=>{if(Ms||js!==e)return;let t=()=>{Ps(),js===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),Ms=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Ps(){Ms?.(),Ms=null}function Fs(){if(typeof document<`u`){if(!js){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=As,document.body.appendChild(e),js=e}Ns(js)}}function Is(){Ps(),js&&=(js.pause(),js.removeAttribute(`src`),js.remove(),null)}function Ls(){return typeof navigator>`u`?null:navigator.wakeLock??null}function Rs(){return dt()||!Pn()}var zs=new Set,Bs=null,Vs=Promise.resolve(),Hs=!1;async function Us(){if(zs.size===0||Bs&&!Bs.released)return;let e=Ls();if(!e)dt()&&Fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{Bs===t&&(Bs=null)}),Bs=t}catch{}}async function Ws(){Is();let e=Bs;if(Bs=null,e&&!e.released)try{await e.release()}catch{}}function Gs(){Hs||typeof document>`u`||(Hs=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&zs.size>0&&(Vs=Vs.then(Us))}))}function Ks(e,t){if(!Rs())return;Gs();let n=zs.size>0;t?zs.add(e):zs.delete(e);let r=zs.size>0;n!==r&&(Vs=Vs.then(r?Us:Ws))}var qs=new Set;function Js(){if(typeof window<`u`)return window.PS5UploadPad}function Ys(e,t){let n=qs.size>0;t?qs.add(e):qs.delete(e);let r=qs.size>0;if(n!==r)try{Js()?.setActive(r)}catch{}}var Xs=class e{constructor(e){this.receiver=e,this.last=null,this.was={}}get frames(){return Number(this.last?.frames??0)}static report(e,t){let n=t=>e[t]??0,r=e=>n(e)-(t[e]??0),i=(e,t)=>r(t)>0?Math.round(r(e)/r(t)*1e4)/10:0;return{frames:n(`framesDecoded`),dropped:n(`framesDropped`),stalls:n(`freezeCount`),stall_ms:Math.round(n(`totalFreezesDuration`)*1e3),decode_ms:i(`totalDecodeTime`,`framesDecoded`),jitter_ms:i(`jitterBufferDelay`,`jitterBufferEmittedCount`),nacks:n(`nackCount`),plis:n(`pliCount`),decoder:`track`}}snapshot(){return this.receiver.getStats().then(t=>{t.forEach(t=>{t.type===`inbound-rtp`&&t.kind===`video`&&(this.last=e.report(t,this.was),this.was={...t})})}).catch(()=>{}),this.last}},Zs=class{constructor(e){this.inner=e,this.video=document.createElement(`video`),this.wrap=document.createElement(`div`),this.media=null,this.trackStats=null,this.audio=!1,this.soundOn=!1,this.muted=!1;let t=this.video;t.muted=t.autoplay=t.playsInline=!0,t.className=`block h-full w-full object-contain`,t.dataset.testid=`track-video`,this.wrap.className=`h-full w-full`,this.wrap.append(t,e.element),this.setTrack(null)}get element(){return this.wrap}get stats(){return this.trackStats??this.inner.stats}setTrack(e,t=!1){this.media=e,this.audio=!!e&&t,this.applySound(),this.trackStats=e?new Xs(e.receiver):null,this.video.style.display=e?``:`none`,this.inner.element.style.display=e?`none`:``,this.video.srcObject!==(e?.stream??null)&&(this.video.srcObject=e?.stream??null),e&&this.play()}play(){try{this.video.play()?.catch?.(()=>{})}catch{}}onMessage(e){let t=new Uint8Array(e)[0];this.media&&t<=1||(!this.audio||t!==3&&t!==4)&&this.inner.onMessage(e)}applySound(){this.video.muted=!(this.audio&&this.soundOn&&!this.muted)}setHevc(e){this.inner.setHevc(e)}set onSoundFail(e){this.inner.onSoundFail=e}soundReport(){return this.inner.soundReport()}startSound(){this.inner.startSound(),this.soundOn=!0,this.applySound(),this.media&&this.play()}setMuted(e){this.inner.setMuted(e),this.muted=e,this.applySound()}resumeSound(){this.inner.resumeSound(),this.media&&this.video.paused&&this.play()}stop(){this.inner.stop(),this.video.srcObject=null}},Qs=`ps5upload.join.muted`,$s=5e3,ec=Object.fromEntries(Object.entries(Na).filter(([e])=>e!==`Escape`)),tc=new Set;function nc(e){if(!(e.code in ec)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||rc(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||rc(t))}function rc(e){let t=e?.tagName;if(t===`BUTTON`||t===`A`)return!0;let n=e?.getAttribute?.(`role`);return n===`button`||n===`link`||n===`menuitem`||n===`tab`||n===`switch`}var ic=!1;function ac(e){ic=e}function oc(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function sc(){if(ic)return{...ja};let e=Ga(Xa(typeof navigator>`u`?void 0:navigator),So),t=hs.touchPad;return{...Ka(Ka(e,Fa(tc,ec)),t),touch:t.touch??null,motion:hs.motion??null}}var cc=class{constructor(e){this.opts=e,this.player=null,this.listeners=new Set,this.cleanups=[],this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.snap={stage:{kind:`connecting`},status:null,rttMs:null,light:null,problem:null,sound:!1,noSound:!1,host:e.host,muted:uc(),path:null},this.client=new zo({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:sc,onStage:e=>{this.set({stage:e}),e.kind===`joined`&&this.readPath(),(e.kind===`refused`||e.kind===`ended`)&&this.teardown()},onStatus:e=>this.set({status:e,host:e.host??this.snap.host}),onRtt:e=>this.set({rttMs:e}),onFrame:e=>this.picture().onMessage(e),readStats:()=>oc(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Zs&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Xa(typeof navigator>`u`?void 0:navigator);qa(n,e,t),n.some(e=>e?.connected)||navigator.vibrate?.(e||t?200:0)},onLight:e=>this.set({light:e})})}picture(){if(!this.player){let e=oa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Zs(e):e,this.player.onSoundFail=()=>this.set({noSound:!0}),this.player.setMuted(this.snap.muted)}return this.player}async readPath(){let e=this.client.socket,t=this.opts.path??null;if(e?.netPath)try{t=await e.netPath()??this.opts.path??null}catch{t=null}t!==this.snap.path&&this.set({path:t})}get element(){return this.picture().element}start(){let e=()=>{document.visibilityState===`hidden`?tc.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{tc.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&nc(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),tc.add(e.code))},r=e=>{tc.delete(e.code)&&nc(e)&&e.preventDefault()};window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r);let i=()=>{this.client.setNeutral(document.visibilityState===`hidden`),document.visibilityState!==`hidden`&&this.player?.resumeSound()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`blur`,t),window.addEventListener(`focus`,i);let a=setInterval(()=>{this.client.current.kind===`joined`&&this.readPath()},$s);this.cleanups.push(()=>{clearInterval(a),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`blur`,t),window.removeEventListener(`focus`,i),window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),tc.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(Qs,e?`1`:`0`)}catch{}this.set({muted:e})}startSound(){this.snap.sound||(this.picture().startSound(),this.set({sound:!0}))}leave(){this.client.leave(),this.teardown()}stop(){this.client.stop(),this.teardown()}teardown(){for(let e of this.cleanups.splice(0))e();hs.touchPad={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};let e=this.player;this.player=null,e&&(e.stop(),e.element.remove())}sendPad(){this.client.sendPad(!1)}get snapshot(){return this.snap}set(e){this.snap={...this.snap,...e};for(let e of this.listeners)e()}};function lc(e){return(0,D.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function uc(){try{return typeof localStorage<`u`&&localStorage.getItem(Qs)===`1`}catch{return!1}}function dc(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Ks(`play-together`,n),Ys(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Ks(`play-together`,!1),Ys(`play-together`,!1)}}var fc=3e3,pc=class{constructor(e,t=fc){this.onChange=e,this.delay=t,this.enabled=!1,this.pinned=!1,this.sticky=!1,this.shown=!0,this.timer=null}get visible(){return!this.enabled||this.pinned||this.shown}set(e,t,n=!1){let r=this.enabled&&!this.pinned,i=this.enabled,a=this.sticky;this.enabled=e,this.pinned=t,this.sticky=n,!e||t?(this.stop(),this.show(!0)):n?(this.stop(),!i||!a?this.show(!1):r||this.show(!0)):(!r||a)&&(this.show(!0),this.arm())}poke(){this.show(!0),this.enabled&&!this.pinned&&!this.sticky&&this.arm()}toggle(){this.visible?this.hide():this.poke()}hide(){this.enabled&&!this.pinned&&(this.stop(),this.show(!1))}dispose(){this.stop()}arm(){this.stop(),this.timer=setTimeout(()=>{this.timer=null,this.show(!1)},this.delay)}stop(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}show(e){this.shown!==e&&(this.shown=e,this.onChange(e))}};function mc(e,t,n=!1){let[r,i]=(0,D.useState)(!0),a=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=new pc(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,D.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,D.useCallback)(()=>a.current?.poke(),[]),s=(0,D.useCallback)(()=>a.current?.hide(),[]),c=(0,D.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var hc=3e4,gc=class{constructor(e,t=hc){this.onChange=e,this.ms=t,this.picking=!1,this.over=!1,this.timer=null}get shown(){return this.picking&&!this.over}set(e){e!==this.picking&&(this.picking=e,this.over=!1,this.stop(),e&&(this.timer=setTimeout(()=>{this.timer=null,this.over=!0,this.onChange()},this.ms)))}stop(){this.timer&&clearTimeout(this.timer),this.timer=null}reset(){this.stop(),this.picking=!1,this.over=!1}};function _c(e){let[,t]=(0,D.useState)(0),[n]=(0,D.useState)(()=>new gc(()=>t(e=>e+1)));return(0,D.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,D.useEffect)(()=>()=>n.reset(),[n]),n.shown}var vc=()=>Xa(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function yc(e,t){if(t.kind===`axis`)return t.which===`lx`?e(`rp_pad_step_lx`,void 0,`Push the left stick right`):t.which===`ly`?e(`rp_pad_step_ly`,void 0,`Push the left stick down`):t.which===`rx`?e(`rp_pad_step_rx`,void 0,`Push the right stick right`):e(`rp_pad_step_ry`,void 0,`Push the right stick down`);if(t.kind===`button`){if(t.bit===R.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===R.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===R.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===R.TRIANGLE)return e(`join_check_top`,void 0,`Press the top face button (△)`)}return e(`rp_pad_press`,{name:t.name},`Press ${t.name}`)}function bc(e,t){let n=(0,D.useRef)(t);(0,D.useEffect)(()=>{n.current=t}),(0,D.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(vc().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var xc=[[R.CROSS,`✕`],[R.CIRCLE,`○`],[R.SQUARE,`□`],[R.TRIANGLE,`△`],[R.UP,`↑`],[R.DOWN,`↓`],[R.LEFT,`←`],[R.RIGHT,`→`],[R.L1,`L1`],[R.R1,`R1`],[R.L3,`L3`],[R.R3,`R3`],[R.SHARE,`Create`],[R.OPTIONS,`Options`],[R.PS,`PS`],[R.TOUCHPAD,`Touchpad`]];function Sc({pad:e}){let t=e=>`flex h-8 min-w-8 items-center justify-center rounded-md px-1.5 text-xs font-medium ${e?`bg-white text-black`:`bg-white/10 text-white/70`}`,n=(e,t,n)=>(0,z.jsxs)(`span`,{className:`relative flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-[10px] text-white/50`,children:[n,(0,z.jsx)(`span`,{className:`absolute h-3 w-3 rounded-full bg-white`,style:{left:`calc(50% + ${e/32767*18}px - 6px)`,top:`calc(50% + ${t/32767*18}px - 6px)`}})]});return(0,z.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[xc.map(([n,r])=>(0,z.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,z.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,z.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,z.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function Cc({onClose:e}){let t=Ie(),[n,r]=(0,D.useState)(()=>vc().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,D.useState)(()=>vc()[0]?.index??null),[o,s]=(0,D.useState)(ja),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(yo),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useRef)(null);(0,D.useEffect)(()=>(ac(!0),()=>ac(!1)),[]),(0,D.useEffect)(()=>{(v.current?.querySelector(`[data-testid="join-pad-learn-start"]`)??v.current?.querySelector(`[data-testid="join-pad-check-close"]`))?.focus({preventScroll:!0})},[]),(0,D.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||v.current?.querySelector(`button:not([disabled])`)?.focus({preventScroll:!0})},[c,u]),(0,D.useEffect)(()=>{let e=()=>{let e=vc();r(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n].id&&t.index===e[n].index)?t:e.map(e=>({index:e.index,id:e.id}))),a(t=>t!==null&&e.some(e=>e.index===t)?t:e[0]?.index??null)},t=window.setInterval(e,500);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(t),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),bc(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(Eo(e))&&y(c,e);return}let t=Ga([e],So);s(e=>e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry?e:t)});let y=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(bo(r,e.profile(n?wo(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},b=()=>{h(null),d(0),l(new Fo(No))},x=g,S=x?Co(x):null,ee=!!(x&&f[x.id]);return(0,z.jsx)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":t(`join_check_title`,void 0,`Check your controller`),className:`absolute inset-0 z-40 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm`,"data-testid":`join-pad-check`,onPointerDown:e=>e.stopPropagation(),children:(0,z.jsxs)(`div`,{className:`w-[min(26rem,100%)] space-y-3 rounded-2xl border border-white/10 bg-neutral-900/95 p-4 text-sm text-white shadow-2xl`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(me,{size:16,className:`text-white/70`}),(0,z.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t(`join_done`,void 0,`Done`),className:`flex h-8 w-8 items-center justify-center rounded-full bg-white/10 hover:bg-white/20`,"data-testid":`join-pad-check-close`,children:(0,z.jsx)(De,{size:15})})]}),x?(0,z.jsxs)(z.Fragment,{children:[n.length>1&&(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,z.jsx)(`button`,{type:`button`,disabled:!!c,onClick:()=>a(e.index),className:`rounded-full px-2.5 py-1 text-xs ${e.index===i?`bg-white text-black`:`bg-white/10`}`,children:to(e.id)},`${e.index}-${e.id}`))}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:to(x.id)}),(0,z.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":S??``,children:S===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):S===`guess`?t(`join_check_unknown`,void 0,`This controller isn't on our list, so its buttons may be mixed up. Setting it up takes a few seconds.`):t(`rp_pad_standard`,void 0,`Recognized`)}),io(x)&&(0,z.jsx)(ps,{id:x.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`rp_pad_progress`,{n:u+1,total:c.steps.length},`${u+1} of ${c.steps.length}`)}),(0,z.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?yc(t,c.current):``}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),y(c,x)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-learn-skip`,children:t(`rp_pad_skip`,void 0,`Skip`)}),u>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.back(),d(c.step)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,children:t(`rp_pad_back`,void 0,`Back`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>l(null),className:`rounded-full px-3 py-1.5 text-xs text-white/70 hover:bg-white/10`,children:t(`rp_pad_cancel`,void 0,`Cancel`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`join_check_try`,void 0,`Press buttons and move the sticks: what you press lights up.`)}),(0,z.jsx)(Sc,{pad:o}),m&&(0,z.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:b,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:ee?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),ee&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{p(bo(x.id,null)),h(null)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-reset`,children:t(`rp_pad_reset`,void 0,`Reset`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-check-done`,children:t(`join_done`,void 0,`Done`)})]})]})]}):(0,z.jsx)(`p`,{className:`text-white/70`,children:t(`rp_pads_none`,void 0,`No controller seen yet. Connect one and press any button on it.`)})]})})}function wc(e,t){let[n,r]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(!e||!t)return;let n=!0;return Be(e,Le).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function Tc({href:e}){let t=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,z.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function Ec(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var Dc=`ps5upload.join.guided`,Oc=1;function kc(e){return e.player!==Oc&&(!e.guided||e.movedOff)&&!e.reconnecting}function Ac(e,t){switch(t){case`lan`:return e(`join_path_lan`,void 0,`Home network`);case`tailscale`:return e(`join_path_tailscale`,void 0,`Tailscale`);default:return e(`join_path_internet`,void 0,`Internet`)}}function jc(e,t){return e(`join_seat_taken`,{host:t},`${t} needed their controller back and no other controller was free on the PS5, so you're out of the game. Ask ${t} to let you in again.`)}function Mc(e,t,n,r=!1){if(t.kind===`refused`)switch(t.why){case`key`:return e(`join_refused_key`,{host:n},`This invite has expired. Ask ${n} for a new link.`);case`expired`:return e(`join_refused_expired`,{host:n},`Your place in the game was lost. Ask ${n} to let you in again.`);case`full`:return e(`join_refused_full`,void 0,`The game is full: four players already.`);case`denied`:return e(`join_refused_denied`,{host:n},`${n} didn't let you in this time.`);case`no_answer`:return e(`join_refused_no_answer`,{host:n},`${n} didn't answer in time. Tell ${n}, then try again.`);case`closed`:return e(`join_refused_closed`,{host:n},`${n} isn't hosting Play Together right now.`);case`old_helper`:return e(`join_refused_old_helper`,{host:n},`${n}'s PS5 needs an updated helper for Play Together.`);case`not_playing`:return e(`join_refused_not_playing`,{host:n},`${n} isn't playing right now. Ask ${n} to start Play first.`);case`unreachable`:return e(`join_refused_unreachable`,{host:n},`${n}'s computer couldn't reach their PS5. Try again in a moment.`);case`slow_down`:return e(`join_refused_slow_down`,void 0,`Too many wrong codes. Wait a minute, then try again.`);case`address`:return e(`join_refused_address`,{host:n},`This link's address is outside your home network, so the app will not use it. Ask ${n} for a link with their computer's IP address.`);case`seat_taken`:return jc(e,n);default:return e(`join_refused_other`,{host:n},`${n} didn't let you in.`)}if(t.kind===`ended`)switch(t.why){case`kicked`:return e(`join_ended_kicked`,{host:n},`${n} took you out of the game.`);case`closed`:return e(`join_ended_closed`,{host:n},`${n} closed Play Together.`);case`host_stopped`:return e(`join_ended_host_stopped`,void 0,`The host stopped playing.`);case`replaced`:return e(`join_ended_replaced`,void 0,`This game was opened in another tab or on another device, so it stopped here.`);case`pad_lost`:return e(`join_ended_pad_lost`,{host:n},`The PS5 lost your controller, so you're out of the game. Ask ${n} to let you in again.`);case`gave_up`:return e(`join_ended_gave_up`,{host:n},`The connection to ${n} didn't come back in time.`);case`lost`:return r?e(`join_net_lost`,{host:n},`The connection to ${n} dropped. Check your internet connection, then ask again.`):e(`join_ended_lost`,{host:n},`Couldn't reach ${n}. Check that you're on the same network.`);case`left`:return e(`join_ended_left`,void 0,`You left the game.`);case`seat_taken`:return jc(e,n);case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`join_net_no_room`,{host:n},`This invite isn't open any more. Ask ${n} for a new link.`);case`net_full`:return e(`join_net_full`,{host:n},`${n}'s game has no room for another friend right now. Try again in a moment.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:return e(`join_net_offer`,{host:n},`${n}'s computer couldn't connect to this browser. Try another browser.`);case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`)}return``}function Nc(e){let[t,n]=(0,D.useState)(()=>Date.now());return(0,D.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function Pc(){let[e,t]=(0,D.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,D.useEffect)(()=>{let e=()=>{let e=Xa(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?sc():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?Co(e):null,s=!!e&&io(e);t(e=>e.ready===n&&e.pressed===i&&e.id===a&&e.kind===o&&e.weak8BitDo===s?e:{ready:n,pressed:i,id:a,kind:o,weak8BitDo:s})};e();let n=window.setInterval(e,120);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(n),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),e}function Fc(e){return!!e?.closest?.(`[data-testid="rp-touch"]`)}var Ic=14,Lc=()=>typeof window<`u`&&!rs()&&!!window.matchMedia?.(`(pointer: coarse)`).matches;function Rc(e,t,n){return!e||e===t||e.closest?.(`[data-join-game]`)?`game`:n?.contains(e)?`controls`:`page`}function zc(e){return e.checking?`close-check`:e.guide?`close-guide`:e.where===`game`?`show-controls`:e.full?`leave-full`:null}var Bc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function Vc({text:e,body:t,onCancel:n}){let r=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,z.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,z.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,z.jsx)(Se,{size:26})})]}),(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!0,className:`rounded-full bg-white/15 px-4 py-2 text-sm hover:bg-white/25`,"data-testid":`join-cancel`,children:r(`join_cancel`,void 0,`Cancel`)})]})}function Hc({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Ie(),c=lc(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,D.useRef)(null),p=(0,D.useRef)(null),m=(0,D.useRef)(null),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(()=>Lt(Dc)===`1`),[y,b]=(0,D.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),x=Pc(),[S,ee]=(0,D.useState)(!1),C=l.kind===`reconnecting`,w=Nc(C),T=l.kind===`joined`||C,E=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[ne,re]=(0,D.useState)(!1),ie=(0,D.useRef)(te);(0,D.useEffect)(()=>{ie.current===Oc&&te>Oc&&re(!0),te&&(ie.current=te)},[te]);let[ae,oe]=(0,D.useState)(!1),[se,ce]=(0,D.useState)(!1),le=T&&(h||!t),de=Lc(),fe=_c(E),k=mc(le,C||fe&&!de||ae||se,de),{poke:he}=k,_e=(0,D.useRef)(null),ve=()=>{_e.current&&clearTimeout(_e.current.timer),_e.current=null};(0,D.useEffect)(()=>ve,[]);let[ye,A]=(0,D.useState)(!1),xe=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(!le||!de||k.shown||!_||xe.current)return;xe.current=!0,A(!0);let e=setTimeout(()=>A(!1),6e3);return()=>clearTimeout(e)},[le,de,k.shown,_]),(0,D.useEffect)(()=>{if(!T)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[T,e]),(0,D.useEffect)(()=>{if(!T||c.sound)return;let t=()=>e.startSound(),n=[`pointerup`,`touchend`,`click`,`keydown`];for(let e of n)window.addEventListener(e,t,!0);return()=>{for(let e of n)window.removeEventListener(e,t,!0)}},[T,c.sound,e]),(0,D.useEffect)(()=>{let e=()=>b(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,D.useEffect)(()=>{if(h)return()=>void i?.(!1)},[h,i]);let Ce=(0,D.useRef)(h);(0,D.useEffect)(()=>{Ce.current=h},[h]),(0,D.useEffect)(()=>{if(!t||!T||!Lc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!Ce.current&&(g(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,T,i]),(0,D.useEffect)(()=>{t&&T&&rs()&&!Ce.current&&(g(!0),i?.(!0))},[t,T,i]),(0,D.useEffect)(()=>{if(!T)return;let e=e=>{if(e.key!==`Escape`)return;if(S)return void Le.current();if(he(),h)return g(!1);let t=Rc(document.activeElement,document.body,p.current);t===`game`?Le.current():t===`controls`&&m.current?.focus({preventScroll:!0})};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[T,h,he,S]),(0,D.useEffect)(()=>{if(!h||!Lc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,g(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[h]),(0,D.useEffect)(()=>{if(!h||typeof document>`u`)return;let e=()=>{document.fullscreenElement||Lc()||g(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[h]);let Te=rs(),Ee=T&&kc({player:te,guided:_,movedOff:ne,reconnecting:C})&&!u?.playsAs,De=async e=>{g(e),await i?.(e)},Oe=()=>m.current?.focus({preventScroll:!0}),ke=()=>{It(Dc,`1`),v(!0),re(!1)},Ae=()=>{he();let e=C?`[data-testid="join-reconnecting-leave"]`:`[data-testid="join-bar"] button`;p.current?.querySelector(e)?.focus({preventScroll:!0})},je=()=>{let e=p.current?.querySelector(`[data-testid="join-check-open"]`);e?e.focus({preventScroll:!0}):Oe(),ee(!1)},Me=()=>Rc(document.activeElement,document.body,p.current),[Ne,Pe]=(0,D.useState)(`game`);(0,D.useEffect)(()=>{if(!T)return;let e=()=>Pe(Me()),t=()=>window.setTimeout(e,0);return e(),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t)}},[T]);let Fe=()=>{switch(T?zc({checking:S,guide:Ee,where:Me(),full:h}):null){case`close-check`:return je(),!0;case`close-guide`:return ke(),Oe(),!0;case`show-controls`:return Ae(),!0;case`leave-full`:return De(!1),!0;default:return!1}},Le=(0,D.useRef)(Fe);(0,D.useEffect)(()=>{Le.current=Fe});let Re=t&&!de&&T&&zc({checking:S,guide:Ee,where:Ne,full:h})!==null;(0,D.useEffect)(()=>{if(Re)return Xo(()=>void Le.current())},[Re]);let ze=!t&&T&&!de;(0,D.useEffect)(()=>{if(!ze)return;let e=window.location.href;window.history.pushState(window.history.state,``);let t=!0,n=()=>{if(t=!1,!Le.current())return window.history.back();window.history.pushState(window.history.state,``),t=!0};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),t&&window.location.href===e&&window.history.back()}},[ze]);let Be=l.kind===`joined`;(0,D.useEffect)(()=>{if(!Be)return;let e=document.activeElement;if(e&&e!==document.body)return;let t=Te&&Ee?p.current?.querySelector(`[data-testid="join-guide-ok"]`):null;t?t.focus({preventScroll:!0}):Oe()},[Be]),(0,D.useEffect)(()=>{x.pressed&&T&&!S&&Me()===`controls`&&Oe()},[x.pressed]);let Ve=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,z.jsxs)(`div`,{className:t?`rounded-[var(--radius-card)] bg-neutral-900 text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black text-white`,"data-join-ui":``,children:[l.kind===`connecting`&&o&&a&&(0,z.jsx)(Tc,{href:a}),(0,z.jsx)(Vc,{text:l.kind===`connecting`?s(`join_connecting`,{host:d},`Connecting to ${d}…`):s(`join_waiting`,{host:d},`Waiting for ${d} to let you in`),body:l.kind===`asking`?s(`join_waiting_body`,{host:d},`${d} sees your name on their screen and taps Allow.`):void 0,onCancel:Ve})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,z.jsxs)(`div`,{className:t?`flex flex-col items-center gap-4 rounded-[var(--radius-card)] bg-neutral-900 px-6 py-10 text-center text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black px-6 text-center text-white`,"data-testid":`join-ended`,"data-why":l.why,"data-join-ui":``,children:[(0,z.jsx)(Se,{size:28,className:`text-white/60`}),(0,z.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:Mc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,z.jsx)(Tc,{href:a}),(0,z.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,z.jsx)(`button`,{type:`button`,onClick:r,autoFocus:!0,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`join-again`,children:l.kind===`refused`&&l.why===`not_playing`?s(`join_retry`,void 0,`Try again`):s(`join_again`,void 0,`Ask to join again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!i,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let He=l.player,Ue=c.light??at(He),We=c.rttMs??u?.rttMs??null,Ge=it(We),Ke=Lc(),qe=T&&!C&&!x.ready&&Ke&&(!t||h),Je=kc({player:He,guided:_,movedOff:ne,reconnecting:C}),Ye=He===Oc,Xe=u?.playsAs??null,Ze=C?(l.deadline-w)/1e3:0,Qe=()=>De(!h),$e=t&&!h&&Ke&&T,et=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`span`,{className:`flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 font-medium`,"data-testid":`join-player`,children:[(0,z.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`}}),t&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:He},`You are Player ${He}`)]}),We!=null&&(0,z.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:Bc[Ge]},"data-testid":`join-delay`,"data-tone":Ge,"data-path":c.path??void 0,children:[c.path&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[Ac(s,c.path),` · `]}),Math.round(We),` ms`]}),Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-stream`,children:s(`join_seat_stream`,{host:d},`You're playing as ${d}'s PS5 user. No need to pick one.`)}),Xe&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-plays-as`,children:s(`join_plays_as`,{profile:Xe},`You're playing as ${Xe}. No need to pick one.`)}),E&&!Ye&&u?.seatNote&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-note`,children:s(`join_seat_tv_asks`,{host:d},`${d} chose a profile for you, but it couldn't be used. The TV will ask who you are.`)}),E&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-picking`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)})]}),tt=(0,z.jsxs)(z.Fragment,{children:[le&&de&&k.shown&&!C&&(0,z.jsxs)(`button`,{type:`button`,onClick:k.hide,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 font-medium`,"data-testid":`join-hide-controls`,children:[(0,z.jsx)(pe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex items-center gap-1 rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-sound`,children:[(0,z.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-mute`,children:[c.muted?(0,z.jsx)(M,{size:13}):(0,z.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,z.jsxs)(`span`,{className:`flex items-center gap-1 rounded-full bg-black/60 px-2.5 py-1 text-white/80`,"data-testid":`join-no-sound`,children:[(0,z.jsx)(M,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>void Qe(),"aria-label":h?s(`join_exit_fullscreen`,void 0,`Leave full screen`):s(`pad_fill`,void 0,`Full screen`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-full`,children:h?(0,z.jsx)(be,{size:13}):(0,z.jsx)(O,{size:13})}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),"aria-label":s(`join_check_title`,void 0,`Check your controller`),title:s(`join_check_title`,void 0,`Check your controller`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-check-open`,children:(0,z.jsx)(me,{size:13})}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex items-center gap-1 rounded-full bg-[var(--color-danger,#dc2626)] px-3 py-1 font-medium`,"data-testid":`join-leave`,children:[(0,z.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),nt=k.shown?`opacity-100`:`pointer-events-none opacity-0`,rt={"data-testid":`join-bar`,"data-shown":k.shown?`1`:`0`,onFocus:e=>{(Te||e.target.matches?.(`:focus-visible`))&&ce(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||ce(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&oe(!0)},onPointerLeave:()=>oe(!1)},ot=h||!t?`fixed inset-0 z-[200] bg-black`:`relative mx-auto aspect-video w-full max-w-[max(20rem,calc((100dvh_-_22rem)*16/9))] overflow-hidden rounded-[var(--radius-card)] bg-black shadow-[var(--shadow-2)]`,st=t&&h;return(0,z.jsxs)(`div`,{className:`space-y-2`,ref:p,"data-join-ui":``,children:[(0,z.jsxs)(`div`,{className:`${ot} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},role:st?`dialog`:void 0,"aria-modal":st?!0:void 0,"aria-label":st?s(`pad_fill`,void 0,`Full screen`):void 0,onPointerMove:e=>{if(e.pointerType===`mouse`)return he();let t=_e.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>Ic&&ve()},onPointerDown:e=>{if(Fc(e.target))return;if(e.pointerType===`mouse`||!de)return he();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;ve();let{pointerId:t,clientX:n,clientY:r}=e;_e.current={id:t,x:n,y:r,timer:setTimeout(()=>{_e.current=null,navigator.vibrate?.(15),k.toggle()},450)}},onPointerUp:ve,onPointerCancel:ve,onPointerLeave:ve,"data-testid":`join-stage-view`,children:[(0,z.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),le&&!k.shown&&!C&&We!=null&&(0,z.jsxs)(`span`,{className:`pointer-events-none absolute z-10 rounded-full bg-black/40 px-1.5 py-0.5 text-[10px] leading-none tabular-nums`,style:{color:Bc[Ge],top:`max(0.5rem, env(safe-area-inset-top))`,right:`max(0.5rem, env(safe-area-inset-right))`},"data-testid":`join-delay-corner`,children:[Math.round(We),` ms`]}),qe?(0,z.jsxs)(`div`,{className:`absolute left-1/2 top-1/2 z-20 flex w-max max-w-[min(24rem,calc(100%-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-2 rounded-2xl bg-black/70 p-3 text-xs backdrop-blur-sm transition-opacity duration-300 ${nt}`,...rt,children:[(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:et}),(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:tt})]}):$e?null:(0,z.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex flex-wrap items-center gap-2 bg-gradient-to-b from-black/70 to-transparent px-3 pb-5 pt-[max(8px,env(safe-area-inset-top))] text-xs transition-opacity duration-300 ${nt}`,...rt,children:[et,(0,z.jsx)(`span`,{className:`flex-1`}),tt]}),!k.shown&&!qe&&(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},"aria-label":s(`join_show_controls`,void 0,`Show controls`),className:`absolute left-1/2 top-[max(6px,env(safe-area-inset-top))] z-20 flex h-7 w-11 -translate-x-1/2 items-center justify-center rounded-full bg-black/40 text-white/70 opacity-60 hover:opacity-100 focus-visible:opacity-100`,"data-testid":`join-show-controls`,children:(0,z.jsx)(ue,{size:16,"aria-hidden":!0})}),ye&&!k.shown&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-[max(10px,env(safe-area-inset-top))] z-20 -translate-x-1/2 rounded-full bg-black/60 px-3 py-1 text-xs text-white/85`,"data-testid":`join-hold-hint`,children:s(`join_hold_hint`,void 0,`Press and hold the picture to show the buttons`)}),c.problem&&(0,z.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`join-problem`,children:c.problem===`no_hevc`?s(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):s(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),S&&(0,z.jsx)(Cc,{onClose:je}),qe&&(0,z.jsx)(ks,{stream:e,layout:`overlay`,onMenu:()=>k.shown?k.hide():he()}),!qe&&!C&&(0,z.jsxs)(`div`,{className:`absolute bottom-3 left-3 z-20 flex items-center gap-2 rounded-2xl bg-black/70 px-3 py-1.5 text-xs transition-opacity duration-300 ${nt}`,"data-testid":`join-pad`,children:[(0,z.jsx)(me,{size:14,style:{color:x.pressed?`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`:void 0}}),x.ready?(0,z.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),x.weak8BitDo&&x.id&&(0,z.jsx)(ps,{id:x.id,className:`text-amber-200/90`}),x.kind===`guess`&&no()&&(0,z.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2 text-white/75`,"data-testid":`join-pad-unknown`,children:[s(`join_check_unknown_short`,void 0,`Not on our list: buttons may be mixed up.`),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),className:`rounded-full bg-white px-2.5 py-0.5 font-medium text-black`,"data-testid":`join-pad-unknown-check`,children:s(`join_check_title`,void 0,`Check your controller`)})]})]}):Ke&&t&&!h?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,z.jsxs)(`span`,{className:`flex flex-col`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,z.jsx)(`span`,{className:`text-white/60`,"data-testid":`join-pad-keys`,children:s(`join_pad_keys`,void 0,`Or use the keyboard: WASD move, arrows D-pad, Enter ✕, Backspace ○, Q □, E △, Tab Options.`)})]}),Te&&(0,z.jsx)(`span`,{className:`max-w-[14rem] border-l border-white/20 pl-2 text-white/70`,"data-testid":`join-tv-back`,children:s(`join_tv_back_hint`,void 0,`Press Back on the remote for the buttons.`)})]}),u?.blockSystem&&u.state===`playing`&&!qe&&(0,z.jsx)(`p`,{className:`absolute bottom-3 right-3 z-20 rounded-full bg-black/60 px-3 py-1 text-[11px] text-white/70 transition-opacity duration-300 ${nt}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),fe&&!Ye&&de&&!k.shown&&!C&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-2 z-20 -translate-x-1/2 whitespace-nowrap rounded-full bg-white/90 px-2.5 py-1 text-xs font-medium text-black`,"data-testid":`join-picking-note`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)}),Je&&!Xe&&(0,z.jsxs)(`div`,{className:`absolute bottom-14 left-1/2 z-30 w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-2xl border border-white/10 bg-neutral-900/90 p-4 text-sm shadow-2xl backdrop-blur-md`,"data-testid":`join-guide`,children:[(0,z.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/75`,children:s(`join_guide_body`,void 0,`On your controller, press PS once. The TV asks "Who's using this controller?". Pick Quick Play or your own user. The host doesn't need to do anything.`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/60`,children:s(`join_guide_menus`,void 0,`On the PS5's home screen only the host controls the menus; your controller plays inside games.`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>{ke(),Oe()},className:`mt-3 rounded-full bg-white px-3 py-1 text-xs font-medium text-black`,"data-testid":`join-guide-ok`,children:s(`join_guide_ok`,void 0,`Got it`)})]}),C&&(0,z.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-black/70 px-6 text-center`,"data-testid":`join-reconnecting`,children:[(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`absolute right-3 top-[max(10px,env(safe-area-inset-top))] flex items-center gap-1 rounded-full bg-white/15 px-3 py-1.5 text-sm font-medium hover:bg-white/25`,"data-testid":`join-reconnecting-leave`,children:[(0,z.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,z.jsx)(`span`,{className:`h-7 w-7 animate-spin rounded-full border-2 border-white/30 border-t-white`,"aria-hidden":!0}),l.hostStopped?(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:Ec(Ze)},`The host stopped playing — waiting for them to start again (${Ec(Ze)})`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:Ec(Ze)},`Your place is kept for ${Ec(Ze)}.`)})]})]}),!t&&T&&y&&Ke&&(0,z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,z.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,z.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})}),(0,z.jsx)(`div`,{ref:m,tabIndex:0,"data-own-arrows":``,"data-join-game":``,"aria-label":s(`join_game_label`,{host:d},`${d}'s game`),className:`pointer-events-none absolute inset-0 outline-none`,"data-testid":`join-game`})]}),$e&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-[var(--radius-card)] bg-neutral-900 px-3 py-2 text-xs text-white`,"data-testid":`join-bar`,"data-shown":`1`,"data-below":`1`,children:[(0,z.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:et}),(0,z.jsxs)(`button`,{type:`button`,onClick:()=>void Qe(),className:`flex h-11 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full bg-white/15 px-3 text-sm font-medium hover:bg-white/25`,"data-testid":`join-fullscreen-below`,children:[(0,z.jsx)(O,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,z.jsx)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,"aria-label":c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`),className:`flex h-11 w-11 items-center justify-center rounded-full bg-white/15 hover:bg-white/25`,children:c.muted?(0,z.jsx)(M,{size:16}):(0,z.jsx)(we,{size:16})}):c.sound?null:(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-white px-3 text-sm font-medium text-black`,children:[(0,z.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-[var(--color-danger,#dc2626)] px-4 text-sm font-medium`,"data-testid":`join-leave-below`,children:[(0,z.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var Uc=`ps5upload.join.name`;function Wc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function Gc(e){return e.trim().slice(0,32)}function Kc(e=``){return Gc(Lt(`ps5upload.join.name`)??``)||e}function qc(e){let t=Gc(e);return t&&It(Uc,t),t}function Jc(e){try{return!!sessionStorage.getItem(Ro(e))}catch{return!1}}async function Yc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Xc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Ie(),c=wc(r&&o!==!1?e:null,i),[l,u]=(0,D.useState)(()=>Kc(Wc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(0),h=(0,D.useCallback)(e=>{if(!e)return;let t=typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,n=e.querySelector(`[data-testid="join-name"]`)?.value.trim()?`join-go`:t?null:`join-name`;n&&e.querySelector(`[data-testid="${n}"]`)?.focus({preventScroll:!0})},[]),g=i=>{let s=qc(i);if(!s)return;let c=new cc({url:e,invite:t,name:s,host:n,transport:r,path:a,...o===void 0?{}:{internet:o}});f(c),m(e=>e+1),c.start()};if((0,D.useEffect)(()=>{!d&&Jc(t)&&l.trim()&&g(l)},[]),(0,D.useEffect)(()=>d?dc(d):void 0,[d]),(0,D.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,z.jsx)(Hc,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),g(l)},onFullscreen:Yc},p);let _=n??s(`join_host_fallback`,void 0,`your friend`),v=(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,"data-join-ui":``,children:(0,z.jsxs)(`form`,{ref:h,className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),g(l)},children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,z.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,z.jsx)(Se,{size:20})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:_},`Play on ${_}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,z.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,z.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,z.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),maxLength:32,autoComplete:`nickname`,className:`block w-full rounded-lg border border-white/15 bg-black px-3 py-2 text-base outline-none focus:border-white/50`,"data-testid":`join-name`}),(0,z.jsx)(`span`,{className:`block text-xs text-white/50`,children:s(`join_name_hint`,void 0,`Your friend sees this when you ask to join.`)})]}),(0,z.jsx)(`button`,{type:`submit`,disabled:!l.trim(),className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black disabled:opacity-40`,"data-testid":`join-go`,children:s(`join_button`,void 0,`Join`)}),c&&i&&(0,z.jsx)(Tc,{href:i})]})});return t?(0,z.jsx)(Wo,{appLink:rt(location.href),children:v}):v}function Zc(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Qc(e,t){let n=Zc(e),r=Zc(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function $c(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Zc(t);return n===0?`lan`:n===1?`tailscale`:null}function el(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Qc(a(i.localCandidateId),a(i.remoteCandidateId))}function tl(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function nl(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function rl(e,t){let n=nl(e);return n!==null&&n===t.toUpperCase()}var il=16777216;function al(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function sl(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var cl=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],ll=1500,ul=2e4;function dl(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var fl=null;function pl(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function ml(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||fl)return;let r=tl(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};fl=a;let o=()=>{fl===a&&(fl=null,a.timer&&clearTimeout(a.timer),pl(i))};i.onopen=()=>i.send(JSON.stringify({v:1,t:`join`,room:e.room})),i.onmessage=e=>{if(typeof e.data==`string`)try{a.msgs.push(JSON.parse(e.data))}catch{}},i.onclose=o,i.onerror=()=>{},a.timer=setTimeout(o,t.keepMs??6e4)}function hl(e,t){let n=fl;return n?(fl=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(pl(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function gl(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new ol,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??tl(e.hub),a=t.signalUrl||t.lan?null:hl(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:cl}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=dl(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!rl(t.sdp,e.fp):nl(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(sl(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return el(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of al(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+ul,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},ll),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(He,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}var _l=3e3;function vl(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var U=e=>vl(e,`api/join/signal`);function yl(e){let t=[];if(e.rtc){let n=e.net??{room:``,key:``,fp:e.fp??``,hub:``};for(let[r,i]of[[`lan`,e.lan],[`tailscale`,e.ts]]){let a=i?U(i):null;if(!a)continue;let o=e.rtcMake(n,{signalUrl:e.reach(a),...e.net?{}:{lan:!0}});t.push({via:r,make:()=>new o(``),pinned:!!n.fp})}if(e.net){let n=e.rtcMake(e.net,{});t.push({via:`hub`,make:()=>new n(``),pinned:!0})}}let n=e.lan?vl(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var bl=new Map;function xl(e,t,n=300,r=_l){let i=e.some(e=>e===`lan`||e===`tailscale`),a=e.some(e=>e!==`socket`);return e.map(e=>e===t?0:e===`hub`&&i?n:e===`socket`&&a?r:0)}function Sl(e){let t=e.find(e=>e.via===`hub`),n=e.find(e=>(e.via===`lan`||e.via===`tailscale`)&&[`no_direct`,`net_full`,`offer`].includes(Ue(e.e)??``));return t&&(Ue(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function Cl(e,t){var n;let r=t.log??(()=>{}),i=t.headStartMs??300,a=t.socketAfterMs??3e3;class o{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.live=[],this.waiting=[],this.pinned=new Set,this.t0=0,this.closes=[],this.winner=null,setTimeout(()=>this.begin(),0)}get via(){return this.winner?.via??null}get media(){return this.winner?.s?.media??null}async netPath(){let e=this.winner?.s;return e?.netPath?e.netPath():null}begin(){if(this.readyState!==0)return;let n=e();if(!n.length){this.end({type:`close`,code:1006,reason:``,wasClean:!1});return}this.t0=Date.now();for(let e of n)e.pinned&&this.pinned.add(e.via);let r=xl(n.map(e=>e.via),bl.get(t.room)??null,i,a);n.forEach((e,t)=>{r[t]===0?this.launch(e.via,e.make):this.waiting.push({via:e.via,make:e.make,timer:setTimeout(()=>this.startWaiting(e.via),r[t])})})}startWaiting(e){let t=this.waiting.findIndex(t=>t.via===e);if(t<0)return;let[n]=this.waiting.splice(t,1);clearTimeout(n.timer),this.launch(n.via,n.make)}launch(e,t){if(this.readyState!==0)return;let n;try{n=t()}catch{this.tryClosed(e,{type:`close`,code:1006,reason:``,wasClean:!1});return}r(`path: trying ${e}`);let i={via:e,s:n};this.live.push(i),n.binaryType=this.binaryType,n.onopen=e=>this.won(i,e),n.onclose=t=>{this.live=this.live.filter(e=>e!==i),this.tryClosed(e,t)},n.onerror=()=>{},n.onmessage=null}tryClosed(e,t){if(this.readyState===0){if(r(`path: ${e} failed after ${Date.now()-this.t0} ms${t?.reason?` (${t.reason})`:``}`),this.closes.push({via:e,e:t}),this.pinned.has(e)&&Ue(t)===`mismatch`){for(let e of this.waiting.filter(e=>e.via===`socket`))clearTimeout(e.timer);this.waiting=this.waiting.filter(e=>e.via!==`socket`)}!this.live.length&&this.waiting.length?this.startWaiting(this.waiting[0].via):!this.live.length&&!this.waiting.length&&this.end(Sl(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,bl.set(t.room,e.via),r(`path: playing by ${e.via} after ${Date.now()-this.t0} ms`);for(let e of this.waiting.splice(0))clearTimeout(e.timer);for(let t of this.live.splice(0))if(t!==e){t.s.onopen=t.s.onclose=t.s.onmessage=t.s.onerror=null;try{t.s.close()}catch{}}let i=e.s;i.onmessage=e=>this.onmessage?.(e),i.onerror=e=>this.onerror?.(e),i.onclose=e=>{this.readyState!==3&&(this.readyState=3,this.onclose?.(e))},this.readyState=1,t.onWin?.(e.via),this.onopen?.(n)}send(e){if(this.readyState!==1||!this.winner)throw Error(`not open`);this.winner.s.send(e)}close(e,t){if(this.readyState===3)return;let n=this.readyState===1;this.readyState=3;for(let e of this.waiting.splice(0))clearTimeout(e.timer);let r=this.winner?[this.winner,...this.live]:this.live.splice(0);for(let n of r){n.s.onopen=n.s.onclose=n.s.onmessage=n.s.onerror=null;try{n.s.close(e,t)}catch{}}let i=this.onclose;if(i){let r={type:`close`,code:e??1e3,reason:t??``,wasClean:n};setTimeout(()=>i(r),0)}}end(e){if(this.readyState===3)return;this.readyState=3;let t=this.onclose,n=e??{type:`close`,code:1006,reason:``,wasClean:!1};t&&setTimeout(()=>t(n),0)}}return n=o,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,o}fs();var wl=new URLSearchParams(location.hash.slice(1)),Tl=wl.get(`n`)?.trim()||null,El=nt(location.hash);El&&ml(El);var Dl=(0,x.createRoot)(document.getElementById(`root`));if(El){let e=gl(El,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Re(location.hash,`join`);Dl.render((0,z.jsx)(Xc,{url:tl(El.hub),invite:El.key,host:Tl,transport:e,lanUrl:t?ze(t,{key:El.key}):null}))}else{let e=wl.get(`i`)||null,t=location.pathname.replace(/\/join\/?$/,``),n=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${t}/api/join/ws`,r=e=>console.info(`[join] ${e}`),i=`${location.origin}${t}/join`,a=typeof RTCPeerConnection>`u`?void 0:Cl(()=>yl({net:null,lan:i,ts:null,fp:tt(wl.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>gl(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});Dl.render((0,z.jsx)(Xc,{url:n,invite:e,host:Tl,path:$c(location.hostname),transport:a,internet:!1}))} diff --git a/site/pad/index.html b/site/pad/index.html index c35b03638..a59852b02 100644 --- a/site/pad/index.html +++ b/site/pad/index.html @@ -268,9 +268,9 @@ ã/¸Äyf"Ÿ5TàyÊ0îEê²Þ—€m6ëÞè6ðÏâ§9ž¬„k=}¼àt<ž‚¦Mdžç6"p_î3, oO3p"pw÷´/(1ñøs.íA/&ÏUÃ_X™ÍpÕ1hÌ80E’Qö„ ow÷!x.™AÜ"¢j+惡¦¶®ä“R–ow÷!xꔊpn…â#ðù z AÍp\Ž0N˜HJê´ªØ^U -I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} From 0699f1b1ec20e00f7a268dc230ef4dc37213f434 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:11:48 -0800 Subject: [PATCH 11/27] Install only an update that matched the release it came from The updater took the download address and the SHA-256 from the page, so a script in the page could have it fetch any file on a pinned host (any GitHub release) with a hash to match. A release with no published hash was downloaded unchecked, and "Install and restart" ran whatever file sat in the updates folder. Now a download must be the file the last check read from the release manifest, checked against the hash that manifest published, under the name the check gave; a file with no published hash is not downloaded (every release since 10.2 has one). Install, install on quit and the Android APK download take only a file that matched, and installs hash it again right before it runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/self_install.rs | 32 ++- .../src-tauri/src/commands/update_android.rs | 50 ++-- client/src-tauri/src/commands/updates.rs | 231 ++++++++++++++---- client/src/i18n/locales/ar.ts | 1 + client/src/i18n/locales/bn.ts | 1 + client/src/i18n/locales/de.ts | 1 + client/src/i18n/locales/en.ts | 1 + client/src/i18n/locales/es.ts | 1 + client/src/i18n/locales/fa.ts | 1 + client/src/i18n/locales/fr.ts | 1 + client/src/i18n/locales/hi.ts | 1 + client/src/i18n/locales/hu.ts | 1 + client/src/i18n/locales/id.ts | 1 + client/src/i18n/locales/it.ts | 1 + client/src/i18n/locales/ja.ts | 1 + client/src/i18n/locales/ko.ts | 1 + client/src/i18n/locales/pl.ts | 1 + client/src/i18n/locales/pt-BR.ts | 1 + client/src/i18n/locales/ru.ts | 1 + client/src/i18n/locales/th.ts | 1 + client/src/i18n/locales/tr.ts | 1 + client/src/i18n/locales/vi.ts | 1 + client/src/i18n/locales/zh-CN.ts | 1 + client/src/i18n/locales/zh-TW.ts | 1 + client/src/lib/shellError.ts | 4 + scripts/i18n-source-hashes.json | 1 + 26 files changed, 242 insertions(+), 97 deletions(-) diff --git a/client/src-tauri/src/commands/self_install.rs b/client/src-tauri/src/commands/self_install.rs index 58002cff9..3770f80fa 100644 --- a/client/src-tauri/src/commands/self_install.rs +++ b/client/src-tauri/src/commands/self_install.rs @@ -956,11 +956,14 @@ pub async fn update_install_on_quit( }; let (download, dir) = downloaded_update(&app, &path)?; // Off the main thread: this runs whenever a transfer starts or ends while an update waits, - // and the plan probes the app's folder with a write and, on Linux, asks the package database. + // the file is hashed again (only a download that matched its release is ever armed), and the + // plan probes the app's folder with a write and, on Linux, asks the package database. let probe = download.clone(); - let armed = tauri::async_runtime::spawn_blocking(move || installs_quietly(&probe)) - .await - .map_err(|e| format!("update_install_on_quit: {e}"))?; + let armed = tauri::async_runtime::spawn_blocking(move || { + super::updates::check_verified(&probe).map(|()| installs_quietly(&probe)) + }) + .await + .map_err(|e| format!("update_install_on_quit: {e}"))??; let record = record_for(&app, &download, version.as_deref()); *on_quit_slot() = armed.then_some(Armed { download, @@ -976,8 +979,13 @@ pub fn install_armed_on_quit() { let Some(armed) = on_quit_slot().take() else { return; }; - let result = match plan(&armed.download) { - Some(p) if !p.needs_password() && armed.download.is_file() => { + // Hashed again: the file waited on disk since it was armed. + let result = match ( + plan(&armed.download), + super::updates::check_verified(&armed.download), + ) { + (_, Err(e)) => Err(e), + (Some(p), Ok(())) if !p.needs_password() => { record_and_start(&p, false, &armed.dir, &armed.record) } _ => Err("the armed update can no longer be installed".into()), @@ -1009,10 +1017,14 @@ pub async fn update_install( ) -> Result<(), String> { let (download, dir) = downloaded_update(&app, &path)?; let probe = download.clone(); - let plan = tauri::async_runtime::spawn_blocking(move || plan(&probe)) - .await - .map_err(|e| format!("update_install: {e}"))? - .ok_or_else(|| super::shell_error::code_only("update_cannot_self_install"))?; + // Only a download that matched its release's SHA-256, hashed again now: the file sat in the + // updates folder since, and this runs it. + let plan = tauri::async_runtime::spawn_blocking(move || { + super::updates::check_verified(&probe)?; + plan(&probe).ok_or_else(|| super::shell_error::code_only("update_cannot_self_install")) + }) + .await + .map_err(|e| format!("update_install: {e}"))??; if let Plan::LinuxPackage { package, manager, .. } = &plan diff --git a/client/src-tauri/src/commands/update_android.rs b/client/src-tauri/src/commands/update_android.rs index c8f374595..88160b1d0 100644 --- a/client/src-tauri/src/commands/update_android.rs +++ b/client/src-tauri/src/commands/update_android.rs @@ -64,13 +64,6 @@ pub fn device_abilist() -> String { .unwrap_or_default() } -/// A SHA-256 from the manifest as 64 lowercase hex chars, or None when it is -/// absent or malformed (a malformed one is an error for the caller, not a skip). -fn normalize_sha256(raw: &str) -> Option { - let s = raw.trim().to_ascii_lowercase(); - (s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())).then_some(s) -} - /// A plain `.apk` basename: no separators, no leading dot. fn is_apk_filename(name: &str) -> bool { !name.is_empty() @@ -135,14 +128,17 @@ pub struct ApkDownload { /// Absolute path of the verified APK, for `PS5UploadUpdater.install`. pub path: String, pub bytes: u64, - /// The SHA-256 from latest.json matched (false: the release has none). + /// The SHA-256 from latest.json matched: always, since an APK without one is not + /// downloaded. Kept for the page. pub verified: bool, } /// Download the update APK into the app's cache, with progress events, and -/// check it. `sha256` is the release's hash for this APK when latest.json has -/// one; a mismatch deletes the file and fails. A download that was cut off -/// carries on where it stopped (`update_fetch`, which is the desktop's path too). +/// check it. `url` must be the APK the last check offered, and it must match the +/// SHA-256 latest.json published for it (`updates::offered_sha256`); `sha256`, the +/// page's copy of that hash, is not what counts. A mismatch deletes the file and +/// fails. A download that was cut off carries on where it stopped (`update_fetch`, +/// which is the desktop's path too). #[tauri::command] pub async fn update_download_apk( app: AppHandle, @@ -156,19 +152,14 @@ pub async fn update_download_apk( serde_json::json!({ "url": url }), )); } - if !is_apk_filename(&filename) { + let _ = sha256; + let expected = super::updates::offered_sha256(&url)?; + if !is_apk_filename(&filename) || filename != super::updates::offered_file_name(&url) { return Err(coded( "update_bad_name", serde_json::json!({ "name": filename }), )); } - let expected = match sha256.as_deref().map(str::trim).filter(|s| !s.is_empty()) { - Some(raw) => Some( - normalize_sha256(raw) - .ok_or_else(|| coded("update_bad_checksum", serde_json::json!({ "value": raw })))?, - ), - None => None, - }; let active = super::update_fetch::ActiveDownload::begin()?; let dir = updates_dir(&app)?; remove_others(&dir, &filename); @@ -176,13 +167,13 @@ pub async fn update_download_apk( // Already downloaded and verified once: hand it over again (the person // cancelled Android's dialog and tapped again). - if let (Some(want), Ok(meta)) = (&expected, std::fs::metadata(&target)) { + if let Ok(meta) = std::fs::metadata(&target) { let t = target.clone(); let actual = tokio::task::spawn_blocking(move || super::update_fetch::sha256_file(&t)) .await .ok() .and_then(Result::ok); - if actual.as_ref() == Some(want) { + if actual.as_ref() == Some(&expected) { return Ok(ApkDownload { path: target.to_string_lossy().into_owned(), bytes: meta.len(), @@ -202,7 +193,7 @@ pub async fn update_download_apk( &url, &part, APK_MAX_BYTES, - expected.as_deref(), + Some(&expected), active.cancel_signal(), &mut report, ) @@ -231,7 +222,7 @@ pub async fn update_download_apk( Ok(ApkDownload { path: target.to_string_lossy().into_owned(), bytes: done.bytes, - verified: expected.is_some(), + verified: true, }) } @@ -273,19 +264,6 @@ mod tests { ); } - #[test] - fn sha256_must_be_64_hex_chars() { - let good = "A".repeat(64); - assert_eq!(normalize_sha256(&good), Some("a".repeat(64))); - assert_eq!( - normalize_sha256(&format!(" {} ", "0f".repeat(32))), - Some("0f".repeat(32)) - ); - assert_eq!(normalize_sha256(&"a".repeat(63)), None); - assert_eq!(normalize_sha256(&"g".repeat(64)), None); - assert_eq!(normalize_sha256(""), None); - } - #[test] fn only_plain_apk_names_are_accepted() { assert!(is_apk_filename("PS5Upload-android.apk")); diff --git a/client/src-tauri/src/commands/updates.rs b/client/src-tauri/src/commands/updates.rs index 9dbf3de26..b20ab9543 100644 --- a/client/src-tauri/src/commands/updates.rs +++ b/client/src-tauri/src/commands/updates.rs @@ -37,12 +37,15 @@ //! //! `sha256` (since 10.2) has the same keys as `assets`; `update_download` checks the file //! against it before the update is offered for install, and deletes a file that does not -//! match. A manifest without it (an older release) is downloaded unchecked, as before. +//! match. The URL and the hash are the ones `update_check` read from the manifest itself, not +//! what the renderer hands back; a file the manifest publishes no hash for is not downloaded, +//! and an install starts only a file that matched its hash and still does. //! //! Missing platforms → the renderer reports "up to date" to users on //! that arch (same as if no new version exists for them). -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager}; @@ -156,9 +159,87 @@ fn expected_sha256(raw: Option<&str>) -> Result, String> { } } -/// Writes one line to stderr without panicking when it is gone (a `println!` would). -fn log_line(args: std::fmt::Arguments<'_>) { - let _ = std::io::Write::write_fmt(&mut std::io::stderr(), args); +// ── what a check offered, and what a download checked ─────────────────── + +/// The release files `update_check` offered in this run, newest last: URL and the manifest's +/// SHA-256 for it (empty when it publishes none). The renderer hands the URL and the hash back +/// to `update_download`; taken at its word, a page script could point the updater at any file +/// on a pinned host (any GitHub release of anyone) with a hash to match, and have it installed. +static OFFERED: Mutex> = Mutex::new(Vec::new()); + +/// How many offers (and checked downloads) are kept: a check per channel, again after a while. +const OFFERS_KEPT: usize = 8; + +fn remember_offer(url: &str, sha256: &str) { + if url.is_empty() { + return; + } + let mut offered = OFFERED.lock().unwrap_or_else(|e| e.into_inner()); + offered.retain(|(u, _)| u != url); + offered.push((url.to_string(), sha256.to_string())); + let over = offered.len().saturating_sub(OFFERS_KEPT); + offered.drain(..over); +} + +/// The SHA-256 a download of `url` must match: the one the release published for the file a +/// check offered. Refused: a URL no check offered (`update_unsafe_url`), a file the release +/// gives no checksum for (`update_no_checksum`; every release since 10.2 has one), a checksum +/// that is not one (`update_bad_checksum`). +pub(crate) fn offered_sha256(url: &str) -> Result { + let sha = OFFERED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .rev() + .find(|(u, _)| u == url) + .map(|(_, sha)| sha.clone()) + .ok_or_else(|| coded("update_unsafe_url", serde_json::json!({ "url": url })))?; + expected_sha256(Some(&sha))? + .ok_or_else(|| coded("update_no_checksum", serde_json::json!({ "url": url }))) +} + +/// The file name a download of `url` is saved under: the last part of the URL, as +/// `update_check` gives it. +pub(crate) fn offered_file_name(url: &str) -> &str { + url.rsplit('/').next().unwrap_or("") +} + +/// Downloads that matched their release's SHA-256 in this run: path and hash. An install starts +/// only one of these, hashed again first ([`check_verified`]). +static VERIFIED: Mutex> = Mutex::new(Vec::new()); + +pub(crate) fn remember_verified(path: &Path, sha256: &str) { + let mut verified = VERIFIED.lock().unwrap_or_else(|e| e.into_inner()); + verified.retain(|(p, _)| p != path); + verified.push((path.to_path_buf(), sha256.to_string())); + let over = verified.len().saturating_sub(OFFERS_KEPT); + verified.drain(..over); +} + +/// Ok when `path` is a download that matched its release's SHA-256 and still does: what an +/// install may start. Reads the whole file, so not on an async worker. +pub(crate) fn check_verified(path: &Path) -> Result<(), String> { + let want = VERIFIED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .rev() + .find(|(p, _)| p == path) + .map(|(_, sha)| sha.clone()) + .ok_or_else(|| format!("{} was not checked against its release", path.display()))?; + let got = super::update_fetch::sha256_file(path).map_err(|e| { + coded( + "update_disk", + serde_json::json!({ "detail": format!("{}: {e}", path.display()) }), + ) + })?; + if got != want { + return Err(coded( + "update_checksum", + serde_json::json!({ "expected": want, "actual": got }), + )); + } + Ok(()) } /// Platform key used in the manifest. Matches the format tauri-plugin- @@ -659,7 +740,8 @@ pub async fn update_check(app: AppHandle, channel: Option) -> Result Option { - let resp = client.head(url).send().await.ok()?; - if !resp.status().is_success() { - return None; - } - resp.headers() - .get(reqwest::header::CONTENT_LENGTH)? - .to_str() - .ok()? - .parse() - .ok() -} - /// What the renderer gets for the update file now at `target`. `reveal` is best-effort: the file /// is complete on disk, so a file manager that fails to open (a sandboxed session, no display /// server) must not read as a failed download. A copy that installs the file itself shows @@ -852,6 +920,10 @@ async fn finished_download( /// there is reused when it matches the release; a transfer that was cut off carries on where it /// stopped (`update_fetch`). Progress goes out as `DOWNLOAD_PROGRESS_EVENT`, and /// `update_download_cancel` stops it. +/// +/// `url` must be the file a check offered, and the file must match the SHA-256 the manifest +/// published for it ([`offered_sha256`]). `sha256`, the renderer's copy of that hash, is not +/// what counts. #[tauri::command] pub async fn update_download( app: AppHandle, @@ -859,10 +931,11 @@ pub async fn update_download( filename: String, sha256: Option, ) -> Result { - let expected = expected_sha256(sha256.as_deref())?; + let _ = sha256; if url.is_empty() { return Err(code_only("update_no_bundle")); } + let expected = offered_sha256(&url)?; // Mirror the manifest-fetch scheme requirement. The download URL // comes from the remote manifest and we verify TLS via rustls, but // if a future misconfiguration ever let a plain-http URL slip into @@ -884,7 +957,8 @@ pub async fn update_download( // - NUL rules out C-string early-terminators (would still fail on // create, but the error would be confusing). // - leading dot rules out hidden-file shenanigans. - if !is_plain_file_name(&filename) { + // The name the check gave for this URL, and nothing else: the install plan goes by it. + if !is_plain_file_name(&filename) || filename != offered_file_name(&url) { return Err(coded( "update_bad_name", serde_json::json!({ "name": filename }), @@ -915,27 +989,18 @@ pub async fn update_download( // A complete copy from a prior run: we stream to `.part` and rename only after the // file checked out, so `target` existing at all means an earlier call finished. It is reused - // when it matches the published checksum (a release before 10.2 publishes none: when it has - // the size the server gives, or the server gives none, without which every click would - // download the same bundle again). One that does not match (a different build under the same - // name, a damaged file) is deleted and downloaded again. + // when it matches the published checksum; one that does not (a different build under the + // same name, a damaged file) is deleted and downloaded again. if let Ok(meta) = std::fs::metadata(&target) { - let reuse = match &expected { - Some(exp) => { - let t = target.clone(); - tokio::task::spawn_blocking(move || super::update_fetch::sha256_file(&t)) - .await - .ok() - .and_then(Result::ok) - .is_some_and(|actual| actual == *exp) - } - None => match published_size(&client, &url).await { - Some(size) => size == meta.len(), - None => meta.len() > 0, - }, - }; + let t = target.clone(); + let reuse = tokio::task::spawn_blocking(move || super::update_fetch::sha256_file(&t)) + .await + .ok() + .and_then(Result::ok) + .is_some_and(|actual| actual == expected); if reuse { - return finished_download(target, meta.len(), expected.is_some()).await; + remember_verified(&target, &expected); + return finished_download(target, meta.len(), true).await; } let _ = std::fs::remove_file(&target); } @@ -953,17 +1018,11 @@ pub async fn update_download( &url, &part, DOWNLOAD_MAX_BYTES, - expected.as_deref(), + Some(&expected), active.cancel_signal(), &mut report, ) .await?; - if expected.is_none() { - log_line(format_args!( - "[updates] the manifest publishes no SHA-256 for {filename} (a release before 10.2): not verified, sha256={}\n", - done.sha256 - )); - } // In the updates folder this is now the one update waiting: earlier versions' downloads go. let in_updates_folder = super::update_files::updates_dir(&app).is_ok_and(|d| d == dl_dir); let (from, to) = (part, target.clone()); @@ -978,7 +1037,8 @@ pub async fn update_download( .map_err(|e| e.to_string()) .and_then(|r| r.map_err(|e| e.to_string())) .map_err(|detail| coded("update_disk", serde_json::json!({ "detail": detail })))?; - finished_download(target, done.bytes, expected.is_some()).await + remember_verified(&target, &done.sha256); + finished_download(target, done.bytes, true).await } /// A bare file name to save an update as: no path separators, no `.` / `..`, no hidden file, @@ -1147,6 +1207,75 @@ mod checksum_tests { ); } + fn code_of(e: &str) -> String { + let v: serde_json::Value = serde_json::from_str(e).unwrap_or_default(); + v["code"].as_str().unwrap_or(e).to_string() + } + + /// A download takes only the file a check offered, with the hash the manifest published for + /// it: the renderer's word for the URL or the hash counts for nothing. + #[test] + fn a_download_is_only_of_a_file_a_check_offered_with_its_hash() { + let url = "https://github.com/phantomptr/ps5upload/releases/download/v9/offered-a.zip"; + // Never offered: not downloaded, whatever hash comes with it. + assert_eq!( + code_of(&offered_sha256(url).unwrap_err()), + "update_unsafe_url" + ); + // Offered with no checksum (a release before 10.2): not downloaded unchecked. + remember_offer(url, ""); + assert_eq!( + code_of(&offered_sha256(url).unwrap_err()), + "update_no_checksum" + ); + // With a broken one: refused as that. + remember_offer(url, "abc"); + assert_eq!( + code_of(&offered_sha256(url).unwrap_err()), + "update_bad_checksum" + ); + // The newest offer for the URL is what counts, normalised. + remember_offer(url, &"AB".repeat(32)); + assert_eq!(offered_sha256(url).unwrap(), "ab".repeat(32)); + assert_eq!(offered_file_name(url), "offered-a.zip"); + // Another release's file on the same host was never offered. + let other = "https://github.com/someone/else/releases/download/v1/offered-a.zip"; + assert_eq!( + code_of(&offered_sha256(other).unwrap_err()), + "update_unsafe_url" + ); + } + + /// An install starts only a download that matched its release's hash, and only while it + /// still does: a file put or changed in the updates folder afterwards is refused. + #[test] + fn an_install_starts_only_a_checked_file_that_is_unchanged() { + use sha2::Digest; + let dir = std::env::temp_dir().join(format!("ps5upload-verified-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("PS5Upload-9.9.9-mac-arm64.dmg"); + std::fs::write(&file, b"the release").unwrap(); + // Never checked. + assert!(check_verified(&file).is_err()); + let sha: String = sha2::Sha256::digest(b"the release") + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + remember_verified(&file, &sha); + assert_eq!(check_verified(&file), Ok(())); + // Changed since: refused, as a checksum mismatch. + std::fs::write(&file, b"something else").unwrap(); + assert_eq!( + code_of(&check_verified(&file).unwrap_err()), + "update_checksum" + ); + // Another file in the same folder was never checked. + let other = dir.join("PS5Upload-9.9.9-mac-x64.dmg"); + std::fs::write(&other, b"the release").unwrap(); + assert!(check_verified(&other).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn expected_checksums_are_normalised_or_refused() { assert_eq!(expected_sha256(None), Ok(None)); diff --git a/client/src/i18n/locales/ar.ts b/client/src/i18n/locales/ar.ts index 9e7cceb71..deccf4253 100644 --- a/client/src/i18n/locales/ar.ts +++ b/client/src/i18n/locales/ar.ts @@ -216,6 +216,7 @@ update_err_no_bundle: "لا يتوفر في هذا الإصدار ملف تنز update_err_unsafe_url: "عنوان التحديث ليس من العناوين التي يثق بها PS5Upload، لذا لم يُنزَّل شيء.", update_err_bad_name: "اسم ملف التحديث غير صالح، لذا لم يُنزَّل شيء.", update_err_bad_checksum: "يذكر هذا الإصدار مجموع تحقق تالفًا لهذا الملف، لذا لم يُنزَّل شيء.", +update_err_no_checksum: "لا يذكر هذا الإصدار مجموع تحقق لهذا الملف، لذا لم يُنزَّل شيء.", update_err_too_large: "الملف أكبر من أن يكون إصدارًا من PS5Upload، لذا لم يُنزَّل.", update_err_interrupted: "انقطع الاتصال. حاول مجددًا: سيكمل التنزيل من حيث توقف.", update_err_checksum: "لا يطابق الملف المنزَّل مجموع التحقق لهذا الإصدار. حُذف الملف ولم يُثبَّت شيء. حاول مجددًا.", diff --git a/client/src/i18n/locales/bn.ts b/client/src/i18n/locales/bn.ts index 866059b8b..6d3932e0d 100644 --- a/client/src/i18n/locales/bn.ts +++ b/client/src/i18n/locales/bn.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "এই রিলিজে আপনার সিস্ট update_err_unsafe_url: "আপডেটের ঠিকানাটি PS5Upload বিশ্বাস করে না, তাই কিছু ডাউনলোড হয়নি।", update_err_bad_name: "আপডেটের ফাইলের নাম সঠিক নয়, তাই কিছু ডাউনলোড হয়নি।", update_err_bad_checksum: "এই রিলিজে ফাইলটির চেকসাম ভুল লেখা আছে, তাই কিছু ডাউনলোড হয়নি।", +update_err_no_checksum: "এই রিলিজে ফাইলটির কোনো চেকসাম নেই, তাই কিছু ডাউনলোড হয়নি।", update_err_too_large: "ফাইলটি PS5Upload রিলিজ হওয়ার পক্ষে খুব বড়, তাই ডাউনলোড হয়নি।", update_err_interrupted: "সংযোগ বিচ্ছিন্ন হয়েছে। আবার চেষ্টা করুন: ডাউনলোড যেখানে থেমেছিল সেখান থেকে চলবে।", update_err_checksum: "ডাউনলোডটি এই রিলিজের চেকসামের সঙ্গে মেলে না। এটি মুছে ফেলা হয়েছে এবং কিছু ইনস্টল হয়নি। আবার চেষ্টা করুন।", diff --git a/client/src/i18n/locales/de.ts b/client/src/i18n/locales/de.ts index 0fc96337d..c354a14b9 100644 --- a/client/src/i18n/locales/de.ts +++ b/client/src/i18n/locales/de.ts @@ -222,6 +222,7 @@ update_err_no_bundle: "Diese Version enthält keinen Download für dein System." update_err_unsafe_url: "PS5Upload vertraut der Update-Adresse nicht, daher wurde nichts heruntergeladen.", update_err_bad_name: "Der Dateiname des Updates ist ungültig, daher wurde nichts heruntergeladen.", update_err_bad_checksum: "Diese Version nennt eine fehlerhafte Prüfsumme für die Datei, daher wurde nichts heruntergeladen.", +update_err_no_checksum: "Diese Version nennt keine Prüfsumme für die Datei, daher wurde nichts heruntergeladen.", update_err_too_large: "Die Datei ist zu groß für eine PS5Upload-Version und wurde nicht heruntergeladen.", update_err_interrupted: "Die Verbindung wurde unterbrochen. Versuche es erneut: Der Download macht dort weiter, wo er aufgehört hat.", update_err_checksum: "Der Download passt nicht zur Prüfsumme dieser Version. Er wurde gelöscht, nichts wurde installiert. Versuche es erneut.", diff --git a/client/src/i18n/locales/en.ts b/client/src/i18n/locales/en.ts index c64f97714..06abacb6c 100644 --- a/client/src/i18n/locales/en.ts +++ b/client/src/i18n/locales/en.ts @@ -388,6 +388,7 @@ update_err_no_bundle: "This release has no download for your system.", update_err_unsafe_url: "The update address isn't one PS5Upload trusts, so nothing was downloaded.", update_err_bad_name: "The update's file name isn't valid, so nothing was downloaded.", update_err_bad_checksum: "The release lists a broken checksum for this file, so nothing was downloaded.", +update_err_no_checksum: "This release lists no checksum for this file, so nothing was downloaded.", update_err_too_large: "The file is too large to be a PS5Upload release, so it wasn't downloaded.", update_err_interrupted: "The connection was lost. Try again: the download carries on where it stopped.", update_err_checksum: "The download doesn't match this release's checksum. It was deleted and nothing was installed. Try again.", diff --git a/client/src/i18n/locales/es.ts b/client/src/i18n/locales/es.ts index 7372a14fb..2a2c6bc47 100644 --- a/client/src/i18n/locales/es.ts +++ b/client/src/i18n/locales/es.ts @@ -216,6 +216,7 @@ update_err_no_bundle: "Esta versión no tiene descarga para tu sistema.", update_err_unsafe_url: "PS5Upload no confía en la dirección de la actualización, así que no se descargó nada.", update_err_bad_name: "El nombre de archivo de la actualización no es válido, así que no se descargó nada.", update_err_bad_checksum: "Esta versión indica una suma de comprobación incorrecta para el archivo, así que no se descargó nada.", +update_err_no_checksum: "Esta versión no indica ninguna suma de comprobación para el archivo, así que no se descargó nada.", update_err_too_large: "El archivo es demasiado grande para ser una versión de PS5Upload, así que no se descargó.", update_err_interrupted: "Se perdió la conexión. Inténtalo de nuevo: la descarga sigue donde se detuvo.", update_err_checksum: "La descarga no coincide con la suma de comprobación de esta versión. Se eliminó y no se instaló nada. Inténtalo de nuevo.", diff --git a/client/src/i18n/locales/fa.ts b/client/src/i18n/locales/fa.ts index 0de41b904..1d0fcc9fa 100644 --- a/client/src/i18n/locales/fa.ts +++ b/client/src/i18n/locales/fa.ts @@ -358,6 +358,7 @@ update_err_no_bundle: "این نسخه دانلودی برای سیستم شما update_err_unsafe_url: "PS5Upload به نشانی به‌روزرسانی اعتماد ندارد، پس چیزی دانلود نشد.", update_err_bad_name: "نام فایل به‌روزرسانی معتبر نیست، پس چیزی دانلود نشد.", update_err_bad_checksum: "این نسخه برای فایل، جمع کنترلی نادرستی اعلام کرده است، پس چیزی دانلود نشد.", +update_err_no_checksum: "این نسخه برای فایل هیچ جمع کنترلی اعلام نکرده است، پس چیزی دانلود نشد.", update_err_too_large: "این فایل برای نسخه‌ای از PS5Upload بیش از حد بزرگ است، پس دانلود نشد.", update_err_interrupted: "اتصال قطع شد. دوباره تلاش کنید: دانلود از همان‌جا ادامه می‌یابد.", update_err_checksum: "فایل دانلودشده با جمع کنترلی این نسخه مطابقت ندارد. حذف شد و چیزی نصب نشد. دوباره تلاش کنید.", diff --git a/client/src/i18n/locales/fr.ts b/client/src/i18n/locales/fr.ts index f34cb27c3..ac5795fc6 100644 --- a/client/src/i18n/locales/fr.ts +++ b/client/src/i18n/locales/fr.ts @@ -216,6 +216,7 @@ update_err_no_bundle: "Cette version ne propose pas de téléchargement pour vot update_err_unsafe_url: "PS5Upload ne fait pas confiance à l'adresse de la mise à jour : rien n'a été téléchargé.", update_err_bad_name: "Le nom de fichier de la mise à jour n'est pas valide : rien n'a été téléchargé.", update_err_bad_checksum: "Cette version indique une somme de contrôle incorrecte pour ce fichier : rien n'a été téléchargé.", +update_err_no_checksum: "Cette version n'indique aucune somme de contrôle pour ce fichier : rien n'a été téléchargé.", update_err_too_large: "Le fichier est trop volumineux pour être une version de PS5Upload : il n'a pas été téléchargé.", update_err_interrupted: "La connexion a été perdue. Réessayez : le téléchargement reprend là où il s'est arrêté.", update_err_checksum: "Le téléchargement ne correspond pas à la somme de contrôle de cette version. Il a été supprimé et rien n'a été installé. Réessayez.", diff --git a/client/src/i18n/locales/hi.ts b/client/src/i18n/locales/hi.ts index 21f83b83c..a44ea8a11 100644 --- a/client/src/i18n/locales/hi.ts +++ b/client/src/i18n/locales/hi.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "इस रिलीज़ में आपके सि update_err_unsafe_url: "PS5Upload को अपडेट के पते पर भरोसा नहीं है, इसलिए कुछ डाउनलोड नहीं हुआ।", update_err_bad_name: "अपडेट की फ़ाइल का नाम मान्य नहीं है, इसलिए कुछ डाउनलोड नहीं हुआ।", update_err_bad_checksum: "इस रिलीज़ में फ़ाइल का चेकसम ग़लत लिखा है, इसलिए कुछ डाउनलोड नहीं हुआ।", +update_err_no_checksum: "इस रिलीज़ में फ़ाइल का कोई चेकसम नहीं है, इसलिए कुछ डाउनलोड नहीं हुआ।", update_err_too_large: "फ़ाइल PS5Upload रिलीज़ होने के लिए बहुत बड़ी है, इसलिए डाउनलोड नहीं हुई।", update_err_interrupted: "कनेक्शन टूट गया। फिर से कोशिश करें: डाउनलोड वहीं से आगे बढ़ेगा जहाँ रुका था।", update_err_checksum: "डाउनलोड इस रिलीज़ के चेकसम से मेल नहीं खाता। उसे हटा दिया गया और कुछ इंस्टॉल नहीं हुआ। फिर से कोशिश करें।", diff --git a/client/src/i18n/locales/hu.ts b/client/src/i18n/locales/hu.ts index 262c9747f..4aa74b463 100644 --- a/client/src/i18n/locales/hu.ts +++ b/client/src/i18n/locales/hu.ts @@ -361,6 +361,7 @@ update_err_no_bundle: "Ebben a kiadásban nincs letöltés a rendszeredhez.", update_err_unsafe_url: "A PS5Upload nem bízik a frissítés címében, ezért nem töltött le semmit.", update_err_bad_name: "A frissítés fájlneve érvénytelen, ezért nem töltött le semmit.", update_err_bad_checksum: "A kiadás hibás ellenőrzőösszeget ad meg ehhez a fájlhoz, ezért nem töltött le semmit.", +update_err_no_checksum: "A kiadás nem ad meg ellenőrzőösszeget ehhez a fájlhoz, ezért nem töltött le semmit.", update_err_too_large: "A fájl túl nagy ahhoz, hogy PS5Upload-kiadás legyen, ezért nem töltötte le.", update_err_interrupted: "Megszakadt a kapcsolat. Próbáld újra: a letöltés onnan folytatódik, ahol abbamaradt.", update_err_checksum: "A letöltés nem egyezik a kiadás ellenőrzőösszegével. Törölve lett, és semmi sem települt. Próbáld újra.", diff --git a/client/src/i18n/locales/id.ts b/client/src/i18n/locales/id.ts index 0b1298286..286545d20 100644 --- a/client/src/i18n/locales/id.ts +++ b/client/src/i18n/locales/id.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "Rilis ini tidak punya unduhan untuk sistem Anda.", update_err_unsafe_url: "PS5Upload tidak memercayai alamat pembaruan, jadi tidak ada yang diunduh.", update_err_bad_name: "Nama file pembaruan tidak valid, jadi tidak ada yang diunduh.", update_err_bad_checksum: "Rilis ini mencantumkan checksum yang rusak untuk file ini, jadi tidak ada yang diunduh.", +update_err_no_checksum: "Rilis ini tidak mencantumkan checksum untuk file ini, jadi tidak ada yang diunduh.", update_err_too_large: "File terlalu besar untuk sebuah rilis PS5Upload, jadi tidak diunduh.", update_err_interrupted: "Koneksi terputus. Coba lagi: unduhan berlanjut dari titik terakhir.", update_err_checksum: "Unduhan tidak cocok dengan checksum rilis ini. File dihapus dan tidak ada yang dipasang. Coba lagi.", diff --git a/client/src/i18n/locales/it.ts b/client/src/i18n/locales/it.ts index 27e9b91f6..469a3d53a 100644 --- a/client/src/i18n/locales/it.ts +++ b/client/src/i18n/locales/it.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "Questa versione non ha un download per il tuo sistema.", update_err_unsafe_url: "PS5Upload non si fida dell'indirizzo dell'aggiornamento, quindi non è stato scaricato nulla.", update_err_bad_name: "Il nome del file dell'aggiornamento non è valido, quindi non è stato scaricato nulla.", update_err_bad_checksum: "Questa versione indica un checksum errato per il file, quindi non è stato scaricato nulla.", +update_err_no_checksum: "Questa versione non indica alcun checksum per il file, quindi non è stato scaricato nulla.", update_err_too_large: "Il file è troppo grande per essere una versione di PS5Upload, quindi non è stato scaricato.", update_err_interrupted: "La connessione si è interrotta. Riprova: il download riprende da dove si era fermato.", update_err_checksum: "Il download non corrisponde al checksum di questa versione. È stato eliminato e non è stato installato nulla. Riprova.", diff --git a/client/src/i18n/locales/ja.ts b/client/src/i18n/locales/ja.ts index b98cd5f9e..4eb5b37cc 100644 --- a/client/src/i18n/locales/ja.ts +++ b/client/src/i18n/locales/ja.ts @@ -222,6 +222,7 @@ update_err_no_bundle: "このリリースにはお使いのシステム向けの update_err_unsafe_url: "PS5Upload が信頼しないアップデート先のため、何もダウンロードしませんでした。", update_err_bad_name: "アップデートのファイル名が正しくないため、何もダウンロードしませんでした。", update_err_bad_checksum: "このリリースに記載されたチェックサムが壊れているため、何もダウンロードしませんでした。", +update_err_no_checksum: "このリリースにはこのファイルのチェックサムがないため、何もダウンロードしませんでした。", update_err_too_large: "PS5Upload のリリースとしては大きすぎるファイルのため、ダウンロードしませんでした。", update_err_interrupted: "接続が切れました。もう一度試してください。ダウンロードは止まった所から再開します。", update_err_checksum: "ダウンロードがこのリリースのチェックサムと一致しません。削除し、何もインストールしていません。もう一度試してください。", diff --git a/client/src/i18n/locales/ko.ts b/client/src/i18n/locales/ko.ts index 85638b7c5..d1ef22208 100644 --- a/client/src/i18n/locales/ko.ts +++ b/client/src/i18n/locales/ko.ts @@ -222,6 +222,7 @@ update_err_no_bundle: "이 릴리스에는 사용 중인 시스템용 다운로 update_err_unsafe_url: "PS5Upload가 신뢰하지 않는 업데이트 주소라서 아무것도 다운로드하지 않았습니다.", update_err_bad_name: "업데이트 파일 이름이 올바르지 않아 아무것도 다운로드하지 않았습니다.", update_err_bad_checksum: "이 릴리스에 적힌 체크섬이 손상되어 아무것도 다운로드하지 않았습니다.", +update_err_no_checksum: "이 릴리스에 이 파일의 체크섬이 없어 아무것도 다운로드하지 않았습니다.", update_err_too_large: "PS5Upload 릴리스라고 하기에는 파일이 너무 커서 다운로드하지 않았습니다.", update_err_interrupted: "연결이 끊겼습니다. 다시 시도하세요. 다운로드는 멈춘 곳에서 이어집니다.", update_err_checksum: "다운로드가 이 릴리스의 체크섬과 일치하지 않습니다. 파일을 삭제했고 아무것도 설치하지 않았습니다. 다시 시도하세요.", diff --git a/client/src/i18n/locales/pl.ts b/client/src/i18n/locales/pl.ts index 9d1bf905f..3313e66e3 100644 --- a/client/src/i18n/locales/pl.ts +++ b/client/src/i18n/locales/pl.ts @@ -352,6 +352,7 @@ update_err_no_bundle: "To wydanie nie ma pliku do pobrania dla twojego systemu." update_err_unsafe_url: "PS5Upload nie ufa adresowi aktualizacji, więc nic nie pobrano.", update_err_bad_name: "Nazwa pliku aktualizacji jest nieprawidłowa, więc nic nie pobrano.", update_err_bad_checksum: "To wydanie podaje błędną sumę kontrolną tego pliku, więc nic nie pobrano.", +update_err_no_checksum: "To wydanie nie podaje sumy kontrolnej tego pliku, więc nic nie pobrano.", update_err_too_large: "Plik jest za duży jak na wydanie PS5Upload, więc go nie pobrano.", update_err_interrupted: "Połączenie zostało przerwane. Spróbuj ponownie: pobieranie wznowi się od miejsca przerwania.", update_err_checksum: "Pobrany plik nie zgadza się z sumą kontrolną tego wydania. Został usunięty i nic nie zainstalowano. Spróbuj ponownie.", diff --git a/client/src/i18n/locales/pt-BR.ts b/client/src/i18n/locales/pt-BR.ts index 798ce1c73..1292241a9 100644 --- a/client/src/i18n/locales/pt-BR.ts +++ b/client/src/i18n/locales/pt-BR.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "Esta versão não tem download para o seu sistema.", update_err_unsafe_url: "O PS5Upload não confia no endereço da atualização, então nada foi baixado.", update_err_bad_name: "O nome do arquivo da atualização não é válido, então nada foi baixado.", update_err_bad_checksum: "Esta versão informa um checksum inválido para o arquivo, então nada foi baixado.", +update_err_no_checksum: "Esta versão não informa um checksum para o arquivo, então nada foi baixado.", update_err_too_large: "O arquivo é grande demais para ser uma versão do PS5Upload, então não foi baixado.", update_err_interrupted: "A conexão caiu. Tente de novo: o download continua de onde parou.", update_err_checksum: "O download não confere com o checksum desta versão. Ele foi apagado e nada foi instalado. Tente de novo.", diff --git a/client/src/i18n/locales/ru.ts b/client/src/i18n/locales/ru.ts index 43712a185..5cb31d9ab 100644 --- a/client/src/i18n/locales/ru.ts +++ b/client/src/i18n/locales/ru.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "В этом выпуске нет загрузки для update_err_unsafe_url: "PS5Upload не доверяет адресу обновления, поэтому ничего не загружено.", update_err_bad_name: "Имя файла обновления недопустимо, поэтому ничего не загружено.", update_err_bad_checksum: "В этом выпуске указана неверная контрольная сумма файла, поэтому ничего не загружено.", +update_err_no_checksum: "В этом выпуске нет контрольной суммы файла, поэтому ничего не загружено.", update_err_too_large: "Файл слишком велик для выпуска PS5Upload, поэтому он не загружен.", update_err_interrupted: "Соединение прервалось. Попробуйте снова: загрузка продолжится с того же места.", update_err_checksum: "Загруженный файл не совпадает с контрольной суммой этого выпуска. Он удалён, ничего не установлено. Попробуйте снова.", diff --git a/client/src/i18n/locales/th.ts b/client/src/i18n/locales/th.ts index 554ede62b..787f5902d 100644 --- a/client/src/i18n/locales/th.ts +++ b/client/src/i18n/locales/th.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "รุ่นนี้ไม่มีไฟล์ดาว update_err_unsafe_url: "PS5Upload ไม่เชื่อถือที่อยู่ของอัปเดต จึงไม่ได้ดาวน์โหลดอะไร", update_err_bad_name: "ชื่อไฟล์ของอัปเดตไม่ถูกต้อง จึงไม่ได้ดาวน์โหลดอะไร", update_err_bad_checksum: "รุ่นนี้ระบุเช็กซัมของไฟล์ไม่ถูกต้อง จึงไม่ได้ดาวน์โหลดอะไร", +update_err_no_checksum: "รุ่นนี้ไม่ได้ระบุเช็กซัมของไฟล์ จึงไม่ได้ดาวน์โหลดอะไร", update_err_too_large: "ไฟล์ใหญ่เกินกว่าจะเป็นรุ่นของ PS5Upload จึงไม่ได้ดาวน์โหลด", update_err_interrupted: "การเชื่อมต่อหลุด ลองใหม่อีกครั้ง การดาวน์โหลดจะทำต่อจากจุดที่หยุด", update_err_checksum: "ไฟล์ที่ดาวน์โหลดไม่ตรงกับเช็กซัมของรุ่นนี้ จึงลบทิ้งและไม่ได้ติดตั้งอะไร ลองใหม่อีกครั้ง", diff --git a/client/src/i18n/locales/tr.ts b/client/src/i18n/locales/tr.ts index 32bc68735..98dd17aa0 100644 --- a/client/src/i18n/locales/tr.ts +++ b/client/src/i18n/locales/tr.ts @@ -221,6 +221,7 @@ update_err_no_bundle: "Bu sürümde sisteminiz için indirme yok.", update_err_unsafe_url: "PS5Upload güncelleme adresine güvenmiyor, bu yüzden hiçbir şey indirilmedi.", update_err_bad_name: "Güncellemenin dosya adı geçersiz, bu yüzden hiçbir şey indirilmedi.", update_err_bad_checksum: "Bu sürüm dosya için bozuk bir sağlama toplamı bildiriyor, bu yüzden hiçbir şey indirilmedi.", +update_err_no_checksum: "Bu sürüm dosya için bir sağlama toplamı bildirmiyor, bu yüzden hiçbir şey indirilmedi.", update_err_too_large: "Dosya bir PS5Upload sürümü olamayacak kadar büyük, bu yüzden indirilmedi.", update_err_interrupted: "Bağlantı kesildi. Yeniden deneyin: indirme kaldığı yerden devam eder.", update_err_checksum: "İndirilen dosya bu sürümün sağlama toplamıyla eşleşmiyor. Silindi ve hiçbir şey yüklenmedi. Yeniden deneyin.", diff --git a/client/src/i18n/locales/vi.ts b/client/src/i18n/locales/vi.ts index 39c12bc59..c7dfb92a4 100644 --- a/client/src/i18n/locales/vi.ts +++ b/client/src/i18n/locales/vi.ts @@ -222,6 +222,7 @@ update_err_no_bundle: "Bản phát hành này không có tệp tải về cho h update_err_unsafe_url: "PS5Upload không tin địa chỉ cập nhật này nên chưa tải gì về.", update_err_bad_name: "Tên tệp cập nhật không hợp lệ nên chưa tải gì về.", update_err_bad_checksum: "Bản phát hành này ghi mã kiểm tra sai cho tệp nên chưa tải gì về.", +update_err_no_checksum: "Bản phát hành này không ghi mã kiểm tra cho tệp nên chưa tải gì về.", update_err_too_large: "Tệp quá lớn để là một bản phát hành PS5Upload nên không được tải về.", update_err_interrupted: "Mất kết nối. Hãy thử lại: lượt tải tiếp tục từ chỗ đã dừng.", update_err_checksum: "Tệp tải về không khớp mã kiểm tra của bản phát hành này. Tệp đã bị xóa và chưa cài gì. Hãy thử lại.", diff --git a/client/src/i18n/locales/zh-CN.ts b/client/src/i18n/locales/zh-CN.ts index 08b9d3314..7d9b1f09c 100644 --- a/client/src/i18n/locales/zh-CN.ts +++ b/client/src/i18n/locales/zh-CN.ts @@ -223,6 +223,7 @@ update_err_no_bundle: "此版本没有适用于你的系统的下载。", update_err_unsafe_url: "PS5Upload 不信任此更新地址,因此没有下载任何内容。", update_err_bad_name: "更新的文件名无效,因此没有下载任何内容。", update_err_bad_checksum: "此版本给出的文件校验和有误,因此没有下载任何内容。", +update_err_no_checksum: "此版本没有给出该文件的校验和,因此没有下载任何内容。", update_err_too_large: "这个文件太大,不可能是 PS5Upload 的版本,因此没有下载。", update_err_interrupted: "连接已断开。请重试:下载会从中断处继续。", update_err_checksum: "下载的文件与此版本的校验和不符。文件已删除,没有安装任何内容。请重试。", diff --git a/client/src/i18n/locales/zh-TW.ts b/client/src/i18n/locales/zh-TW.ts index 5e6d2a5bf..7fce80eb5 100644 --- a/client/src/i18n/locales/zh-TW.ts +++ b/client/src/i18n/locales/zh-TW.ts @@ -217,6 +217,7 @@ update_err_no_bundle: "此版本沒有適用於你系統的下載。", update_err_unsafe_url: "PS5Upload 不信任此更新位址,因此沒有下載任何內容。", update_err_bad_name: "更新的檔案名稱無效,因此沒有下載任何內容。", update_err_bad_checksum: "此版本提供的檔案檢查碼有誤,因此沒有下載任何內容。", +update_err_no_checksum: "此版本沒有提供該檔案的檢查碼,因此沒有下載任何內容。", update_err_too_large: "這個檔案太大,不可能是 PS5Upload 的版本,因此沒有下載。", update_err_interrupted: "連線已中斷。請重試:下載會從中斷處繼續。", update_err_checksum: "下載的檔案與此版本的檢查碼不符。檔案已刪除,沒有安裝任何內容。請重試。", diff --git a/client/src/lib/shellError.ts b/client/src/lib/shellError.ts index 4aefc9be0..22bd53954 100644 --- a/client/src/lib/shellError.ts +++ b/client/src/lib/shellError.ts @@ -46,6 +46,10 @@ const SIMPLE: Record = { "update_err_bad_checksum", "The release lists a broken checksum for this file, so nothing was downloaded.", ], + update_no_checksum: [ + "update_err_no_checksum", + "This release lists no checksum for this file, so nothing was downloaded.", + ], update_too_large: ["update_err_too_large", "The file is too large to be a PS5Upload release, so it wasn't downloaded."], update_interrupted: [ "update_err_interrupted", diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index 15707e037..c3f42bae2 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -8577,6 +8577,7 @@ "update_err_interrupted": "73a914a1 IXfCGlRKm2zAswKty2aEBFivI_O9cEssoaUBkPadhPTdrZfLV2xy4NOIXBh5", "update_err_network": "10b7285d qBWPp7ZAV8FQb7ARmGbK9SJ7rM_xUD-qjXgq27TWAv8XBQ5RgImhxPDAVRHE", "update_err_no_bundle": "bf80cd32 Ak1NJidO9c_JHX1z1KcocaULMIOQeZYRiNqI07tww14Hb6tmB4ZGnZu44-fy", + "update_err_no_checksum": "eb31bd8a b0v14dcA_ZBt3TSARtKs-DlPKjggADQKyDVJV_-puaTb8471Dd4SC_8wFJuS", "update_err_no_manifest": "d878f878 La0t-TrIUyKAD-e8LSxus6GPOfplAzjK8hFT5oRL6gumU_TLzt45O2NSLEy-", "update_err_not_apk": "990fa0bf TcDdT1eyLACIYwiqU7WZy1eNZJfu1HIg1taVXIJqS4goud0SfezPQbh2YH_w", "update_err_rate_limited": "116468bb E0963iwsFfuLp2wel67wvF-iV5XjAduI66N0jy7BS6NB1IVMm9e389Vdvdmt", From ee6fee323937b5df596778ef51a5e3487061eb54 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:54:36 -0800 Subject: [PATCH 12/27] Let the app's pages read only the files they show The asset protocol's scope was "**", so the page could load any file on the computer through an asset URL. It now covers only what the app shows from disk: the scratch folders it downloads previews and thumbnails into ($TEMP/ps5upload-save-*) and a game folder's cover (sce_sys/icon0.png). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/Cargo.lock | 1 + client/src-tauri/Cargo.toml | 5 ++ client/src-tauri/src/lib.rs | 92 ++++++++++++++++++++++++++++++++ client/src-tauri/tauri.conf.json | 3 +- 4 files changed, 100 insertions(+), 1 deletion(-) diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 9293fb8ce..1b73d0a58 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -4879,6 +4879,7 @@ dependencies = [ "evdev", "flate2", "futures-util", + "glob", "hidapi", "image", "jni 0.21.1", diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 30cfe005b..0688206ed 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -174,6 +174,11 @@ tokio = { version = "1", features = ["signal"] } # through wry. webkit2gtk-sys = "2" +[dev-dependencies] +# Matches the asset protocol's scope patterns the way Tauri does (asset_scope_tests in lib.rs). +# Already in the tree through Tauri. +glob = "0.3" + [features] # Default: build Tauri-native (no custom features yet) default = [] diff --git a/client/src-tauri/src/lib.rs b/client/src-tauri/src/lib.rs index 273fa6051..0e343eead 100644 --- a/client/src-tauri/src/lib.rs +++ b/client/src-tauri/src/lib.rs @@ -853,6 +853,98 @@ pub fn run() { }); } +#[cfg(test)] +mod asset_scope_tests { + use std::path::{Path, PathBuf}; + + /// The asset protocol's scope from tauri.conf.json, `$TEMP` resolved as Tauri resolves it + /// (`std::env::temp_dir`), each pattern also with its existing parent canonicalized, as + /// Tauri adds it. + fn scope() -> Vec { + let conf: serde_json::Value = + serde_json::from_str(include_str!("../tauri.conf.json")).unwrap(); + let mut out = Vec::new(); + for p in conf["app"]["security"]["assetProtocol"]["scope"] + .as_array() + .expect("the asset protocol has a scope") + { + let p = p.as_str().unwrap(); + let raw = match p.strip_prefix("$TEMP/") { + Some(rest) => std::env::temp_dir().join(rest), + None => PathBuf::from(p), + }; + out.push(glob::Pattern::new(&raw.to_string_lossy()).unwrap()); + let mut base = raw.clone(); + let mut tail = Vec::new(); + while let Some(name) = base.file_name().map(|n| n.to_os_string()) { + if let Ok(c) = base.canonicalize() { + let full = tail.iter().rev().fold(c, |acc: PathBuf, t| acc.join(t)); + out.push(glob::Pattern::new(&full.to_string_lossy()).unwrap()); + break; + } + tail.push(name); + base.pop(); + } + } + out + } + + /// Whether the asset protocol serves `path`: Tauri matches the canonical path, and a path + /// that does not exist is never served. + fn served(scope: &[glob::Pattern], path: &Path) -> bool { + let Ok(path) = path.canonicalize() else { + return false; + }; + let opts = glob::MatchOptions { + case_sensitive: true, + require_literal_separator: true, + require_literal_leading_dot: !cfg!(windows), + }; + scope.iter().any(|p| p.matches_path_with(&path, opts)) + } + + /// The asset protocol serves what the app shows from disk, and nothing else: the previews + /// and thumbnails it downloads into its own scratch folders, and a game folder's cover. + /// With `**` the page could read any file on the computer (a key, a browser profile). + #[test] + fn the_asset_protocol_serves_only_what_the_app_shows() { + let scope = scope(); + assert!( + !scope.iter().any(|p| p.as_str() == "**"), + "the scope must not be every file" + ); + // Previews (Screenshots, Videos, Captures) land in a scratch dir of `make_temp_dir`. + let scratch = ps5upload_core::save_archive::make_temp_dir("ss-preview").unwrap(); + let shot = scratch.join("shot.png"); + std::fs::write(&shot, b"png").unwrap(); + std::fs::create_dir_all(scratch.join("sub")).unwrap(); + let clip = scratch.join("sub").join("clip.mp4"); + std::fs::write(&clip, b"mp4").unwrap(); + // A game folder's cover (Upload), wherever the folder is. + let other = std::env::temp_dir().join(format!("ps5upload-scope-{}", std::process::id())); + let game = other.join("My Game").join("sce_sys"); + std::fs::create_dir_all(&game).unwrap(); + let icon = game.join("icon0.png"); + let param = game.join("param.json"); + let loose = other.join("notes.txt"); + for f in [&icon, ¶m, &loose] { + std::fs::write(f, b"x").unwrap(); + } + + assert!(served(&scope, &shot), "{}", shot.display()); + assert!(served(&scope, &clip), "{}", clip.display()); + assert!(served(&scope, &icon), "{}", icon.display()); + assert!(!served(&scope, ¶m), "{}", param.display()); + assert!(!served(&scope, &loose), "{}", loose.display()); + assert!(!served(&scope, &std::env::current_exe().unwrap())); + #[cfg(unix)] + assert!(!served(&scope, Path::new("/etc/hosts"))); + + let _ = std::fs::remove_dir_all(&scratch); + let _ = std::fs::remove_dir_all(&other); + } +} + #[cfg(test)] mod profile_tests { /// `panic = "abort"` in this package's release profile switches off every `catch_unwind` in diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index c3201a193..2f3c40551 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -34,7 +34,8 @@ "assetProtocol": { "enable": true, "scope": [ - "**" + "$TEMP/ps5upload-save-*/**", + "**/sce_sys/icon0.png" ] } } From d3fcf5f9f352f6492aa498c71205978ab88c4c11 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:56:56 -0800 Subject: [PATCH 13/27] Send only payload files when a payload is sent by its path The engine refused a path that is not a .elf, .bin, .js, .lua or .jar file, but the desktop app's own send (used when the engine is down) read any file and sent it to any address and port. The check now sits in the one function every path send goes through, so both ways refuse a file that is not a payload, and the send check no longer opens such a file either. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/probes.rs | 4 +- .../ps5upload-core/src/payload_lifecycle.rs | 59 ++++++++++++++++++- .../ps5upload-engine/src/browser_payload.rs | 18 ++---- 3 files changed, 66 insertions(+), 15 deletions(-) diff --git a/client/src-tauri/src/commands/probes.rs b/client/src-tauri/src/commands/probes.rs index 8915ef399..7974f6128 100644 --- a/client/src-tauri/src/commands/probes.rs +++ b/client/src-tauri/src/commands/probes.rs @@ -523,7 +523,9 @@ pub async fn payload_send_check(ip: String, path: String, port: Option) -> if port.unwrap_or(PS5_LOADER_PORT) != PS5_LOADER_PORT { return serde_json::json!({ "ok": true }); } - let helper = file_is_helper(&path).await; + // Only a payload file is opened: the probe reads its first 512 KiB. + let helper = ps5upload_core::payload_lifecycle::is_payload_file_name(&path) + && file_is_helper(&path).await; let url = format!("{}/api/payload/send-check", crate::engine::url()); let Ok(client) = crate::engine_http::engine_client_builder() .timeout(Duration::from_secs(20)) diff --git a/engine/crates/ps5upload-core/src/payload_lifecycle.rs b/engine/crates/ps5upload-core/src/payload_lifecycle.rs index 771b99dca..2ccf5cf43 100644 --- a/engine/crates/ps5upload-core/src/payload_lifecycle.rs +++ b/engine/crates/ps5upload-core/src/payload_lifecycle.rs @@ -32,6 +32,23 @@ use crate::net::resolve_connect_targets; /// as a fresh process once the sender half-closes the socket. pub const PS5_LOADER_PORT: u16 = 9021; +/// What a loader takes, by file extension. A send of a file by its path reads whatever the +/// process can, and a port other than :9021 has no ELF check: without this, a send could stream +/// any file of this computer (a key, a document) to any address. +pub const PAYLOAD_EXTENSIONS: &[&str] = &["elf", "bin", "js", "lua", "jar"]; + +/// Whether `path` names a payload file by its extension ([`PAYLOAD_EXTENSIONS`], any case). +pub fn is_payload_file_name(path: &str) -> bool { + std::path::Path::new(path.trim()) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| { + PAYLOAD_EXTENSIONS + .iter() + .any(|ok| e.eq_ignore_ascii_case(ok)) + }) +} + /// The longest the running helper is given to answer `node.shutdown` while a connection to the /// loader waits. The call itself is bounded at 2 s once a session exists; finding out there is /// no session can take a few seconds more. @@ -884,13 +901,20 @@ fn refuse_second_mounter( Ok(()) } -/// [`send_payload_image`] for a file on this machine. +/// [`send_payload_image`] for a file on this machine. Only a payload file +/// ([`is_payload_file_name`]) is read: every way a path reaches a send (the engine's +/// `/api/payload/send`, the desktop app's own socket when the engine is down) comes here. pub fn send_payload_file( host: &str, path: &str, port: u16, stamp: &mut dyn FnMut(&mut Vec), ) -> Result { + if !is_payload_file_name(path) { + return Err(format!( + "{path} is not a payload file: send a .elf, .bin, .js, .lua or .jar file" + )); + } let size = std::fs::metadata(path) .map_err(|e| format!("open {path}: {e}"))? .len(); @@ -1485,6 +1509,39 @@ mod tests { assert!(e.contains("/no/such/file.elf"), "{e}"); } + /// A path that is not a payload file is never read or sent, to any port: the send by path + /// would otherwise hand any file of this computer to any address (the desktop app's own + /// socket had no such check when the engine was down). + #[test] + fn only_a_payload_file_is_read_and_sent() { + let (port, h) = listen_once(); + let p = temp_file("id_rsa", b"-----BEGIN OPENSSH PRIVATE KEY-----"); + let e = + send_payload_file("127.0.0.1", p.to_str().unwrap(), port, &mut no_stamp()).unwrap_err(); + assert!(e.contains("not a payload file"), "{e}"); + let p = temp_file("notes.txt", b"\x7FELF and more"); + let e = + send_payload_file("127.0.0.1", p.to_str().unwrap(), port, &mut no_stamp()).unwrap_err(); + assert!(e.contains("not a payload file"), "{e}"); + // Nothing reached the listener: unblock it and see it got nothing. + drop(std::net::TcpStream::connect(("127.0.0.1", port)).unwrap()); + assert!(h.join().unwrap().is_empty()); + + for ok in ["a.elf", "A.BIN", "x.Js", "/d/y.lua", "z.jar"] { + assert!(is_payload_file_name(ok), "{ok}"); + } + for bad in [ + "", + "elf", + "a.elf.txt", + "a.so", + "/home/u/.ssh/id_ed25519", + "a.", + ] { + assert!(!is_payload_file_name(bad), "{bad}"); + } + } + #[test] fn a_dead_port_that_is_not_the_loader_gets_no_fallback() { let closed = { diff --git a/engine/crates/ps5upload-engine/src/browser_payload.rs b/engine/crates/ps5upload-engine/src/browser_payload.rs index f7621b9da..177150d50 100644 --- a/engine/crates/ps5upload-engine/src/browser_payload.rs +++ b/engine/crates/ps5upload-engine/src/browser_payload.rs @@ -15,8 +15,8 @@ use axum::{ Json, Router, }; use ps5upload_core::payload_lifecycle::{ - image_is_helper, is_ps5upload_payload, send_payload_file, send_payload_image, SentPayload, - PS5_LOADER_PORT, + image_is_helper, is_payload_file_name, is_ps5upload_payload, send_payload_file, + send_payload_image, SentPayload, PS5_LOADER_PORT, }; use serde::Deserialize; use serde_json::json; @@ -88,11 +88,6 @@ struct SendRequest { opts: SendOpts, } -/// What a loader takes (`payload_probe`'s list). The `path` form reads any file the engine can, -/// and a port other than :9021 has no ELF check, so without this it would stream any file on this -/// machine to any address. -const PAYLOAD_EXTENSIONS: &[&str] = &["elf", "bin", "js", "lua", "jar"]; - #[derive(Deserialize)] struct CheckBody { host: String, @@ -432,12 +427,9 @@ async fn send_json(installs: PkgInstallStateHandle, body: &[u8]) -> Response { } let path = match (req.path, req.payload_id) { (Some(path), None) => { - let ext_ok = std::path::Path::new(&path) - .extension() - .and_then(|e| e.to_str()) - .map(|e| e.to_ascii_lowercase()) - .is_some_and(|e| PAYLOAD_EXTENSIONS.contains(&e.as_str())); - if !ext_ok { + // What a loader takes (`payload_lifecycle::PAYLOAD_EXTENSIONS`): the send by path + // reads any file the engine can, so it is refused here in words, as well as there. + if !is_payload_file_name(&path) { return bad_request("path must be a .elf, .bin, .js, .lua or .jar file"); } path From 1f572dcd2b4023a9124ccfa6167875ebe1df813d Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:07:41 -0800 Subject: [PATCH 14/27] Hand an agent only a clean engine address, and keep its entry on a failed move "Add to agent" passed the engine address to the agent's CLI as it was typed in Settings, so an address starting with "-" read as an option and spaces or line breaks went into the agent's config as more than an address. It is now parsed as an http(s) URL and written out again, and anything else is refused. Claude Code also had its ps5upload entry removed before the new one was added: when that add failed, the agent was left with none. The old entry is now put back. Each agent's own CLI still writes its config, so its other servers and comments stay the CLI's to keep; no shell is involved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/agent_mcp.rs | 120 +++++++++++++++++++-- 1 file changed, 109 insertions(+), 11 deletions(-) diff --git a/client/src-tauri/src/commands/agent_mcp.rs b/client/src-tauri/src/commands/agent_mcp.rs index a69b3212e..546b921d9 100644 --- a/client/src-tauri/src/commands/agent_mcp.rs +++ b/client/src-tauri/src/commands/agent_mcp.rs @@ -156,7 +156,24 @@ pub struct AgentMcpStatus { } fn expected_url() -> String { - format!("{}/mcp", engine::url().trim_end_matches('/')) + let base = engine::url(); + mcp_url(&base).unwrap_or_else(|_| format!("{}/mcp", base.trim_end_matches('/'))) +} + +/// The address an agent saves: the engine's `/mcp` as a plain http(s) URL, or `bad_engine_url`. +/// Settings → Engine URL takes any text, and the agent's CLI gets this as an argument: one that +/// starts with `-` reads as an option, and spaces or line breaks would go into its config as +/// more than an address. Parsed and written out again, it is one URL and nothing else. +fn mcp_url(base: &str) -> Result { + let bad = || "bad_engine_url".to_string(); + let mut url = reqwest::Url::parse(base.trim()).map_err(|_| bad())?; + let host_ok = url.host_str().is_some_and(|h| !h.is_empty()); + if !matches!(url.scheme(), "http" | "https") || !host_ok { + return Err(bad()); + } + let path = format!("{}/mcp", url.path().trim_end_matches('/')); + url.set_path(&path); + Ok(url.to_string()) } /// `PATH` for finding and running these CLIs: an npm-installed one starts `node` by name, so what @@ -447,24 +464,37 @@ pub async fn agent_mcp_status() -> Result, String> { pub async fn agent_mcp_add(agent: String) -> Result { not_on_phones()?; let agent = agent_from(&agent)?; + let url = mcp_url(&engine::url())?; tauri::async_runtime::spawn_blocking(move || { let path = search_path(); - let before = status_of(agent, &path); - if !before.found { - return Err("cli_not_found".to_string()); - } - if agent.add_refuses_existing() && before.configured { - if let Some(args) = agent.remove_args() { - change(agent, &args, &path)?; - } - } - change(agent, &agent.add_args(&expected_url()), &path)?; + add_with(agent, &url, &path)?; Ok(status_of(agent, &path)) }) .await .map_err(|e| e.to_string())? } +/// Saves `url` as the agent's `ps5upload` entry. An agent that refuses a name it has (Claude +/// Code) has its entry removed first; when the add then fails, the entry it had is put back, so +/// a failed move never leaves the agent without one. +fn add_with(agent: Agent, url: &str, path: &OsString) -> Result<(), String> { + let before = status_of(agent, path); + if !before.found { + return Err("cli_not_found".to_string()); + } + let replacing = agent.add_refuses_existing() && before.configured; + if replacing { + if let Some(args) = agent.remove_args() { + change(agent, &args, path)?; + } + } + change(agent, &agent.add_args(url), path).inspect_err(|_| { + if let (true, Some(old)) = (replacing, before.saved_url.as_deref()) { + let _ = change(agent, &agent.add_args(old), path); + } + }) +} + /// Takes this engine out of an agent. Answers with where it stands after. #[tauri::command] pub async fn agent_mcp_remove(agent: String) -> Result { @@ -514,6 +544,32 @@ mod tests { assert_eq!(Agent::from_id(""), None); } + /// The engine address goes to the agent's CLI as an argument and into its config: only a + /// plain http(s) URL does, written out again so nothing else rides along. + #[test] + fn only_a_web_address_is_handed_to_an_agent() { + assert_eq!(mcp_url("http://127.0.0.1:19113").unwrap(), URL); + assert_eq!(mcp_url(" http://127.0.0.1:19113/ ").unwrap(), URL); + assert_eq!( + mcp_url("https://nas.lan/ps5upload").unwrap(), + "https://nas.lan/ps5upload/mcp" + ); + // Spaces and line breaks are encoded or dropped, never passed on as they are. + let odd = mcp_url("http://h/a b\n--scope project").unwrap(); + assert!(!odd.contains([' ', '\n']), "{odd}"); + for bad in [ + "", + "-e http://h", + "--transport stdio", + "file:///etc/passwd", + "ftp://h/", + "h:19113", + "http://", + ] { + assert_eq!(mcp_url(bad), Err("bad_engine_url".to_string()), "{bad:?}"); + } + } + #[test] fn each_agent_gets_the_arguments_its_cli_takes() { assert_eq!( @@ -660,6 +716,48 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Claude Code refuses a name it has, so its entry is removed before the new one is + /// added. When that add failed, the agent was left with no entry at all; the old one is + /// now put back. + #[test] + fn a_failed_move_puts_the_old_entry_back() { + let dir = scratch("move"); + let d = dir.display(); + // Shell builtins only: `run` gives the program this folder alone as its PATH. + let body = format!( + r#"case "$1 $2" in + "mcp get") + if [ -f "{d}/added" ]; then IFS= read -r u < "{d}/added"; echo " URL: $u"; exit 0; fi + if [ -f "{d}/gone" ]; then exit 1; fi + echo " URL: http://old.lan:1/mcp"; exit 0 ;; + "mcp remove") : > "{d}/gone"; exit 0 ;; + "mcp add") + if [ "$8" = "http://old.lan:1/mcp" ]; then echo "$8" > "{d}/added"; exit 0; fi + echo "cannot reach the new address" >&2; exit 1 ;; +esac +exit 2"# + ); + script(&dir, "claude", &body); + let path = std::env::join_paths([&dir]).unwrap(); + let mut tries = 0; + let e = loop { + match add_with(Agent::ClaudeCode, "http://new.lan:2/mcp", &path) { + Err(e) if e.contains("Text file busy") && tries < 50 => { + tries += 1; + std::thread::sleep(Duration::from_millis(20)); + } + other => break other.unwrap_err(), + } + }; + assert_eq!(e, "cannot reach the new address"); + let saved = std::fs::read_to_string(dir.join("added")).unwrap(); + assert_eq!(saved.trim(), "http://old.lan:1/mcp"); + let now = status_of(Agent::ClaudeCode, &path); + assert!(now.configured); + assert_eq!(now.saved_url.as_deref(), Some("http://old.lan:1/mcp")); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn output_and_exit_status_come_back() { let dir = scratch("out"); From f34eddee3066e4b03633b3382189b401a8211bad Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:06:18 -0800 Subject: [PATCH 15/27] Keep NFS and FTP file names that are not UTF-8 A name from an older system (Latin-1 and the like) was read as lossy UTF-8, so it became a name the server does not have: opening the file failed, and on NFS a folder listed without attributes could not be listed at all. Names now keep every byte: a byte that is not UTF-8 stands for itself as one private-use character, and is sent back as that byte when the file is opened, looked up or renamed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../ps5upload-engine/src/remote/ftp_fs.rs | 106 ++++++++++++ .../crates/ps5upload-engine/src/remote/mod.rs | 1 + .../ps5upload-engine/src/remote/name_bytes.rs | 154 ++++++++++++++++++ .../ps5upload-engine/src/remote/nfs_fs.rs | 87 +++++++++- 4 files changed, 345 insertions(+), 3 deletions(-) create mode 100644 engine/crates/ps5upload-engine/src/remote/name_bytes.rs diff --git a/engine/crates/ps5upload-engine/src/remote/ftp_fs.rs b/engine/crates/ps5upload-engine/src/remote/ftp_fs.rs index 22ea413d4..5dd96be70 100644 --- a/engine/crates/ps5upload-engine/src/remote/ftp_fs.rs +++ b/engine/crates/ps5upload-engine/src/remote/ftp_fs.rs @@ -421,6 +421,9 @@ async fn sign_in(t: &Target) -> Result { // A NAS behind a router often names its private address for passive data; use the one // we connected to instead. ftp.set_passive_nat_workaround(true); + // Names go both ways as the server's bytes: one that is not UTF-8 (Latin-1 from an older + // system) read as lossy UTF-8 could not be asked for again, so the file failed to open. + ftp.set_encoding(super::name_bytes::Lossless).await; if implicit { // The library secures only the control connection here; the data connections want this. for command in ["PBSZ 0", "PROT P"] { @@ -1489,6 +1492,109 @@ mod tests { const GLOB_FILE: &str = "PPSA00000_Game_v01.003.000_FW10.ffpfsc"; const GLOB_SIZE: u64 = 13_851_336_704; + /// A file named in Latin-1 (not UTF-8), as an older NAS keeps it. + const LATIN1_PATH: &[u8] = b"/caf\xE9.bin"; + const LATIN1_BODY: &[u8] = b"hello"; + + /// A server whose root holds [`LATIN1_PATH`]: it answers SIZE and RETR only for those exact + /// bytes, as a real one does. + async fn latin1_server() -> u16 { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let ctl = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = ctl.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((sock, _)) = ctl.accept().await { + tokio::spawn(async move { + let (rd, mut wr) = sock.into_split(); + let mut rd = BufReader::new(rd); + let mut data: Option = None; + wr.write_all(b"220 ready\r\n").await.ok(); + let mut line = Vec::new(); + while matches!(rd.read_until(b'\n', &mut line).await, Ok(n) if n > 0) { + let l = line.strip_suffix(b"\r\n").unwrap_or(&line).to_vec(); + line.clear(); + let sp = l.iter().position(|&b| b == b' ').unwrap_or(l.len()); + let cmd = String::from_utf8_lossy(&l[..sp]).to_ascii_uppercase(); + let arg = l.get(sp + 1..).unwrap_or_default(); + let ours = arg == LATIN1_PATH; + let reply = match cmd.as_str() { + "USER" => "331 Password required".to_string(), + "PASS" => "230 OK".into(), + "TYPE" => "200 OK".into(), + "PWD" => "257 \"/\" is the current folder".into(), + "CWD" if arg == b"/" => "250 OK".into(), + "SIZE" if ours => format!("213 {}", LATIN1_BODY.len()), + "REST" => "350 Restarting".into(), + "PASV" => { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let p = l.local_addr().unwrap().port(); + data = Some(l); + format!( + "227 Entering Passive Mode (127,0,0,1,{},{})", + p / 256, + p % 256 + ) + } + "LIST" | "RETR" if cmd == "LIST" || ours => { + let Some(l) = data.take() else { + wr.write_all(b"425 No data connection\r\n").await.ok(); + continue; + }; + wr.write_all(b"150 Opening data connection\r\n").await.ok(); + let (mut d, _) = l.accept().await.unwrap(); + if cmd == "LIST" { + let mut row = + b"-rw-r--r-- 1 1000 1000 5 Nov 8 04:11 ".to_vec(); + row.extend_from_slice(&LATIN1_PATH[1..]); + row.extend_from_slice(b"\r\n"); + d.write_all(&row).await.ok(); + } else { + d.write_all(LATIN1_BODY).await.ok(); + } + drop(d); + "226 Transfer complete".into() + } + "QUIT" => { + wr.write_all(b"221 Goodbye\r\n").await.ok(); + break; + } + "SIZE" | "MDTM" | "RETR" | "CWD" => "550 No such file".into(), + _ => "500 Unknown command".into(), + }; + wr.write_all(format!("{reply}\r\n").as_bytes()).await.ok(); + } + }); + } + }); + port + } + + /// A file named in Latin-1 listed as lossy UTF-8 (`caf\u{FFFD}.bin`), which no server has: + /// opening it failed. The name keeps its bytes, and the file opens and reads by it. + #[tokio::test] + async fn a_name_that_is_not_utf8_lists_and_opens() { + let port = latin1_server().await; + let mut conn = crate::remote::store::conn("t", crate::remote::store::Protocol::Ftp); + conn.host = "127.0.0.1".into(); + conn.port = port; + conn.user = "t".into(); + let secret = Secret::Password { + password: "t".into(), + }; + let fs = FtpFs::connect(&conn, &secret, false).await.unwrap(); + let page = fs.list("/", None).await.unwrap(); + assert_eq!(page.entries.len(), 1, "{:?}", triples(&page.entries)); + let name = page.entries[0].name.clone(); + assert!(!name.contains('\u{FFFD}'), "{name:?}"); + assert_eq!( + super::super::name_bytes::encode(&format!("/{name}")), + LATIN1_PATH + ); + let f = fs.open(&format!("/{name}")).await.unwrap(); + assert_eq!(f.size(), LATIN1_BODY.len() as u64); + assert_eq!(f.read_at(0, f.size()).await.unwrap(), LATIN1_BODY); + } + /// A server that, like Pure-FTPd (and the Keenetic router's FTP server of the report), reads a /// LIST argument as a glob: `[PS5]` is a character class, so listing the folder by its path /// matches nothing and answers an empty listing with success. Speaks no FEAT, so no MLSD. diff --git a/engine/crates/ps5upload-engine/src/remote/mod.rs b/engine/crates/ps5upload-engine/src/remote/mod.rs index ebfb4510b..1c2730b45 100644 --- a/engine/crates/ps5upload-engine/src/remote/mod.rs +++ b/engine/crates/ps5upload-engine/src/remote/mod.rs @@ -13,6 +13,7 @@ pub mod ftp_fs; pub mod hints; pub mod host_key; mod http_digest; +pub(crate) mod name_bytes; pub mod nfs_fs; pub mod path; pub mod pool; diff --git a/engine/crates/ps5upload-engine/src/remote/name_bytes.rs b/engine/crates/ps5upload-engine/src/remote/name_bytes.rs new file mode 100644 index 000000000..68da2d87b --- /dev/null +++ b/engine/crates/ps5upload-engine/src/remote/name_bytes.rs @@ -0,0 +1,154 @@ +//! File names from an NFS or FTP server as text, with every byte kept. +//! +//! Both protocols send a name as raw bytes. Most servers use UTF-8, but a folder copied from an +//! older system can hold Latin-1, Windows-1252 or Shift-JIS names. Read as lossy UTF-8, such a +//! name became `U+FFFD` and could not be asked for again: the listing showed a name the server +//! did not have, opening the file failed, and an NFS folder holding one could not be listed at +//! all. Here each byte that is not part of valid UTF-8 stands for itself as one character of a +//! private-use range, and turning the text back into bytes gives the exact name again. +//! +//! The range is U+10FF80..=U+10FFFF (the end of Supplementary Private Use Area-B), one character +//! per byte 0x80..=0xFF. A real name that holds one of those characters (valid UTF-8, four bytes +//! each) is read byte by byte the same way, so it comes back unchanged too. + +/// The character that stands for byte 0x80; byte `b` is `ESCAPE_BASE + (b - 0x80)`. +const ESCAPE_BASE: u32 = 0x10_FF80; + +fn escape(b: u8) -> char { + // Only bytes 0x80..=0xFF are ever escaped (ASCII is always valid UTF-8). + char::from_u32(ESCAPE_BASE + u32::from(b.saturating_sub(0x80))).unwrap_or('\u{FFFD}') +} + +fn unescape(c: char) -> Option { + let n = u32::from(c); + (ESCAPE_BASE..=ESCAPE_BASE + 0x7F) + .contains(&n) + .then(|| (n - ESCAPE_BASE + 0x80) as u8) +} + +fn push_text(out: &mut String, text: &str) { + for c in text.chars() { + if unescape(c).is_some() { + let mut buf = [0u8; 4]; + for &b in c.encode_utf8(&mut buf).as_bytes() { + out.push(escape(b)); + } + } else { + out.push(c); + } + } +} + +/// A name the server sent, as text: valid UTF-8 as it is, every other byte as its stand-in. +pub(crate) fn decode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len()); + let mut rest = bytes; + while !rest.is_empty() { + match std::str::from_utf8(rest) { + Ok(text) => { + push_text(&mut out, text); + break; + } + Err(e) => { + let (good, bad) = rest.split_at(e.valid_up_to()); + push_text(&mut out, std::str::from_utf8(good).unwrap_or_default()); + let n = e.error_len().unwrap_or(bad.len()).max(1); + for &b in &bad[..n] { + out.push(escape(b)); + } + rest = &bad[n..]; + } + } + } + out +} + +/// The bytes to send for `name`: what [`decode`] read, exactly. +pub(crate) fn encode(name: &str) -> Vec { + let mut out = Vec::with_capacity(name.len()); + for c in name.chars() { + match unescape(c) { + Some(b) => out.push(b), + None => { + let mut buf = [0u8; 4]; + out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); + } + } + } + out +} + +/// Names on an FTP server's control and data connections, through [`decode`] and [`encode`]. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct Lossless; + +impl suppaftp::Encoding for Lossless { + fn decode(&self, bytes: &[u8]) -> String { + decode(bytes) + } + + fn encode(&self, text: &str) -> std::io::Result> { + Ok(encode(text)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utf8_names_are_unchanged() { + for name in [ + "game.pkg", + "[PS5] Hellblade [RUS]", + "café", + "ゲーム", + "a\u{1F600}b", + ] { + assert_eq!(decode(name.as_bytes()), name); + assert_eq!(encode(name), name.as_bytes()); + } + } + + #[test] + fn a_latin1_name_comes_back_byte_for_byte() { + let raw = b"caf\xE9 \xFF\x80.bin"; + let text = decode(raw); + assert!(!text.contains('\u{FFFD}'), "{text:?}"); + assert!(text.starts_with("caf") && text.ends_with(".bin")); + assert_eq!(encode(&text), raw); + // Two names that differ only in a byte that is not UTF-8 stay two names. + assert_ne!(decode(b"a\xE9"), decode(b"a\xE8")); + } + + #[test] + fn a_name_holding_a_stand_in_character_also_comes_back() { + let stand_in = char::from_u32(ESCAPE_BASE + 0x69).unwrap(); + let raw = format!("x{stand_in}y"); + let text = decode(raw.as_bytes()); + assert_eq!(encode(&text), raw.as_bytes()); + } + + #[test] + fn every_byte_string_round_trips() { + // A small deterministic generator: every length up to 12 with mixed bytes. + let mut state = 0x2545_F491_4F6C_DD1Du64; + for len in 0..=12 { + for _ in 0..2000 { + let bytes: Vec = (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + // Weight towards high bytes and the stand-in range's lead bytes. + match state % 4 { + 0 => b"\xF4\x8F\xBE\xBF"[(state >> 8) as usize % 4], + _ => (state >> 16) as u8, + } + }) + .collect(); + assert_eq!(encode(&decode(&bytes)), bytes, "{bytes:02x?}"); + } + } + } +} diff --git a/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs b/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs index d9e361567..d4f893e44 100644 --- a/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs +++ b/engine/crates/ps5upload-engine/src/remote/nfs_fs.rs @@ -109,8 +109,10 @@ impl Xdr { fn opaque(self, b: &[u8]) -> Self { self.u32(b.len() as u32).fixed(b) } + /// A directory handle and a name in it, the name as the bytes the server listed + /// ([`super::name_bytes`]). fn dir_op(self, dir: &[u8], name: &str) -> Self { - self.opaque(dir).opaque(name.as_bytes()) + self.opaque(dir).opaque(&super::name_bytes::encode(name)) } } @@ -170,8 +172,11 @@ impl<'a> In<'a> { fn skip_padding(&mut self, n: usize) { self.take((4 - n % 4) % 4); } + /// A name or path the server sent, every byte kept: a name that is not UTF-8 (Latin-1 from + /// an older system) read lossily could not be looked up again, and the folder holding it + /// failed to list ([`super::name_bytes`]). fn text(&mut self) -> String { - String::from_utf8_lossy(&self.opaque(4096)).into_owned() + super::name_bytes::decode(&self.opaque(4096)) } } @@ -837,7 +842,10 @@ impl Inner { return Ok(h.clone()); } let reply = self - .mount_call(MNT, Xdr::default().opaque(export.as_bytes())) + .mount_call( + MNT, + Xdr::default().opaque(&super::name_bytes::encode(export)), + ) .await?; let mut i = In::new(&reply); match i.u32() { @@ -1777,8 +1785,13 @@ mod tests { mount: bool, nfs: bool, map: Vec<((u32, u32), u16)>, + /// The export holds one file named in Latin-1 (`LATIN1_NAME`, not UTF-8), listed + /// without its attributes, so the client must look it up by the exact bytes. + latin1: bool, } + const LATIN1_NAME: &[u8] = b"caf\xE9.bin"; + impl Fake { /// The accept_stat and results for a call, PROG_UNAVAIL for a program it doesn't serve. fn answer(&self, program: u32, proc: u32, args: &[u8]) -> (u32, Vec) { @@ -1800,6 +1813,47 @@ mod tests { MOUNT if self.mount && proc == EXPORT => { (0, Xdr::default().u32(1).opaque(b"/PS4 NFS").u32(0).u32(0).0) } + NFS if self.latin1 && proc == READDIRPLUS => ( + 0, + Xdr::default() + .u32(0) + .u32(0) + .fixed(&[0; 8]) + .u32(1) + .u64(1) + .opaque(LATIN1_NAME) + .u64(1) + .u32(0) // no attributes: looked up by name + .u32(0) + .u32(0) + .u32(1) + .0, + ), + NFS if self.latin1 && proc == GETATTR => { + let file = Xdr::default() + .u32(0) + .u32(1) // a regular file + .fixed(&[0; 16]) + .u64(5) + .fixed(&[0; 56]); + (0, file.0) + } + NFS if self.latin1 && proc == LOOKUP => { + let mut i = In::new(args); + i.opaque(64); // the folder's handle + if i.opaque(255) != LATIN1_NAME { + return (0, Xdr::default().u32(2).0); // NFS3ERR_NOENT + } + let file = Xdr::default() + .u32(0) + .opaque(b"file-handle") + .u32(1) + .u32(1) // a regular file + .fixed(&[0; 16]) + .u64(5) + .fixed(&[0; 56]); + (0, file.0) + } NFS if self.nfs && proc == READDIRPLUS => ( 0, Xdr::default() @@ -1934,6 +1988,33 @@ mod tests { assert_eq!(listed.entries[0].name, "game"); } + /// A file named in Latin-1 on an older NAS: its name was read as lossy UTF-8, so looking it + /// up (which a listing without attributes does) failed and the whole folder could not be + /// listed. The name now keeps its bytes and is asked for exactly as listed. + #[tokio::test] + async fn a_name_that_is_not_utf8_lists_and_is_found_again() { + let both = Fake { + mount: true, + nfs: true, + latin1: true, + ..Fake::default() + } + .tcp() + .await; + let fs = NfsFs::connect_via(&nfs_conn(both), closed_port().await) + .await + .unwrap(); + let listed = fs.list("/", None).await.unwrap(); + assert_eq!(listed.entries.len(), 1); + let entry = &listed.entries[0]; + assert!(!entry.is_dir); + assert_eq!(entry.size, 5); + assert!(!entry.name.contains('\u{FFFD}'), "{:?}", entry.name); + assert_eq!(super::super::name_bytes::encode(&entry.name), LATIN1_NAME); + let found = fs.stat(&format!("/{}", entry.name)).await.unwrap(); + assert_eq!(found.size, 5); + } + /// #796: NFS at 2049 and the mount service on a port of its own, which only the portmapper /// knows. The NFS port answers PROG_UNAVAIL for MOUNT. #[tokio::test] From 19824b9c8d5a3fe3a47bc57158dcc6920c5176ec Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:01:22 -0800 Subject: [PATCH 16/27] Keep a save restore inside the save folder it names A restore empties the console folder it is given and fills it from the backup. The engine only checked that the folder ends with the title ID, so a save path with ".." (or a title ID that was a path, which the restore-file route did not check) could point it at another folder on the PS5. The save path must now be a plain absolute path and the title ID one plain name, checked before anything is read, kept or deleted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../ps5upload-engine/src/save_backup.rs | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/engine/crates/ps5upload-engine/src/save_backup.rs b/engine/crates/ps5upload-engine/src/save_backup.rs index 512d0fab7..0394bf6c8 100644 --- a/engine/crates/ps5upload-engine/src/save_backup.rs +++ b/engine/crates/ps5upload-engine/src/save_backup.rs @@ -1723,6 +1723,28 @@ pub(crate) fn mark_restored(host: &str, save_path: &str) { let _ = save(DONE_FILE, &done); } +/// A restore empties the console folder `save_path` and fills it from a backup, and unpacks the +/// backup under `title_id` here: refused unless `title_id` is one plain name ([`plain`]) and +/// `save_path` is a plain absolute path, with no `.`, `..` or empty part, no backslash and +/// no control character. Otherwise a path such as `/user/home/1/savedata_prospero/../../../x/CUSA1` +/// ends with the title ID and passed, and the folder it reaches was emptied. +pub(crate) fn save_folder_ok(save_path: &str, title_id: &str) -> Result<(), String> { + if !plain(title_id) { + return Err(format!("{title_id:?} is not a title ID")); + } + let plain_path = save_path.starts_with('/') + && !save_path.contains('\\') + && !save_path.chars().any(char::is_control) + && save_path + .split('/') + .skip(1) + .all(|part| !part.is_empty() && part != "." && part != ".."); + if !plain_path { + return Err(format!("{save_path} is not a save folder")); + } + Ok(()) +} + /// The app that writes a save folder, which must be closed while it is restored. #[derive(Debug, PartialEq)] pub(crate) struct Writer<'a> { @@ -1740,6 +1762,7 @@ pub(crate) fn save_writer<'a>( title_id: &'a str, user_id: u32, ) -> Result, String> { + save_folder_ok(save_path, title_id)?; let ps2 = crate::ps2_saves::place_of(save_path); let switch = crate::emulator_saves::place_of(save_path); let fits = match &ps2 { @@ -1971,6 +1994,8 @@ pub(crate) fn put_in_place( tag: Option<&str>, keep_current: bool, ) -> Result<(), String> { + // Every name first: this empties the folder. + save_folder_ok(save_path, title_id)?; let _op = save_op(&[host]); // Keep what is there now, so the change can be undone: in the backup folder, or (with none // set) on the server the save backups go to. @@ -3548,6 +3573,53 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A restore empties the folder it is given, so a save path that climbs out with `..` (it + /// still ends with the title ID), or a title ID that is a path, is refused before the console + /// or this computer is touched. The payload's own restore refuses the same (backup.c). + #[test] + fn a_restore_never_reaches_outside_the_save_folder() { + for (path, title) in [ + ( + "/user/home/1/savedata_prospero/../../../system_data/PPSA01234", + "PPSA01234", + ), + ("/user/home/1/savedata_prospero/./PPSA01234", "PPSA01234"), + ("/user/home/1/savedata_prospero//PPSA01234", "PPSA01234"), + ("user/home/1/savedata_prospero/PPSA01234", "PPSA01234"), + ( + "/user/home/1/savedata_prospero\\..\\x/PPSA01234", + "PPSA01234", + ), + ("/user/home/1/savedata_prospero/PPSA01234\n", "PPSA01234"), + ("/user/home/1/savedata_prospero/..", ".."), + ("/user/home/1/savedata_prospero/a/../b", "a/../b"), + ("/user/home/1/savedata_prospero/x", ""), + ] { + assert!(save_folder_ok(path, title).is_err(), "{path:?} {title:?}"); + assert!(save_writer(path, title, 1).is_err(), "{path:?} {title:?}"); + // Refused before anything else: no console answers at this address. + let e = put_in_place( + "127.0.0.1", + title, + Path::new("/nonexistent"), + path, + 1, + &Settings::default(), + None, + false, + ) + .unwrap_err(); + assert!( + e.contains("not a save folder") || e.contains("not a title ID"), + "{path:?} {title:?}: {e}" + ); + } + let ok = "/user/home/1/savedata_prospero/PPSA01234"; + assert!(save_folder_ok(ok, "PPSA01234").is_ok()); + assert!(save_writer(ok, "PPSA01234", 1).is_ok()); + assert!(save_folder_ok("/data/PCSX2/*.ps2", "PPSA99203").is_ok()); + } + #[test] fn a_restore_is_only_into_the_saves_own_folder() { let ps5 = save_writer("/user/home/1/savedata_prospero/PPSA01234", "PPSA01234", 1).unwrap(); From 8e62c4d470e39ea2d5b258058a4151c25c2b3849 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:57:25 -0800 Subject: [PATCH 17/27] Cap replies whose size the other side decides Several places read a peer's whole reply into memory with no limit, so a server that kept sending could fill it: the console's Remote Play session and registration answers, Payload Manager replies, cheat and patch downloads, the console FTP log tail, and the release list the pre-release update channel reads. Each now stops at a size well above any real reply and reports it, and a patch archive entry is held to the size it declares. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/updates.rs | 73 +++++++++++++------ engine/crates/ps5upload-core/src/cheats.rs | 27 +++++-- engine/crates/ps5upload-core/src/net.rs | 47 ++++++++++++ .../ps5upload-core/src/payload_manager.rs | 39 +++++++++- engine/crates/ps5upload-core/src/rp_regist.rs | 10 ++- .../crates/ps5upload-core/src/rp_session.rs | 6 +- .../ps5upload-engine/src/helper_mirror.rs | 5 +- 7 files changed, 170 insertions(+), 37 deletions(-) diff --git a/client/src-tauri/src/commands/updates.rs b/client/src-tauri/src/commands/updates.rs index b20ab9543..3feea2c7f 100644 --- a/client/src-tauri/src/commands/updates.rs +++ b/client/src-tauri/src/commands/updates.rs @@ -547,6 +547,32 @@ mod is_newer_tests { /// default-unlimited body buffer. const MANIFEST_MAX_BYTES: usize = 64 * 1024; +/// Hard cap on the releases list the pre-release channel reads: ten releases with their notes +/// and asset lists come to some tens of KiB. +const RELEASE_LIST_MAX_BYTES: usize = 4 * 1024 * 1024; + +/// A response body, refused past `max` bytes. The Content-Length check is only an early-out: +/// it is absent for chunked transfer-encoding, and `resp.bytes()` / `resp.json()` would then +/// buffer the entire body before any cap fires. The running total is what holds the limit. +async fn read_capped(resp: reqwest::Response, max: usize) -> Result, String> { + if let Some(len) = resp.content_length() { + if len > max as u64 { + return Err(code_only("update_too_large")); + } + } + let mut stream = resp.bytes_stream(); + use futures_util::StreamExt; + let mut body: Vec = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|e| network_error(&e))?; + if body.len().saturating_add(chunk.len()) > max { + return Err(code_only("update_too_large")); + } + body.extend_from_slice(&chunk); + } + Ok(body) +} + /// Ask the releases API for the newest release of any kind and return its /// `latest.json` asset URL. /// @@ -575,7 +601,8 @@ async fn prerelease_manifest_url(client: &reqwest::Client) -> Result = resp.json().await.map_err(|e| { + let body = read_capped(resp, RELEASE_LIST_MAX_BYTES).await?; + let releases: Vec = serde_json::from_slice(&body).map_err(|e| { coded( "update_bad_manifest", serde_json::json!({ "detail": e.to_string() }), @@ -632,27 +659,7 @@ async fn fetch_manifest(channel: UpdateChannel) -> Result { if !resp.status().is_success() { return Err(http_error(&resp)); } - // Bound the body before JSON parsing. The Content-Length pre-check is - // only an early-out: content_length() is None for chunked - // transfer-encoding, so a Some-only guard is bypassable and - // `resp.bytes()` would then buffer the entire body before any cap - // fires. Stream with a running-total cap (mirroring update_download) - // so an absent Content-Length cannot defeat the limit. - if let Some(len) = resp.content_length() { - if len as usize > MANIFEST_MAX_BYTES { - return Err(code_only("update_too_large")); - } - } - let mut stream = resp.bytes_stream(); - use futures_util::StreamExt; - let mut body: Vec = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(|e| network_error(&e))?; - if body.len().saturating_add(chunk.len()) > MANIFEST_MAX_BYTES { - return Err(code_only("update_too_large")); - } - body.extend_from_slice(&chunk); - } + let body = read_capped(resp, MANIFEST_MAX_BYTES).await?; serde_json::from_slice::(&body).map_err(|e| { coded( "update_bad_manifest", @@ -1326,6 +1333,28 @@ mod checksum_tests { mod tests { use super::{is_plain_file_name, is_safe_update_url}; + /// A body with no Content-Length (chunked) that never ends is refused at the cap. The + /// pre-release channel's release list was read whole with `resp.json()`. + #[tokio::test] + async fn an_endless_answer_is_refused_at_the_cap() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut head = [0u8; 1024]; + let _ = sock.read(&mut head).await; + let _ = sock + .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n") + .await; + let chunk = format!("4000\r\n{}\r\n", "x".repeat(0x4000)); + while sock.write_all(chunk.as_bytes()).await.is_ok() {} + }); + let resp = reqwest::get(format!("http://{addr}/")).await.unwrap(); + let e = super::read_capped(resp, 64 * 1024).await.unwrap_err(); + assert!(e.contains("update_too_large"), "{e}"); + } + #[test] fn update_file_names_are_bare_names() { assert!(is_plain_file_name("PS5Upload-10.7.4-win-x64.zip")); diff --git a/engine/crates/ps5upload-core/src/cheats.rs b/engine/crates/ps5upload-core/src/cheats.rs index 1890eb88b..8dc72034f 100644 --- a/engine/crates/ps5upload-core/src/cheats.rs +++ b/engine/crates/ps5upload-core/src/cheats.rs @@ -421,6 +421,9 @@ fn patch_xml_title(xml: &str) -> String { .replace("&", "&") } +/// The largest patch file read from the archive. +const PATCH_FILE_MAX: u64 = 1024 * 1024; + /// Every patch file of the release archive. fn parse_patch_archive(zip_bytes: &[u8]) -> Result> { let mut archive = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes))?; @@ -430,11 +433,17 @@ fn parse_patch_archive(zip_bytes: &[u8]) -> Result> { let Some(name) = file.name().ok().and_then(|n| patch_archive_name(&n)) else { continue; }; - if file.size() > 1024 * 1024 { + if file.size() > PATCH_FILE_MAX { + continue; + } + // The size is the archive's own word: what the entry inflates to is held to it too. + let mut bytes = Vec::new(); + (&mut file) + .take(PATCH_FILE_MAX + 1) + .read_to_end(&mut bytes)?; + if bytes.len() as u64 > PATCH_FILE_MAX { continue; } - let mut bytes = Vec::with_capacity(file.size() as usize); - file.read_to_end(&mut bytes)?; let title = patch_xml_title(&String::from_utf8_lossy(&bytes)); out.push((name, title, bytes)); } @@ -498,15 +507,21 @@ fn tree_entry_from_path(path: &str, prefix: &str) -> Option<(String, &'static st Some((filename.to_string(), format)) } +/// The most one cheat or patch download may be. +const REPO_FETCH_MAX: u64 = 64 * 1024 * 1024; + fn repo_fetch(url: &str) -> Result> { let config = ureq::Agent::config_builder() .timeout_global(Some(std::time::Duration::from_secs(20))) .build(); let agent = ureq::Agent::new_with_config(config); let resp = agent.get(url).header("User-Agent", "ps5upload").call()?; - let mut buf = Vec::with_capacity(32 * 1024); - resp.into_body().into_reader().read_to_end(&mut buf)?; - Ok(buf) + // The largest thing fetched is the game-patch archive (a few MiB); a server that keeps + // sending is refused at the cap instead of filling memory. + Ok(crate::net::read_to_end_capped( + resp.into_body().into_reader(), + REPO_FETCH_MAX, + )?) } /// Parse one line of `filename=game_title` format. diff --git a/engine/crates/ps5upload-core/src/net.rs b/engine/crates/ps5upload-core/src/net.rs index 4025f8c2d..4b970418a 100644 --- a/engine/crates/ps5upload-core/src/net.rs +++ b/engine/crates/ps5upload-core/src/net.rs @@ -81,6 +81,53 @@ pub(crate) fn resolve_connect_targets(addr: &str) -> Result> { Ok(out) } +/// Everything `r` gives until it ends, refused with `InvalidData` past `cap` bytes. For a reply +/// whose length the other side decides (a console's HTTP answer, a download): read whole without +/// a limit, a peer that keeps sending fills this computer's memory. +pub fn read_to_end_capped(r: R, cap: u64) -> io::Result> { + let mut out = Vec::new(); + read_to_end_capped_into(r, cap, &mut out)?; + Ok(out) +} + +/// [`read_to_end_capped`] into `out`, which keeps what arrived when the read fails (a reply cut +/// short by a reset can still be the whole answer). +pub fn read_to_end_capped_into(r: R, cap: u64, out: &mut Vec) -> io::Result<()> { + use io::Read as _; + let start = out.len() as u64; + r.take(cap.saturating_add(1)).read_to_end(out)?; + if out.len() as u64 - start > cap { + out.truncate((start + cap) as usize); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("the reply is larger than {cap} bytes"), + )); + } + Ok(()) +} + +#[cfg(test)] +mod capped_read_tests { + use super::*; + + #[test] + fn a_reply_up_to_the_cap_is_read_whole() { + assert_eq!(read_to_end_capped(&b"abc"[..], 3).unwrap(), b"abc"); + assert_eq!(read_to_end_capped(&b""[..], 0).unwrap(), b""); + } + + #[test] + fn a_reply_past_the_cap_is_refused_after_reading_no_more_than_one_byte_over() { + // An endless reply: stops at once instead of growing without end. + let e = read_to_end_capped(io::repeat(b'x'), 1024).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::InvalidData); + assert!(e.to_string().contains("1024"), "{e}"); + let mut kept = b"head".to_vec(); + assert!(read_to_end_capped_into(io::repeat(b'y'), 8, &mut kept).is_err()); + assert_eq!(kept, b"headyyyyyyyy"); + } +} + #[cfg(test)] mod transient_resource_error_tests { //! Pin the WSAENOBUFS-class classification. The bug this guards against: diff --git a/engine/crates/ps5upload-core/src/payload_manager.rs b/engine/crates/ps5upload-core/src/payload_manager.rs index 20b9b99b4..42ad122f1 100644 --- a/engine/crates/ps5upload-core/src/payload_manager.rs +++ b/engine/crates/ps5upload-core/src/payload_manager.rs @@ -27,7 +27,7 @@ //! Plain HTTP/1.1 over a TcpStream, no client crate: this runs in the Android //! build too, where the engine has no HTTP client dependency. -use std::io::{Read, Write}; +use std::io::Write; use std::net::TcpStream; use std::time::Duration; @@ -590,6 +590,9 @@ pub fn http_request( exchange(addr, &head, &[], connect, io) } +/// The most of a Payload Manager reply that is read. +const REPLY_MAX: u64 = 8 * 1024 * 1024; + fn exchange( addr: &str, head: &str, @@ -609,9 +612,9 @@ fn exchange( .write_all(head.as_bytes()) .and_then(|()| stream.write_all(body)) .map_err(|e| format!("send to {addr}: {e}"))?; - let mut resp = Vec::new(); - stream - .read_to_end(&mut resp) + // Payload Manager answers with a small JSON or a status line; one that keeps sending is + // refused at the cap instead of filling memory. + let resp = crate::net::read_to_end_capped(&mut stream, REPLY_MAX) .map_err(|e| format!("read from {addr}: {e}"))?; parse_response(&resp).ok_or_else(|| format!("{addr} sent a response that is not HTTP")) } @@ -654,6 +657,34 @@ fn dechunk(mut raw: &[u8]) -> Option> { #[cfg(test)] mod tests { use super::*; + use std::io::Read; + + /// A server on the console's address that answers without end is cut off at the cap: the + /// reply was read whole into memory before. + #[test] + fn an_endless_reply_is_refused_at_the_cap() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let server = std::thread::spawn(move || { + let (mut sock, _) = listener.accept().unwrap(); + let mut head = [0u8; 1024]; + let _ = sock.read(&mut head); + let _ = sock.write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"); + let chunk = vec![b'x'; 64 * 1024]; + // Until the client hangs up. + while sock.write_all(&chunk).is_ok() {} + }); + let e = http_request( + &addr, + "GET", + "/", + Duration::from_secs(2), + Duration::from_secs(5), + ) + .unwrap_err(); + assert!(e.contains("larger than"), "{e}"); + server.join().unwrap(); + } #[test] fn an_upload_replaces_a_stored_copy_only_when_there_is_one() { diff --git a/engine/crates/ps5upload-core/src/rp_regist.rs b/engine/crates/ps5upload-core/src/rp_regist.rs index 114092511..ef9e1594e 100644 --- a/engine/crates/ps5upload-core/src/rp_regist.rs +++ b/engine/crates/ps5upload-core/src/rp_regist.rs @@ -23,7 +23,7 @@ //! rather than filler. The reply is encrypted the same way and carries the //! regist key. -use std::io::{Read, Write}; +use std::io::Write; use std::net::{Shutdown, TcpStream, ToSocketAddrs, UdpSocket}; use std::time::Duration; @@ -40,6 +40,8 @@ type Aes128CfbDec = cfb_mode::Decryptor; /// Registration listens here — not on the discovery port. pub const REGIST_PORT: u16 = 9295; +/// The most of the console's registration reply that is read: a short HTTP answer. +const REGIST_REPLY_MAX: u64 = 1024 * 1024; /// The PS5 registration path. PS4 uses `/sie/ps4/...` or, before system /// software 8.0, `/sce/rp/regist`; we only ever talk to a PS5. @@ -441,8 +443,9 @@ fn exchange( let _ = stream.shutdown(Shutdown::Write); } let mut raw = Vec::new(); - if let Err(e) = stream.read_to_end(&mut raw) { - if raw.is_empty() { + // The answer is a short HTTP reply; one past the cap is refused, never taken cut short. + if let Err(e) = crate::net::read_to_end_capped_into(&mut stream, REGIST_REPLY_MAX, &mut raw) { + if raw.is_empty() || e.kind() == std::io::ErrorKind::InvalidData { return Err(anyhow!("reading the console's reply: {e}")); } } @@ -1177,6 +1180,7 @@ pub fn pair_with_pin(host: &str, account_id_b64: &str, pin: &str) -> Result; pub(crate) const SESSION_PORT: u16 = 9295; pub(crate) const KEY_SIZE: usize = 16; pub(crate) const RP_VERSION: &str = "1.0"; +/// The most of a session start reply that is read: it is a few hundred bytes of headers. +const RP_REPLY_MAX: u64 = 1024 * 1024; /// The two secrets a pairing produces, both needed to open a session. #[derive(Clone)] @@ -243,7 +245,9 @@ pub(crate) fn session_init_for_wake( let _ = stream.shutdown(Shutdown::Write); let mut raw = Vec::new(); - stream.read_to_end(&mut raw).map_err(|e| { + // The console's answer is a few hundred bytes of headers: the cap keeps a peer that keeps + // sending from filling memory. + crate::net::read_to_end_capped_into(&mut stream, RP_REPLY_MAX, &mut raw).map_err(|e| { crate::core_debug!( "rp session init: {host}: reading the reply failed after {} ms ({} bytes in): {e}", t0.elapsed().as_millis(), diff --git a/engine/crates/ps5upload-engine/src/helper_mirror.rs b/engine/crates/ps5upload-engine/src/helper_mirror.rs index 7c8a1402d..339054d0f 100644 --- a/engine/crates/ps5upload-engine/src/helper_mirror.rs +++ b/engine/crates/ps5upload-engine/src/helper_mirror.rs @@ -525,7 +525,10 @@ async fn ftp_tail( .await .map_err(|e| format!("read: {e}"))?; let mut buf = Vec::new(); - stream + // The tail asked for and no more: a server that ignores REST (or sends without end) would + // otherwise be read whole into memory. + (&mut stream) + .take(max) .read_to_end(&mut buf) .await .map_err(|e| format!("read: {e}"))?; From d3281487ff17869dfcefdf140756170ad9f0eecd Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:45:19 -0800 Subject: [PATCH 18/27] Refuse a directory cycle when extracting from an .ffpkg image A directory entry that pointed back at its own folder or an ancestor was only stopped by the 64-level depth cap. Two such entries in one folder doubled the work at every level, so the extract never finished and kept making folders. Each directory is now walked once; one reached again is refused as a cycle before anything more is written. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- engine/crates/ps5upload-pkg/src/lib.rs | 94 ++++++++++++++++++++++--- engine/crates/ps5upload-pkg/src/ufs2.rs | 12 ++++ 2 files changed, 98 insertions(+), 8 deletions(-) diff --git a/engine/crates/ps5upload-pkg/src/lib.rs b/engine/crates/ps5upload-pkg/src/lib.rs index 85eae55b4..2e6f2f8e8 100644 --- a/engine/crates/ps5upload-pkg/src/lib.rs +++ b/engine/crates/ps5upload-pkg/src/lib.rs @@ -134,7 +134,8 @@ pub fn extract_from_ffpkg( } else if inode.is_dir() { let target = dest_dir.join(leaf_name); create_dir_all(&target).map_err(Ufs2Error::Io)?; - extract_dir_recursive(&mut img, &inode, &target, &mut result, 0)?; + let mut walked = std::collections::HashSet::from([inode.number]); + extract_dir_recursive(&mut img, &inode, &target, &mut result, 0, &mut walked)?; } else { return Err(Ufs2Error::NotFound { component: format!("{leaf_name} (not a file or directory)"), @@ -184,17 +185,18 @@ fn is_safe_child_name(name: &str) -> bool { ) } -fn extract_dir_recursive( - img: &mut Ufs2Image, +fn extract_dir_recursive( + img: &mut Ufs2Image, dir: &ufs2::Inode, dest: &Path, result: &mut FfpkgExtractResult, depth: u32, + walked: &mut std::collections::HashSet, ) -> Result<(), Ufs2Error> { - // Bound recursion against a hostile image with a directory cycle or - // pathological nesting (the block-pointer walk has cycle detection, but - // the directory tree didn't). "." / ".." are already skipped by - // is_safe_child_name, so a cycle requires a crafted non-dotdot entry. + // Bound recursion against pathological nesting. A directory cycle is refused on its own + // (`walked`): an entry naming its own directory or an ancestor is not stopped by the depth + // cap alone, as two such entries in one directory double the work at every level. "." / ".." + // are already skipped by is_safe_child_name, so a cycle requires a crafted non-dotdot entry. if depth > FFPKG_EXTRACT_MAX_DEPTH { return Err(Ufs2Error::WalkTooDeep { max: FFPKG_EXTRACT_MAX_DEPTH, @@ -212,8 +214,15 @@ fn extract_dir_recursive( let child_path = dest.join(&e.name); let child_inode = img.read_inode(e.inode)?; if child_inode.is_dir() { + // Every directory is walked once: one reached again is a cycle (or a directory + // linked twice), refused before anything more is written. + if !walked.insert(child_inode.number) { + return Err(Ufs2Error::DirectoryCycle { + inode: child_inode.number, + }); + } create_dir_all(&child_path).map_err(Ufs2Error::Io)?; - extract_dir_recursive(img, &child_inode, &child_path, result, depth + 1)?; + extract_dir_recursive(img, &child_inode, &child_path, result, depth + 1, walked)?; } else if child_inode.is_file() { let written = extract_file(img, &child_inode, &child_path)?; result.file_count += 1; @@ -2284,6 +2293,75 @@ mod tests { d } + /// A 4 KiB-block image whose root directory (inode 2) lists, besides `.` and `..`, the entries + /// `names`, each a directory entry pointing back at inode 2 itself. + fn looping_root(names: &[&str]) -> ufs2::Ufs2Image>> { + const BS: usize = 4096; + // Inode table in fragments 1..5 (64 inodes of 256 bytes), the root's entries in 5. + let mut image = vec![0u8; 6 * BS]; + let root = BS + 2 * 256; + image[root..root + 2].copy_from_slice(&0x41edu16.to_le_bytes()); + image[root + 16..root + 24].copy_from_slice(&(BS as u64).to_le_bytes()); + image[root + 112..root + 120].copy_from_slice(&5u64.to_le_bytes()); + let mut entries: Vec<&str> = vec![".", ".."]; + entries.extend(names); + let mut at = 5 * BS; + for (i, name) in entries.iter().enumerate() { + let len = if i + 1 == entries.len() { + 6 * BS - at + } else { + (8 + name.len() + 1).next_multiple_of(4) + }; + image[at..at + 4].copy_from_slice(&2u32.to_le_bytes()); + image[at + 4..at + 6].copy_from_slice(&(len as u16).to_le_bytes()); + image[at + 6] = 4; // DT_DIR + image[at + 7] = name.len() as u8; + image[at + 8..at + 8 + name.len()].copy_from_slice(name.as_bytes()); + at += len; + } + let sb = ufs2::Superblock { + block_size: BS as u32, + fragment_size: BS as u32, + size_fragments: 6, + cg_count: 1, + inodes_per_cg: 64, + fragments_per_cg: 6, + iblkno: 1, + volume_name: String::new(), + }; + ufs2::Ufs2Image::from_parts(std::io::Cursor::new(image), sb) + } + + /// A directory that lists itself is refused at once. Two such entries in one directory used + /// to double the work at each of the 64 levels the depth cap allowed: an extract that never + /// ended, making folders all the while. + #[test] + fn a_directory_that_contains_itself_is_refused() { + for names in [&["loop"][..], &["a", "b"][..]] { + let mut img = looping_root(names); + let root = img.read_inode(2).unwrap(); + assert!(root.is_dir()); + let dest = tempdir().join(format!("cycle-{}", names.len())); + let _ = std::fs::remove_dir_all(&dest); + std::fs::create_dir_all(&dest).unwrap(); + let mut result = FfpkgExtractResult { + file_count: 0, + bytes_written: 0, + sample_paths: Vec::new(), + }; + let mut walked = std::collections::HashSet::from([root.number]); + let e = extract_dir_recursive(&mut img, &root, &dest, &mut result, 0, &mut walked) + .unwrap_err(); + assert!( + matches!(e, Ufs2Error::DirectoryCycle { inode: 2 }), + "{names:?}: {e}" + ); + // Nothing was made for the entry that loops. + assert_eq!(std::fs::read_dir(&dest).unwrap().count(), 0, "{names:?}"); + let _ = std::fs::remove_dir_all(&dest); + } + } + #[test] fn a_package_parses_the_same_through_a_reader() { let bytes = build_pkg_multi( diff --git a/engine/crates/ps5upload-pkg/src/ufs2.rs b/engine/crates/ps5upload-pkg/src/ufs2.rs index 6c3025fbd..292abcb67 100644 --- a/engine/crates/ps5upload-pkg/src/ufs2.rs +++ b/engine/crates/ps5upload-pkg/src/ufs2.rs @@ -98,6 +98,10 @@ pub enum Ufs2Error { InodeOutOfRange { inode: u64, max: u64 }, #[error("directory tree exceeds max depth {max} — refusing to recurse (possible cycle or pathological nesting in the image)")] WalkTooDeep { max: u32 }, + /// A directory reached a second time on one walk: an entry names the directory itself or + /// one that was already walked (a cycle, or one directory linked twice). + #[error("directory inode {inode} is linked twice — refusing to walk it again (a directory cycle in the image)")] + DirectoryCycle { inode: u64 }, #[error("inode {inode} would point at block {block} which is past the image's {total_blocks} blocks")] BlockOutOfRange { inode: u64, @@ -332,6 +336,14 @@ pub struct Ufs2Image { pub superblock: Superblock, } +#[cfg(test)] +impl Ufs2Image { + /// An image over `reader` with `superblock` as it is, for fixtures that are not whole images. + pub(crate) fn from_parts(reader: R, superblock: Superblock) -> Self { + Self { reader, superblock } + } +} + impl Ufs2Image { /// Open a `.ffpkg` (or any UFS2 image) by path. Cheap — only /// reads the superblock. From 55a2fe8d3b6c70655f78d381a91d4d5650a45c2d Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:20:36 -0800 Subject: [PATCH 19/27] Catch up to 12.6.29 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- CHANGELOG.md | 2 +- VERSION | 2 +- client/package-lock.json | 4 ++-- client/package.json | 2 +- client/src-tauri/Cargo.lock | 30 ++++++++++++------------ client/src-tauri/Cargo.toml | 2 +- client/src-tauri/tauri.conf.json | 2 +- engine/Cargo.lock | 40 ++++++++++++++++---------------- engine/Cargo.toml | 2 +- payload/include/config.h | 2 +- 10 files changed, 44 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b3e419e..11f6101d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ What's new in ps5upload, written for humans. --- -## Unreleased +## 12.6.29 **Fake packages (FPKG)** - **The "won't start" warning for fake PS5 games is gone.** Fake PS5 games now play up to firmware 13.60, the newest a public jailbreak reaches, so the warning could no longer appear anywhere. The fake-package note keeps its payload list, and a failed launch on 11.61 to 13.60 still says a fake package needs the November 2026 kstuff. Convert marks the package as the usual choice once a game is checked. diff --git a/VERSION b/VERSION index 1e518e280..5c0072e97 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -12.6.28 +12.6.29 diff --git a/client/package-lock.json b/client/package-lock.json index 478b5654c..c722aebef 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1,12 +1,12 @@ { "name": "ps5upload-client", - "version": "12.6.28", + "version": "12.6.29", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ps5upload-client", - "version": "12.6.28", + "version": "12.6.29", "dependencies": { "@tauri-apps/api": "^2.12.5", "@tauri-apps/plugin-dialog": "^2.8.4", diff --git a/client/package.json b/client/package.json index 679095089..b51e2535a 100644 --- a/client/package.json +++ b/client/package.json @@ -2,7 +2,7 @@ "name": "ps5upload-client", "private": true, "type": "module", - "version": "12.6.28", + "version": "12.6.29", "description": "The all-in-one PS5 companion app.", "homepage": "https://github.com/phantomptr/ps5upload", "author": "PhantomPtr ", diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 1b73d0a58..e63897f3f 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.28" +version = "12.6.29" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4752,14 +4752,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.28" +version = "12.6.29" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.28" +version = "12.6.29" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -4768,7 +4768,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.28" +version = "12.6.29" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4777,7 +4777,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.28" +version = "12.6.29" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -4788,7 +4788,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "crc32fast", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -4817,7 +4817,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.28" +version = "12.6.29" dependencies = [ "blake3", "libc", @@ -4834,7 +4834,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4868,7 +4868,7 @@ dependencies = [ [[package]] name = "ps5upload-desktop" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -4910,7 +4910,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4974,7 +4974,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.2", "crc32fast", @@ -4997,7 +4997,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.28" +version = "12.6.29" dependencies = [ "axum", "base64 0.23.1", @@ -5011,7 +5011,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.2", "blake3", @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.28" +version = "12.6.29" dependencies = [ "cc", ] diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 0688206ed..c1be8da2c 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ps5upload-desktop" -version = "12.6.28" +version = "12.6.29" description = "The all-in-one PS5 companion app." license = "GPL-3.0-or-later" edition = "2021" diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index 2f3c40551..c81ef0712 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PS5Upload", - "version": "12.6.28", + "version": "12.6.29", "identifier": "com.phantomptr.ps5upload", "build": { "beforeDevCommand": "npm run dev:vite", diff --git a/engine/Cargo.lock b/engine/Cargo.lock index 4ebdf0bbe..43da054d8 100644 --- a/engine/Cargo.lock +++ b/engine/Cargo.lock @@ -2561,7 +2561,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.28" +version = "12.6.29" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2570,14 +2570,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.28" +version = "12.6.29" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.28" +version = "12.6.29" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -2587,7 +2587,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.28" +version = "12.6.29" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2597,7 +2597,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.28" +version = "12.6.29" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -2608,7 +2608,7 @@ dependencies = [ [[package]] name = "ps5upload-apidoc" -version = "12.6.28" +version = "12.6.29" dependencies = [ "proc-macro2", "quote", @@ -2618,7 +2618,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "crc32fast", @@ -2628,7 +2628,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -2651,7 +2651,7 @@ dependencies = [ [[package]] name = "ps5upload-convert" -version = "12.6.28" +version = "12.6.29" dependencies = [ "libc", "ps5upload-archive", @@ -2666,7 +2666,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.28" +version = "12.6.29" dependencies = [ "blake3", "flate2", @@ -2686,7 +2686,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2720,7 +2720,7 @@ dependencies = [ [[package]] name = "ps5upload-ctest" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -2736,7 +2736,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2804,7 +2804,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.4", "blake3", @@ -2828,7 +2828,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.28" +version = "12.6.29" dependencies = [ "axum", "base64 0.23.1", @@ -2843,7 +2843,7 @@ dependencies = [ [[package]] name = "ps5upload-lab" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -2861,7 +2861,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.28" +version = "12.6.29" dependencies = [ "aes 0.9.4", "blake3", @@ -2873,14 +2873,14 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.28" +version = "12.6.29" dependencies = [ "cc", ] [[package]] name = "ps5upload-tests" -version = "12.6.28" +version = "12.6.29" dependencies = [ "anyhow", "ava1", @@ -2898,7 +2898,7 @@ dependencies = [ [[package]] name = "ps5upload-unrar" -version = "12.6.28" +version = "12.6.29" dependencies = [ "serde", "serde_json", diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 6328b6541..de3be6f31 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -32,7 +32,7 @@ resolver = "2" [workspace.package] edition = "2021" license = "GPL-3.0-or-later" -version = "12.6.28" +version = "12.6.29" [workspace.dependencies] # AVA1 (github.com/phantomptr/ava1): the Rust crate from crates.io; the payload builds the C side diff --git a/payload/include/config.h b/payload/include/config.h index 5b1f768f4..35fe083c4 100644 --- a/payload/include/config.h +++ b/payload/include/config.h @@ -5,7 +5,7 @@ * UI tell apart an old payload still running from a build that includes * a particular fix, without having to boot the console. Keep in sync * with the desktop app's package.json during releases. */ -#define PS5UPLOAD2_VERSION "12.6.28" +#define PS5UPLOAD2_VERSION "12.6.29" /* Author credit — embedded in the startup toast so anyone looking at * the console screen knows who wrote the software that just loaded. * Kept separate from VERSION so release scripts can bump the version From f13835a1bad6fa8934ec191c609a50115af6b3d3 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 03:59:25 -0800 Subject: [PATCH 20/27] Files on phones: Back closes menus first, compact pinned header, long-press selection (#932, #936) System Back (Android app and a phone's browser) now closes the Files row menu, the Add files and Recent lists, and the inline editors before anything else. On the Files listing it then leaves selection mode, then goes up one folder, and only leaves Files from the drive's root. Screens register these steps in one place (lib/systemBack useScreenBack), after any open menu or dialog. A test checks that every menu in the app registers for Back. On a phone (portrait or held sideways) Files gets a compact header pinned over the list: the folder name, search, the drive switcher and a menu with the other actions, and the path under it. Checkboxes show only in selection mode, which a long press on a row starts (or Select in the menu, for a keyboard or D-pad). While selecting, the header shows the count, Select all and cancel, and a bar with Copy, Move to, Rename, Delete and More takes the bottom navigation's place. Tablets and computers keep their layout. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/components/BrowseButton.tsx | 3 + client/src/components/PageHeader.tsx | 5 +- client/src/i18n/locales/ar.ts | 2 + client/src/i18n/locales/bn.ts | 2 + client/src/i18n/locales/de.ts | 2 + client/src/i18n/locales/en.ts | 2 + client/src/i18n/locales/es.ts | 2 + client/src/i18n/locales/fa.ts | 2 + client/src/i18n/locales/fr.ts | 2 + client/src/i18n/locales/hi.ts | 2 + client/src/i18n/locales/hu.ts | 2 + client/src/i18n/locales/id.ts | 2 + client/src/i18n/locales/it.ts | 2 + client/src/i18n/locales/ja.ts | 2 + client/src/i18n/locales/ko.ts | 2 + client/src/i18n/locales/pl.ts | 2 + client/src/i18n/locales/pt-BR.ts | 2 + client/src/i18n/locales/ru.ts | 2 + client/src/i18n/locales/th.ts | 2 + client/src/i18n/locales/tr.ts | 2 + client/src/i18n/locales/vi.ts | 2 + client/src/i18n/locales/zh-CN.ts | 2 + client/src/i18n/locales/zh-TW.ts | 2 + client/src/index.css | 5 + client/src/lib/backCoverage.test.ts | 39 ++ client/src/lib/focusTrap.ts | 31 + client/src/lib/longPress.test.ts | 100 +++ client/src/lib/longPress.ts | 98 +++ client/src/lib/phoneLayout.test.ts | 18 + client/src/lib/phoneLayout.ts | 22 + client/src/lib/systemBack.test.ts | 66 +- client/src/lib/systemBack.ts | 31 +- client/src/screens/FileSystem/PhoneBars.tsx | 198 ++++++ .../FileSystem/RecentPathsDropdown.tsx | 3 + client/src/screens/FileSystem/RowActions.tsx | 16 +- .../src/screens/FileSystem/SelectionBar.tsx | 4 +- client/src/screens/FileSystem/index.tsx | 652 ++++++++++++++---- .../src/screens/FileSystem/phoneFiles.test.ts | 44 ++ client/src/screens/FileSystem/phoneFiles.ts | 48 ++ scripts/i18n-source-hashes.json | 2 + 40 files changed, 1275 insertions(+), 152 deletions(-) create mode 100644 client/src/lib/backCoverage.test.ts create mode 100644 client/src/lib/longPress.test.ts create mode 100644 client/src/lib/longPress.ts create mode 100644 client/src/lib/phoneLayout.test.ts create mode 100644 client/src/lib/phoneLayout.ts create mode 100644 client/src/screens/FileSystem/PhoneBars.tsx create mode 100644 client/src/screens/FileSystem/phoneFiles.test.ts create mode 100644 client/src/screens/FileSystem/phoneFiles.ts diff --git a/client/src/components/BrowseButton.tsx b/client/src/components/BrowseButton.tsx index 6a4b97244..c1c9bc055 100644 --- a/client/src/components/BrowseButton.tsx +++ b/client/src/components/BrowseButton.tsx @@ -8,6 +8,7 @@ import { ChevronDown, FolderOpen, HardDrive, Plus, Server } from "lucide-react"; import type { Connection } from "../api/remote"; import { pickPath, pickPaths, type PickPathOptions } from "../lib/pickPath"; import { isMobile } from "../lib/platform"; +import { useBackDismiss } from "../lib/systemBack"; import { displayPath, isRemotePath } from "../lib/remotePath"; import { useConnectionsStore, type ConnStatus } from "../state/connections"; import { getEngineUrl } from "../state/engine"; @@ -192,6 +193,8 @@ export function BrowseButton(props: BrowseButtonProps) { if (open && !loaded) void load().catch(() => {}); }, [open, loaded, load]); + // System Back closes the list first. + useBackDismiss(open, () => setOpen(false)); // Close on a click outside or Escape. useEffect(() => { if (!open) return; diff --git a/client/src/components/PageHeader.tsx b/client/src/components/PageHeader.tsx index dca260a4d..2db6555cb 100644 --- a/client/src/components/PageHeader.tsx +++ b/client/src/components/PageHeader.tsx @@ -30,6 +30,7 @@ export function PageHeader({ description, right, compact = false, + className = "", }: { /** A small accent glyph beside the title. Optional: the big title alone * says where you are. */ @@ -41,9 +42,11 @@ export function PageHeader({ right?: React.ReactNode; /** Less room under the header, for a dense working screen (the Workshop). */ compact?: boolean; + /** More classes on the header (Files hides it in the phone layout, which has its own). */ + className?: string; }) { return ( -
+
{/* From `sm` the row wraps: the title and the actions share a line when both fit, and otherwise the actions drop under the title. The actions never shrink, so without the wrap a screen with several of them (the diff --git a/client/src/i18n/locales/ar.ts b/client/src/i18n/locales/ar.ts index deccf4253..69afd9a35 100644 --- a/client/src/i18n/locales/ar.ts +++ b/client/src/i18n/locales/ar.ts @@ -329,6 +329,8 @@ fs_busy_copying: "جارٍ النسخ", fs_busy_renaming: "جارٍ إعادة التسمية", fs_busy_creating_folder: "جارٍ إنشاء المجلد", fs_select_all: "تحديد الكل", +fs_select_items: "تحديد", +fs_selection_actions: "إجراءات العناصر المحددة", fs_rename: "إعادة تسمية", faq: "الأسئلة الشائعة", diff --git a/client/src/i18n/locales/bn.ts b/client/src/i18n/locales/bn.ts index 6d3932e0d..093f5352e 100644 --- a/client/src/i18n/locales/bn.ts +++ b/client/src/i18n/locales/bn.ts @@ -334,6 +334,8 @@ fs_busy_copying: "কপি হচ্ছে", fs_busy_renaming: "নাম পরিবর্তন করা হচ্ছে", fs_busy_creating_folder: "ফোল্ডার তৈরি হচ্ছে", fs_select_all: "সব নির্বাচন করুন", +fs_select_items: "নির্বাচন করুন", +fs_selection_actions: "নির্বাচিত আইটেমগুলোর কাজ", fs_rename: "নাম পরিবর্তন", created_by: "তৈরি করেছেন", diff --git a/client/src/i18n/locales/de.ts b/client/src/i18n/locales/de.ts index c354a14b9..77ccd7082 100644 --- a/client/src/i18n/locales/de.ts +++ b/client/src/i18n/locales/de.ts @@ -335,6 +335,8 @@ fs_busy_copying: "Wird kopiert", fs_busy_renaming: "Wird umbenannt", fs_busy_creating_folder: "Ordner wird erstellt", fs_select_all: "Alle auswählen", +fs_select_items: "Auswählen", +fs_selection_actions: "Aktionen für die ausgewählten Elemente", fs_rename: "Umbenennen", created_by: "Erstellt von", diff --git a/client/src/i18n/locales/en.ts b/client/src/i18n/locales/en.ts index 06abacb6c..c7e5347c3 100644 --- a/client/src/i18n/locales/en.ts +++ b/client/src/i18n/locales/en.ts @@ -564,6 +564,8 @@ fs_busy_copying: "Copying", fs_busy_renaming: "Renaming", fs_busy_creating_folder: "Creating folder", fs_select_all: "Select all", +fs_select_items: "Select", +fs_selection_actions: "Actions for the selected items", fs_task_delete: "Delete {name}", fs_task_decompress: "Decompress {name}", fs_task_extract: "Extract {name}", diff --git a/client/src/i18n/locales/es.ts b/client/src/i18n/locales/es.ts index 2a2c6bc47..4c5ceb7c3 100644 --- a/client/src/i18n/locales/es.ts +++ b/client/src/i18n/locales/es.ts @@ -329,6 +329,8 @@ fs_busy_copying: "Copiando", fs_busy_renaming: "Renombrando", fs_busy_creating_folder: "Creando carpeta", fs_select_all: "Seleccionar todo", +fs_select_items: "Seleccionar", +fs_selection_actions: "Acciones para los elementos seleccionados", fs_rename: "Renombrar", faq: "Preguntas frecuentes", diff --git a/client/src/i18n/locales/fa.ts b/client/src/i18n/locales/fa.ts index 1d0fcc9fa..e8569b463 100644 --- a/client/src/i18n/locales/fa.ts +++ b/client/src/i18n/locales/fa.ts @@ -517,6 +517,8 @@ fs_busy_copying: "در حال کپی", fs_busy_renaming: "در حال تغییر نام", fs_busy_creating_folder: "در حال ایجاد پوشه", fs_select_all: "انتخاب همه", +fs_select_items: "انتخاب", +fs_selection_actions: "کارها برای موارد انتخاب‌شده", fs_task_delete: "حذف {name}", fs_task_decompress: "باز کردن فشرده‌سازی {name}", fs_task_extract: "استخراج {name}", diff --git a/client/src/i18n/locales/fr.ts b/client/src/i18n/locales/fr.ts index ac5795fc6..a78c9aac5 100644 --- a/client/src/i18n/locales/fr.ts +++ b/client/src/i18n/locales/fr.ts @@ -329,6 +329,8 @@ fs_busy_copying: "Copie", fs_busy_renaming: "Renommage", fs_busy_creating_folder: "Création du dossier", fs_select_all: "Tout sélectionner", +fs_select_items: "Sélectionner", +fs_selection_actions: "Actions pour les éléments sélectionnés", fs_rename: "Renommer", faq: "FAQ", diff --git a/client/src/i18n/locales/hi.ts b/client/src/i18n/locales/hi.ts index a44ea8a11..3d919eb08 100644 --- a/client/src/i18n/locales/hi.ts +++ b/client/src/i18n/locales/hi.ts @@ -334,6 +334,8 @@ fs_busy_copying: "कॉपी हो रहा है", fs_busy_renaming: "नाम बदला जा रहा है", fs_busy_creating_folder: "फ़ोल्डर बनाया जा रहा है", fs_select_all: "सभी का चयन करें", +fs_select_items: "चुनें", +fs_selection_actions: "चुने गए आइटम के लिए कार्य", fs_rename: "नाम बदलें", created_by: "पारां", diff --git a/client/src/i18n/locales/hu.ts b/client/src/i18n/locales/hu.ts index 4aa74b463..7847a2edf 100644 --- a/client/src/i18n/locales/hu.ts +++ b/client/src/i18n/locales/hu.ts @@ -519,6 +519,8 @@ fs_busy_copying: "Másolás", fs_busy_renaming: "Átnevezés", fs_busy_creating_folder: "Mappa létrehozása", fs_select_all: "Összes kijelölése", +fs_select_items: "Kijelölés", +fs_selection_actions: "Műveletek a kijelölt elemekkel", fs_task_delete: "{name} törlése", fs_task_decompress: "{name} kicsomagolása", fs_task_extract: "{name} kibontása", diff --git a/client/src/i18n/locales/id.ts b/client/src/i18n/locales/id.ts index 286545d20..6dc699568 100644 --- a/client/src/i18n/locales/id.ts +++ b/client/src/i18n/locales/id.ts @@ -334,6 +334,8 @@ fs_busy_copying: "Menyalin", fs_busy_renaming: "Mengganti nama", fs_busy_creating_folder: "Membuat folder", fs_select_all: "Pilih semua", +fs_select_items: "Pilih", +fs_selection_actions: "Tindakan untuk item yang dipilih", fs_rename: "Ganti nama", created_by: "Dibuat oleh", diff --git a/client/src/i18n/locales/it.ts b/client/src/i18n/locales/it.ts index 469a3d53a..c6ee76f05 100644 --- a/client/src/i18n/locales/it.ts +++ b/client/src/i18n/locales/it.ts @@ -334,6 +334,8 @@ fs_busy_copying: "Copia", fs_busy_renaming: "Rinominazione", fs_busy_creating_folder: "Creazione cartella", fs_select_all: "Seleziona tutto", +fs_select_items: "Seleziona", +fs_selection_actions: "Azioni per gli elementi selezionati", fs_rename: "Rinomina", created_by: "Creato da", diff --git a/client/src/i18n/locales/ja.ts b/client/src/i18n/locales/ja.ts index 4eb5b37cc..e6ad901d9 100644 --- a/client/src/i18n/locales/ja.ts +++ b/client/src/i18n/locales/ja.ts @@ -335,6 +335,8 @@ fs_busy_copying: "コピー中", fs_busy_renaming: "リネーム中", fs_busy_creating_folder: "フォルダ作成中", fs_select_all: "すべて選択", +fs_select_items: "選択", +fs_selection_actions: "選択した項目の操作", fs_rename: "名前変更", created_by: "作成者", diff --git a/client/src/i18n/locales/ko.ts b/client/src/i18n/locales/ko.ts index d1ef22208..4743122fa 100644 --- a/client/src/i18n/locales/ko.ts +++ b/client/src/i18n/locales/ko.ts @@ -335,6 +335,8 @@ fs_busy_copying: "복사 중", fs_busy_renaming: "이름 변경 중", fs_busy_creating_folder: "폴더 생성 중", fs_select_all: "모두 선택", +fs_select_items: "선택", +fs_selection_actions: "선택한 항목에 대한 작업", fs_rename: "이름 변경", created_by: "제작자", diff --git a/client/src/i18n/locales/pl.ts b/client/src/i18n/locales/pl.ts index 3313e66e3..96cf03b81 100644 --- a/client/src/i18n/locales/pl.ts +++ b/client/src/i18n/locales/pl.ts @@ -507,6 +507,8 @@ fs_busy_copying: "Kopiowanie", fs_busy_renaming: "Zmiana nazwy", fs_busy_creating_folder: "Tworzenie folderu", fs_select_all: "Zaznacz wszystko", +fs_select_items: "Zaznacz", +fs_selection_actions: "Działania dla zaznaczonych elementów", fs_task_delete: "Usuń {name}", fs_task_decompress: "Dekompresuj {name}", fs_task_extract: "Wypakuj {name}", diff --git a/client/src/i18n/locales/pt-BR.ts b/client/src/i18n/locales/pt-BR.ts index 1292241a9..d1e50d3d5 100644 --- a/client/src/i18n/locales/pt-BR.ts +++ b/client/src/i18n/locales/pt-BR.ts @@ -334,6 +334,8 @@ fs_busy_copying: "Copiando", fs_busy_renaming: "Renomeando", fs_busy_creating_folder: "Criando pasta", fs_select_all: "Selecionar tudo", +fs_select_items: "Selecionar", +fs_selection_actions: "Ações para os itens selecionados", fs_rename: "Renomear", created_by: "Criada por", diff --git a/client/src/i18n/locales/ru.ts b/client/src/i18n/locales/ru.ts index 5cb31d9ab..c43b8f088 100644 --- a/client/src/i18n/locales/ru.ts +++ b/client/src/i18n/locales/ru.ts @@ -334,6 +334,8 @@ fs_busy_copying: "Копирование", fs_busy_renaming: "Переименование", fs_busy_creating_folder: "Создание папки", fs_select_all: "Выбрать всё", +fs_select_items: "Выбрать", +fs_selection_actions: "Действия с выбранными элементами", fs_rename: "Переименовать", created_by: "Автор", diff --git a/client/src/i18n/locales/th.ts b/client/src/i18n/locales/th.ts index 787f5902d..4da30dc72 100644 --- a/client/src/i18n/locales/th.ts +++ b/client/src/i18n/locales/th.ts @@ -334,6 +334,8 @@ fs_busy_copying: "กำลังคัดลอก", fs_busy_renaming: "กำลังเปลี่ยนชื่อ", fs_busy_creating_folder: "กำลังสร้างโฟลเดอร์", fs_select_all: "เลือกทั้งหมด", +fs_select_items: "เลือก", +fs_selection_actions: "การทำงานกับรายการที่เลือก", fs_rename: "เปลี่ยนชื่อ", created_by: "สร้างโดย", diff --git a/client/src/i18n/locales/tr.ts b/client/src/i18n/locales/tr.ts index 98dd17aa0..6e445bf41 100644 --- a/client/src/i18n/locales/tr.ts +++ b/client/src/i18n/locales/tr.ts @@ -334,6 +334,8 @@ fs_busy_copying: "Kopyalanıyor", fs_busy_renaming: "Yeniden adlandırılıyor", fs_busy_creating_folder: "Klasör oluşturuluyor", fs_select_all: "Tümünü seç", +fs_select_items: "Seç", +fs_selection_actions: "Seçili öğeler için işlemler", fs_rename: "Yeniden adlandır", created_by: "Oluşturan", diff --git a/client/src/i18n/locales/vi.ts b/client/src/i18n/locales/vi.ts index c7dfb92a4..d4efde988 100644 --- a/client/src/i18n/locales/vi.ts +++ b/client/src/i18n/locales/vi.ts @@ -335,6 +335,8 @@ fs_busy_copying: "Đang sao chép", fs_busy_renaming: "Đang đổi tên", fs_busy_creating_folder: "Đang tạo thư mục", fs_select_all: "Chọn tất cả", +fs_select_items: "Chọn", +fs_selection_actions: "Thao tác cho các mục đã chọn", fs_rename: "Đổi tên", created_by: "Được tạo bởi", diff --git a/client/src/i18n/locales/zh-CN.ts b/client/src/i18n/locales/zh-CN.ts index 7d9b1f09c..0bd61df6f 100644 --- a/client/src/i18n/locales/zh-CN.ts +++ b/client/src/i18n/locales/zh-CN.ts @@ -336,6 +336,8 @@ fs_busy_copying: "正在复制", fs_busy_renaming: "正在重命名", fs_busy_creating_folder: "正在创建文件夹", fs_select_all: "全选", +fs_select_items: "选择", +fs_selection_actions: "所选项目的操作", fs_rename: "重命名", faq: "常见问题解答", diff --git a/client/src/i18n/locales/zh-TW.ts b/client/src/i18n/locales/zh-TW.ts index 7fce80eb5..198c14a16 100644 --- a/client/src/i18n/locales/zh-TW.ts +++ b/client/src/i18n/locales/zh-TW.ts @@ -330,6 +330,8 @@ fs_busy_copying: "正在複製", fs_busy_renaming: "正在重新命名", fs_busy_creating_folder: "正在建立資料夾", fs_select_all: "全選", +fs_select_items: "選擇", +fs_selection_actions: "所選項目的操作", fs_rename: "重新命名", faq: "常見問題", diff --git a/client/src/index.css b/client/src/index.css index 7ab31f205..3866eef2f 100644 --- a/client/src/index.css +++ b/client/src/index.css @@ -1181,6 +1181,11 @@ body { of the screen, and these fixed bars would take up a good part of it. */ html[data-keyboard] [data-bottom-nav], html[data-keyboard] [data-testid="activity-pill"] { display: none !important; } +/* Selecting in Files on a phone (#936): the selection's actions take the bottom bar's place. The + same query as the `phone:` variant, where that bar of actions shows. */ +@media not all and (min-width: 40rem), (pointer: coarse) and (max-height: 520px) { + html[data-selection-bar] [data-bottom-nav] { display: none !important; } +} /* The tabs down a column the system leaves empty (an iPhone Duo folded, TabNav.tsx useSideRail): under its icons, at the bottom where a thumb reaches, and the page gets its height back. */ .tab-rail-probe { diff --git a/client/src/lib/backCoverage.test.ts b/client/src/lib/backCoverage.test.ts new file mode 100644 index 000000000..0a5120f59 --- /dev/null +++ b/client/src/lib/backCoverage.test.ts @@ -0,0 +1,39 @@ +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +// System Back on a phone closes what is open on top (lib/systemBack), but only what registered +// for it. The Files row menu did not, and Back left the Files tab with the menu still up (#932). +// Every menu has to take part: through useBackDismiss, or a modal surface's focus trap. + +const SRC = fileURLToPath(new URL("..", import.meta.url)); + +/** Menus that handle Back another way. */ +const OWN_BACK: Record = { + // Remote Play's stream menu: the stream screen takes Back itself (its own popstate handler). + "screens/Play/StreamPanel.tsx": "popstate", +}; + +function sources(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const p = join(dir, name); + if (statSync(p).isDirectory()) return name === "console" ? [] : sources(p); + return /\.tsx$/.test(name) && !/\.test\.tsx$/.test(name) ? [p] : []; + }); +} + +describe("system Back reaches every menu", () => { + it("each file that draws a menu registers it for Back", () => { + const missing = sources(SRC) + .filter((p) => readFileSync(p, "utf8").includes('role="menu"')) + .map((p) => ({ rel: relative(SRC, p).split("\\").join("/"), text: readFileSync(p, "utf8") })) + .filter(({ rel, text }) => { + const own = OWN_BACK[rel]; + if (own) return !text.includes(own); + return !/useBackDismiss\(|activateFocusTrap\(| rel); + expect(missing).toEqual([]); + }); +}); diff --git a/client/src/lib/focusTrap.ts b/client/src/lib/focusTrap.ts index 8fcce7770..96bc9f878 100644 --- a/client/src/lib/focusTrap.ts +++ b/client/src/lib/focusTrap.ts @@ -132,6 +132,37 @@ export function closeTopModal(): boolean { return true; } +/** What system Back does on the screen itself once nothing covers it (leave selection mode, go up + * a folder), newest last. Kept apart from `backOrder`: these are steps of a screen, not surfaces + * over it, so they never count as an open dialog (lib/tvNav keeps focus inside one). */ +const screenSteps: Array<() => void> = []; + +/** A step of the screen on show that system Back takes once no surface is open. Returns the undo. */ +export function registerScreenBack(step: () => void): () => void { + screenSteps.push(step); + stackChanged(); + return () => { + const at = screenSteps.lastIndexOf(step); + if (at !== -1) screenSteps.splice(at, 1); + stackChanged(); + }; +} + +/** How many presses of system Back the page would take before the history moves. Zero: none. */ +export function backStepCount(): number { + return backOrder.length + screenSteps.length; +} + +/** One press of system Back: the top surface first, else the screen's newest step. False when + * neither has anything, and the history should move. */ +export function takeBackStep(): boolean { + if (closeTopModal()) return true; + const step = screenSteps[screenSteps.length - 1]; + if (!step) return false; + step(); + return true; +} + /** A surface that is not modal (a sheet, a menu) but that system Back should close first. Returns * the undo. Escape stays its own business. */ export function registerBackDismiss(close: () => void): () => void { diff --git a/client/src/lib/longPress.test.ts b/client/src/lib/longPress.test.ts new file mode 100644 index 000000000..66bd7638c --- /dev/null +++ b/client/src/lib/longPress.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from "vitest"; + +import { createLongPress, LONG_PRESS_MS } from "./longPress"; + +function setup() { + const fired: string[] = []; + let pending: { fn: () => void; at: number } | null = null; + let now = 0; + const timers = { + set: (fn: () => void, ms: number) => (pending = { fn, at: now + ms }), + clear: () => void (pending = null), + }; + const lp = createLongPress((t) => fired.push(t), { timers }); + const wait = (ms: number) => { + now += ms; + if (pending && pending.at <= now) { + const { fn } = pending; + pending = null; + fn(); + } + }; + return { lp, fired, wait }; +} + +describe("long press", () => { + it("fires after the finger holds still, once", () => { + const { lp, fired, wait } = setup(); + lp.down("a", 10, 10, "touch"); + wait(LONG_PRESS_MS - 1); + expect(fired).toEqual([]); + wait(1); + expect(fired).toEqual(["a"]); + // Android also reports it as a context menu: the same press, not a second one, and no menu. + expect(lp.contextMenu()).toBe(true); + expect(fired).toEqual(["a"]); + }); + + it("swallows the click of the finger lifting, and only that one", () => { + const { lp, wait } = setup(); + lp.down("a", 0, 0, "touch"); + wait(LONG_PRESS_MS); + lp.end(); + expect(lp.takeClick()).toBe(true); + expect(lp.takeClick()).toBe(false); + }); + + it("is a tap when the finger lifts early", () => { + const { lp, fired, wait } = setup(); + lp.down("a", 0, 0, "touch"); + wait(100); + lp.end(); + wait(LONG_PRESS_MS); + expect(fired).toEqual([]); + expect(lp.takeClick()).toBe(false); + }); + + it("is a scroll when the finger moves away", () => { + const { lp, fired, wait } = setup(); + lp.down("a", 0, 0, "touch"); + lp.move(3, 4); // 5 px: still holding + lp.move(0, 30); + wait(LONG_PRESS_MS); + expect(fired).toEqual([]); + }); + + it("takes no mouse or pen: a right-click keeps its menu", () => { + const { lp, fired, wait } = setup(); + lp.down("a", 0, 0, "mouse"); + wait(LONG_PRESS_MS); + expect(fired).toEqual([]); + expect(lp.contextMenu()).toBe(false); + }); + + it("ends early on the browser's own long press", () => { + const { lp, fired, wait } = setup(); + lp.down("b", 0, 0, "touch"); + wait(300); + expect(lp.contextMenu()).toBe(true); + expect(fired).toEqual(["b"]); + wait(LONG_PRESS_MS); + expect(fired).toEqual(["b"]); + }); + + it("runs on real timers", () => { + vi.useFakeTimers(); + try { + const fired: string[] = []; + const lp = createLongPress((t) => fired.push(t)); + lp.down("c", 0, 0, "touch"); + vi.advanceTimersByTime(LONG_PRESS_MS); + expect(fired).toEqual(["c"]); + lp.down("d", 0, 0, "touch"); + lp.dispose(); + vi.advanceTimersByTime(LONG_PRESS_MS); + expect(fired).toEqual(["c"]); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/client/src/lib/longPress.ts b/client/src/lib/longPress.ts new file mode 100644 index 000000000..810a5e698 --- /dev/null +++ b/client/src/lib/longPress.ts @@ -0,0 +1,98 @@ +// A long press with a finger: hold still on one spot for a moment. Files starts selecting with it +// on a phone (#936), as a phone's own file managers do. +// +// The browser can report the same press as a `contextmenu` event too (Android does, about when the +// hold is long enough), so either one ends the press, once. The tap that lifts the finger is not +// a tap: the click after a long press is swallowed, or it would also open the folder under it. + +/** How long a finger holds still before it counts (Android's own long press is 400-500 ms). */ +export const LONG_PRESS_MS = 500; +/** How far a finger may drift and still be holding still. More is a scroll. */ +export const LONG_PRESS_SLOP_PX = 10; + +export interface LongPress { + /** A pointer went down on `target`. Only a finger (touch) starts a press. */ + down(target: T, x: number, y: number, pointerType: string): void; + move(x: number, y: number): void; + /** The finger lifted, or the browser took the touch over (a scroll). */ + end(): void; + /** The browser's own long press (`contextmenu`) for the press under way. True when it was + * this press's, and its menu should not open. */ + contextMenu(): boolean; + /** Call for each click: true for the one right after a long press, to swallow. */ + takeClick(): boolean; + /** Stop any timer (unmount). */ + dispose(): void; +} + +type Timers = { + set: (fn: () => void, ms: number) => unknown; + clear: (id: unknown) => void; +}; + +const realTimers: Timers = { + set: (fn, ms) => setTimeout(fn, ms), + clear: (id) => clearTimeout(id as ReturnType), +}; + +export function createLongPress( + onLongPress: (target: T) => void, + options: { ms?: number; slop?: number; timers?: Timers } = {}, +): LongPress { + const ms = options.ms ?? LONG_PRESS_MS; + const slop = options.slop ?? LONG_PRESS_SLOP_PX; + const timers = options.timers ?? realTimers; + let press: { target: T; x: number; y: number; fired: boolean } | null = null; + let timer: unknown = null; + let swallowClick = false; + + const stopTimer = () => { + if (timer !== null) timers.clear(timer); + timer = null; + }; + const fire = () => { + stopTimer(); + if (!press || press.fired) return; + press.fired = true; + swallowClick = true; + onLongPress(press.target); + }; + + return { + down(target, x, y, pointerType) { + stopTimer(); + swallowClick = false; + press = null; + if (pointerType !== "touch") return; + press = { target, x, y, fired: false }; + timer = timers.set(fire, ms); + }, + move(x, y) { + if (!press || press.fired) return; + if (Math.hypot(x - press.x, y - press.y) > slop) { + stopTimer(); + press = null; + } + }, + end() { + stopTimer(); + press = null; + }, + contextMenu() { + // Already a long press (the timer won): its menu stays shut even after the finger lifted. + if (swallowClick) return true; + if (!press) return false; + fire(); + return true; + }, + takeClick() { + const swallow = swallowClick; + swallowClick = false; + return swallow; + }, + dispose() { + stopTimer(); + press = null; + }, + }; +} diff --git a/client/src/lib/phoneLayout.test.ts b/client/src/lib/phoneLayout.test.ts new file mode 100644 index 000000000..d065753b0 --- /dev/null +++ b/client/src/lib/phoneLayout.test.ts @@ -0,0 +1,18 @@ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +import { PHONE_LAYOUT_QUERY } from "./phoneLayout"; + +const css = readFileSync(fileURLToPath(new URL("../index.css", import.meta.url)), "utf8"); + +describe("the phone layout's query", () => { + it("is the `phone:` variant's, so the script and the styles agree on what a phone is", () => { + const variant = css.match(/@custom-variant phone \{\s*@media ([^{]+)\{/); + expect(variant?.[1].trim()).toBe(PHONE_LAYOUT_QUERY); + }); + + it("is where the selection bar hides the bottom navigation (#936)", () => { + expect(css).toContain(`@media ${PHONE_LAYOUT_QUERY} {\n html[data-selection-bar] [data-bottom-nav]`); + }); +}); diff --git a/client/src/lib/phoneLayout.ts b/client/src/lib/phoneLayout.ts new file mode 100644 index 000000000..ff95499e7 --- /dev/null +++ b/client/src/lib/phoneLayout.ts @@ -0,0 +1,22 @@ +import { useSyncExternalStore } from "react"; + +/** The phone layout, as the `phone:` variant in index.css has it: narrower than `sm`, or a touch + * screen held sideways (about 520 px tall or less). Keep the two the same. */ +export const PHONE_LAYOUT_QUERY = + "not all and (min-width: 40rem), (pointer: coarse) and (max-height: 520px)"; + +function subscribe(onChange: () => void): () => void { + if (typeof window === "undefined" || !window.matchMedia) return () => {}; + const mq = window.matchMedia(PHONE_LAYOUT_QUERY); + mq.addEventListener?.("change", onChange); + return () => mq.removeEventListener?.("change", onChange); +} + +function snapshot(): boolean { + return typeof window !== "undefined" && !!window.matchMedia?.(PHONE_LAYOUT_QUERY).matches; +} + +/** True while the phone layout is on show (the `phone:` variant), live. */ +export function usePhoneLayout(): boolean { + return useSyncExternalStore(subscribe, snapshot, () => false); +} diff --git a/client/src/lib/systemBack.test.ts b/client/src/lib/systemBack.test.ts index 8e51ece68..e6de7c008 100644 --- a/client/src/lib/systemBack.test.ts +++ b/client/src/lib/systemBack.test.ts @@ -1,6 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { activateFocusTrap, closeTopModal, openModalCount, registerBackDismiss } from "./focusTrap"; +import { + activateFocusTrap, + backStepCount, + closeTopModal, + openModalCount, + registerBackDismiss, + registerScreenBack, +} from "./focusTrap"; import { installAppBack, installBrowserBack } from "./systemBack"; // No jsdom in this repo: just enough of `document`, KeyboardEvent and a window's history. @@ -169,6 +176,63 @@ describe("Back in a phone's browser", () => { }); }); +describe("a screen's own steps (Files: leave selection mode, go up a folder)", () => { + it("come after every surface, newest step first, and leave the history alone until none is left", () => { + const w = {} as Window; + installAppBack(w); + const did: string[] = []; + const up = registerScreenBack(() => did.push("up")); + const menu = registerBackDismiss(() => did.push("menu")); + const select = registerScreenBack(() => did.push("end selection")); + // A screen step is not a dialog: focus is not kept inside one for it (lib/tvNav). + expect(openModalCount()).toBe(1); + expect(backStepCount()).toBe(3); + expect(w.__ps5uBack?.()).toBe(true); + menu(); + expect(w.__ps5uBack?.()).toBe(true); + select(); + expect(w.__ps5uBack?.()).toBe(true); + up(); + expect(did).toEqual(["menu", "end selection", "up"]); + expect(w.__ps5uBack?.()).toBe(false); + expect(closeTopModal()).toBe(false); + }); + + it("hold a history entry in a phone's browser, and take it again while the screen has more", () => { + vi.useFakeTimers(); + const pop = new Set<() => void>(); + const h = { state: null, pushState: vi.fn(), back: vi.fn() }; + const w = { + location: { href: "http://nas/files" }, + history: h, + addEventListener: (_t: string, fn: () => void) => void pop.add(fn), + removeEventListener: (_t: string, fn: () => void) => void pop.delete(fn), + } as unknown as Window; + const off = installBrowserBack(w); + let depth = 2; + let undo: (() => void) | null = registerScreenBack(() => { + depth -= 1; + if (depth === 0) { + undo?.(); + undo = null; + } + }); + vi.runAllTimers(); + expect(h.pushState).toHaveBeenCalledTimes(1); + pop.forEach((f) => f()); + vi.runAllTimers(); + // Still a folder to go up to: Back stays with the screen. + expect(depth).toBe(1); + expect(h.pushState).toHaveBeenCalledTimes(2); + pop.forEach((f) => f()); + vi.runAllTimers(); + expect(depth).toBe(0); + expect(h.pushState).toHaveBeenCalledTimes(2); + expect(h.back).not.toHaveBeenCalled(); + off(); + }); +}); + describe("a surface that is not modal (a sheet, a menu)", () => { it("closes on Back, newest first, in order with the modals", () => { const closed: string[] = []; diff --git a/client/src/lib/systemBack.ts b/client/src/lib/systemBack.ts index c7626717d..8bc9f021f 100644 --- a/client/src/lib/systemBack.ts +++ b/client/src/lib/systemBack.ts @@ -9,7 +9,13 @@ import { useEffect, useRef } from "react"; -import { closeTopModal, onModalStackChange, openModalCount, registerBackDismiss } from "./focusTrap"; +import { + backStepCount, + onModalStackChange, + registerBackDismiss, + registerScreenBack, + takeBackStep, +} from "./focusTrap"; import { isMobile } from "./platform"; import { isTauriEnv } from "./tauriEnv"; import { isTvDevice } from "./tvNav"; @@ -23,7 +29,7 @@ declare global { /** The app: the shell calls this, and moves the history itself when it answers false. */ export function installAppBack(w: Window = window): void { - w.__ps5uBack = () => closeTopModal(); + w.__ps5uBack = () => takeBackStep(); } /** A browser: returns the undo. */ @@ -35,7 +41,7 @@ export function installBrowserBack(w: Window = window): () => void { const reconcile = () => { settle = null; - const open = openModalCount() > 0; + const open = backStepCount() > 0; if (open && !held) { // Same state as the page's own entry: the router sees no navigation. w.history.pushState(w.history.state, ""); @@ -55,8 +61,9 @@ export function installBrowserBack(w: Window = window): () => void { const onPop = () => { if (!held) return; held = false; - closeTopModal(); - // Something still open (or one that refused Escape): Back stays with it. + takeBackStep(); + // Something still open (or one that refused Escape), or the screen has another step: Back + // stays with it. schedule(); }; w.addEventListener("popstate", onPop); @@ -81,6 +88,20 @@ export function useBackDismiss(open: boolean, close: () => void): void { }, [open]); } +/** While `active`, system Back runs `step` on the screen itself once no surface covers it (leave + * selection mode, go up a folder). A kept screen that is hidden has its effects torn down, so + * only the screen on show has a step: Back never acts on one out of sight. */ +export function useScreenBack(active: boolean, step: () => void): void { + const latest = useRef(step); + useEffect(() => { + latest.current = step; + }); + useEffect(() => { + if (!active) return; + return registerScreenBack(() => latest.current()); + }, [active]); +} + let installed = false; /** Once, at start-up. */ diff --git a/client/src/screens/FileSystem/PhoneBars.tsx b/client/src/screens/FileSystem/PhoneBars.tsx new file mode 100644 index 000000000..3f3ee2dc3 --- /dev/null +++ b/client/src/screens/FileSystem/PhoneBars.tsx @@ -0,0 +1,198 @@ +// The Files bars of the phone layout (#936): the top row of the pinned header, and the bar of +// selection actions that takes the bottom navigation's place while selecting. Tablets and +// computers never show either (`roomy:hidden`); they keep the page header and the selection bar. + +import type { ComponentType } from "react"; +import { CheckCheck, FolderOpen, MoreVertical, Search, X } from "lucide-react"; + +import { Spinner } from "../../components"; + +type IconType = ComponentType<{ size?: number; className?: string }>; + +const ICON_BUTTON = + "grid h-10 w-10 shrink-0 place-items-center rounded-full text-[var(--color-text)] hover:bg-[var(--color-surface-3)] disabled:opacity-40 aria-expanded:bg-[var(--color-surface-3)] aria-pressed:text-[var(--color-accent-bright)]"; + +/** A round icon button whose name is its label (read out, and the tooltip). */ +function IconButton({ + icon: Icon, + label, + onClick, + menu, + pressed, + disabled, + testId, +}: { + icon: IconType; + label: string; + onClick: (box: DOMRect) => void; + /** Opens a menu: whether it is open. */ + menu?: boolean; + pressed?: boolean; + disabled?: boolean; + testId?: string; +}) { + return ( + + ); +} + +/** The top row of the pinned header: the open folder, search, the drive and ⋮. */ +export function PhoneFolderRow({ + title, + loading, + searchLabel, + onSearch, + driveIcon, + driveLabel, + drivesOpen, + onDrives, + moreLabel, + moreOpen, + onMore, + disabled, +}: { + title: string; + loading: boolean; + searchLabel: string; + onSearch: () => void; + /** Null: no drive to switch to (none listed yet). */ + driveIcon: IconType | null; + driveLabel: string; + drivesOpen: boolean; + onDrives: (box: DOMRect) => void; + moreLabel: string; + moreOpen: boolean; + onMore: (box: DOMRect) => void; + /** No console to act on. */ + disabled: boolean; +}) { + return ( +
+ +

+ {title} +

+ {loading && } + + {driveIcon && ( + + )} + +
+ ); +} + +/** The same row in selection mode: cancel, how many, and Select all. */ +export function PhoneSelectionRow({ + countLabel, + cancelLabel, + onCancel, + selectAllLabel, + allSelected, + onSelectAll, +}: { + countLabel: string; + cancelLabel: string; + onCancel: () => void; + selectAllLabel: string; + allSelected: boolean; + onSelectAll: () => void; +}) { + return ( +
+ + + {countLabel} + + +
+ ); +} + +export interface PhoneBarAction { + id: string; + icon: IconType; + label: string; + run: (box: DOMRect) => void; + disabled?: boolean; + tone?: "bad"; + /** Opens a menu: whether it is open. */ + menu?: boolean; +} + +/** The actions for the selected items, where the bottom navigation is (it hides meanwhile: + * `html[data-selection-bar]` in index.css). */ +export function PhoneSelectionActions({ + label, + actions, +}: { + /** The toolbar's name, read out. */ + label: string; + actions: PhoneBarAction[]; +}) { + return ( +
+ {actions.map((a) => ( + + ))} +
+ ); +} diff --git a/client/src/screens/FileSystem/RecentPathsDropdown.tsx b/client/src/screens/FileSystem/RecentPathsDropdown.tsx index 548f3e166..2dbaf40b9 100644 --- a/client/src/screens/FileSystem/RecentPathsDropdown.tsx +++ b/client/src/screens/FileSystem/RecentPathsDropdown.tsx @@ -1,6 +1,7 @@ import { useMemo, useRef, useState } from "react"; import { ChevronRight, Star, StarOff } from "lucide-react"; +import { useBackDismiss } from "../../lib/systemBack"; import { useTr } from "../../state/lang"; import { useRecentPathsStore } from "../../state/recentPaths"; import { useFitOnScreen } from "../../components/useFitOnScreen"; @@ -152,6 +153,8 @@ export function RecentPathsDropdown({ const remove = useRecentPathsStore((s) => s.remove); const clear = useRecentPathsStore((s) => s.clear); const [open, setOpen] = useState(false); + // System Back closes the list first. + useBackDismiss(open, () => setOpen(false)); // Filter out the current path — no value in offering "go where you // already are." Keeps the list focused on actual destinations. diff --git a/client/src/screens/FileSystem/RowActions.tsx b/client/src/screens/FileSystem/RowActions.tsx index f2d0dfc5a..70fecb743 100644 --- a/client/src/screens/FileSystem/RowActions.tsx +++ b/client/src/screens/FileSystem/RowActions.tsx @@ -10,6 +10,7 @@ import { createPortal } from "react-dom"; import { Archive, BadgeCheck, + Check, Download, Eye, EyeOff, @@ -29,6 +30,7 @@ import { import { Spinner } from "../../components"; import { menuKeyAction } from "../../lib/menuKeys"; +import { useBackDismiss } from "../../lib/systemBack"; import { isInstallPackagePath } from "../../lib/pkgDropDedupe"; import { isExtractableArchive } from "../../lib/archiveName"; import type { Translator } from "../../state/lang"; @@ -63,6 +65,8 @@ export interface RowMenuItem { run: () => void; disabled?: boolean; destructive?: boolean; + /** The one in use among several (the drive you are on): marked, and read out as current. */ + current?: boolean; } export function rowActionMenuItems(actions: RowAction[]): RowMenuItem[] { @@ -407,11 +411,14 @@ export function RowActionsTrigger({ label, open, onToggle, + hidden = false, }: { label: string; open: boolean; /** Called with the trigger's box, for the menu to sit against. */ onToggle: (anchor: DOMRect) => void; + /** Selection mode on a phone: a tap selects the row, the bar at the bottom has the actions. */ + hidden?: boolean; }) { return ( @@ -499,6 +506,8 @@ export function RowMenu({ onClose: () => void; }) { const ref = useRef(null); + // System Back closes the menu and stays in the folder (#932): before, it left the Files tab. + useBackDismiss(true, onClose); const [pos, setPos] = useState<{ left: number; top: number; maxHeight?: number }>({ left: x, top: y }); useLayoutEffect(() => { const el = ref.current; @@ -625,14 +634,17 @@ export function RowMenuList({ role="menuitem" tabIndex={-1} disabled={it.disabled} + aria-current={it.current ? "true" : undefined} onClick={() => onPick(it)} className={ "flex w-full items-center gap-2 rounded-full px-3 py-1.5 text-start hover:bg-[var(--color-surface-3)] focus:bg-[var(--color-surface-3)] disabled:opacity-40 " + - (it.destructive ? "text-[var(--color-bad)]" : "") + (it.destructive ? "text-[var(--color-bad)] " : "") + + (it.current ? "font-medium text-[var(--color-accent-bright)]" : "") } > {it.label} + {it.current && } )); } diff --git a/client/src/screens/FileSystem/SelectionBar.tsx b/client/src/screens/FileSystem/SelectionBar.tsx index 2e09fd2e1..58349b06b 100644 --- a/client/src/screens/FileSystem/SelectionBar.tsx +++ b/client/src/screens/FileSystem/SelectionBar.tsx @@ -15,17 +15,19 @@ export function SelectionBar({ clearLabel, onClear, children, + className = "", }: { countLabel: string; clearLabel: string; onClear: () => void; /** The action buttons (use SELECTION_ACTION for their class). */ children: ReactNode; + className?: string; }) { return (
{countLabel}
(null); const [selected, setSelected] = useState>(new Set()); + // Selection mode on a phone with nothing ticked yet: "Select" in the ⋮ menu, the way in for a + // keyboard or a D-pad (a finger long-presses a row). Ends with the selection (#936). + const [selectMode, setSelectMode] = useState(false); const [localBusy, setBusyEntry] = useState<{ name: string; op: "rename" | "mkdir"; @@ -915,9 +926,20 @@ export default function FileSystemScreen() { // under the new path, and their actions join that path with their names. useEffect(() => { setSelected(new Set()); + setSelectMode(false); setEntries(null); setMeshHome(false); }, [host, path]); + // Selection mode ends with the selection: the last row unticked, or an action that used it + // (Copy, Move…). It stays only while nothing was ticked yet since "Select" opened it. + const hadSelection = useRef(false); + useEffect(() => { + if (selected.size > 0) hadSelection.current = true; + else if (hadSelection.current) { + hadSelection.current = false; + setSelectMode(false); + } + }, [selected]); const toggleSelected = (name: string) => { setSelected((s) => { @@ -3090,6 +3112,60 @@ export default function FileSystemScreen() { return best; }, [volumes, path]); + // ── The phone layout (#936) and system Back (#932) ───────────────────────────────────── + const phone = usePhoneLayout(); + const selecting = selectMode || selectionActive; + /** Selection mode as the phone shows it: checkboxes, the selection row, the bottom bar. */ + const phoneSelecting = phone && selecting && view === null; + const endSelection = () => { + setSelected(new Set()); + setSelectMode(false); + }; + // The header's menus on a phone: ⋮ (the page's actions), the drives, where "Add files" reads + // from, and the bottom bar's More. + const [phoneMenu, setPhoneMenu] = useState<{ + kind: "more" | "drives" | "add-file" | "add-folder" | "selection"; + anchor: DOMRect; + } | null>(null); + const togglePhoneMenu = (kind: NonNullable["kind"], anchor: DOMRect) => + setPhoneMenu((cur) => (cur?.kind === kind ? null : { kind, anchor })); + // Back on the listing once nothing covers it: selection mode first, then up one folder; from + // the drive's root it leaves Files. Menus, dialogs and the inline editors close before that. + const backState = { view: view !== null, selecting, path, driveRoot: currentVolumePath }; + useScreenBack(filesBackStep(backState) !== null, () => { + const step = filesBackStep(backState); + if (step === "end-selection") endSelection(); + else if (step === "up") { + const to = backUpTarget(path, currentVolumePath); + if (to !== null) setPath(to); + } + }); + useBackDismiss(renaming !== null, () => setRenaming(null)); + useBackDismiss(mkdirDraft !== null, () => setMkdirDraft(null)); + useBackDismiss(pathDraft !== null, () => setPathDraft(null)); + useBackDismiss(linkInto !== null, () => setLinkInto(null)); + // The selection's actions take the bottom navigation's place (index.css hides it). Only while + // Files is on show: a kept, hidden screen has its effects torn down. + useEffect(() => { + if (!phoneSelecting) return; + const root = document.documentElement; + root.setAttribute("data-selection-bar", ""); + return () => root.removeAttribute("data-selection-bar"); + }, [phoneSelecting]); + // A long press on a row starts selection mode with that row (a finger, in the phone layout); + // in selection mode it ticks or unticks the row, as a tap does. + const [longPress] = useState(() => + createLongPress((name) => + setSelected((s) => { + const next = new Set(s); + if (next.has(name)) next.delete(name); + else next.add(name); + return next; + }), + ), + ); + useEffect(() => () => longPress.dispose(), [longPress]); + // What the row actions (desktop buttons and the phone ⋮ menu) need. const [properties, setProperties] = useState<{ host: string; @@ -3163,6 +3239,196 @@ export default function FileSystemScreen() { }, ]; + /** The page's ⋯ menu: the folder's views, a link download, the drive's tools and search. */ + const pageMoreItems = (): RowMenuItem[] => [ + ...folderViewItems(), + { + icon: Link2, + label: tr("fs_link_download", undefined, "Download from a link"), + run: () => setLinkInto(path), + }, + // The size map of the drive you are on (Disk usage, a Files view). With the other + // whole-drive tools here, not among the drive chips, which only pick a drive. + { + icon: PieChart, + label: tr("fs_space_title", undefined, "What takes space?"), + run: () => openSpace(currentVolumePath ?? path), + }, + { + icon: Archive, + label: tr("fs_snapshots_open", undefined, "Snapshots"), + run: () => openView("snapshots"), + }, + { + icon: SearchIcon, + label: tr("fs_search_all_drives", undefined, "Search all drives"), + run: () => { + // An empty box only opens the view: what was typed there stays. + if (searchDraft.trim()) askSearch(searchDraft.trim(), undefined, false); + openView("search"); + }, + }, + ...(searchFolder + ? [ + { + icon: SearchIcon, + label: tr("fs_search_this_folder", undefined, "Search this folder"), + run: () => { + askSearch(searchDraft.trim(), undefined, true); + openView("search"); + }, + }, + ] + : []), + ]; + + /** Web UI: the device's own picker (the hidden inputs in the page header). */ + function pickOnDevice(mode: "file" | "folder") { + if (mode === "file") deviceFilesInput.current?.click(); + else deviceFolderInput.current?.click(); + } + /** Where "Add files" / "Add folder" read from on a phone: what the desktop's ▾ beside each + * button offers (BrowseButton), in the same order. The app reads this device; the web UI the + * server or the device the browser runs on. Files can come from a saved server too. */ + const app = isTauriEnv(); + const addSources: Record<"file" | "folder", RowMenuItem[]> = { + file: [ + ...(app + ? [] + : [{ icon: Server, label: tr("browse_on_server", undefined, "On the server…"), run: () => void addFilesHere() }]), + { + icon: HardDrive, + label: tr("browse_this_device", undefined, "This device…"), + run: app ? () => void addFilesHere() : () => pickOnDevice("file"), + }, + ...savedServers.map((c) => ({ + icon: Network, + label: c.name, + run: () => + void pickPath({ + mode: "file", + title: tr("fs_add_files_dialog_title", undefined, "Pick files to copy onto the PS5"), + source: { connectionId: c.id }, + }).then((p) => { + if (typeof p === "string") void addPicked([p], "file"); + }), + })), + ], + folder: [ + ...(app + ? [] + : [{ icon: Server, label: tr("browse_on_server", undefined, "On the server…"), run: () => void addFolderHere() }]), + { + icon: HardDrive, + label: tr("browse_this_device", undefined, "This device…"), + run: app ? () => void addFolderHere() : () => pickOnDevice("folder"), + }, + ], + }; + /** "Add files" / "Add folder" in the phone's ⋮: straight to the picker when there is only one + * place to read from, else a menu of them at the same button. */ + const startPhoneAdd = (mode: "file" | "folder") => { + const sources = addSources[mode]; + if (sources.length === 1) sources[0].run(); + else if (phoneMenu) + setPhoneMenu({ kind: mode === "file" ? "add-file" : "add-folder", anchor: phoneMenu.anchor }); + }; + const addBusy = loading || !host?.trim() || localBusy !== null; + + /** The phone's menus, by the button that opened them. */ + const phoneMenus: Record["kind"], RowMenuItem[]> = { + more: [ + { + icon: Upload, + label: tr("fs_add_files", "Add files"), + run: () => startPhoneAdd("file"), + disabled: addBusy, + }, + { + icon: FolderUp, + label: tr("fs_add_folder", undefined, "Add folder"), + run: () => startPhoneAdd("folder"), + disabled: addBusy, + }, + { + icon: FolderPlus, + label: tr("fs_new_folder", "New folder"), + run: () => setMkdirDraft(""), + disabled: loading || !host?.trim(), + }, + { + icon: RefreshCw, + label: tr("fs_refresh", "Refresh"), + run: () => void refresh(), + disabled: loading || !host?.trim(), + }, + // The way into selection mode without a long press (a keyboard, a D-pad). + { + icon: ListChecks, + label: tr("fs_select_items", undefined, "Select"), + run: () => setSelectMode(true), + disabled: !entries?.length, + }, + ...pageMoreItems(), + ], + drives: [ + ...(volumes ?? []).map((v) => { + const external = v.path.startsWith("/mnt/usb") || v.path.startsWith("/mnt/ext"); + return { + icon: external ? Usb : HardDrive, + label: `${v.path} · ${formatBytes(v.free_bytes)} ${tr("fs_free", "free")}`, + run: () => setPath(v.path), + current: currentVolumePath === v.path, + }; + }), + ...meshDrives.map((d) => ({ + icon: FolderSync, + label: d.name, + run: () => setPath(d.hub), + current: path === d.hub || path.startsWith(`${d.hub}/`), + })), + ...(volumes ?? []) + .filter((v) => canEjectUsb(v.path)) + .map((v) => ({ + icon: Eject, + label: `${tr("volumes_eject", undefined, "Eject")} ${v.path}`, + run: () => void ejectUsb(v.path), + disabled: ejectingPath !== null, + })), + ], + "add-file": addSources.file, + "add-folder": addSources.folder, + selection: [ + { + icon: Scissors, + label: tr("fs_cut", undefined, "Cut"), + run: () => stageClipboard("cut"), + disabled: bulkOp.op !== null, + }, + ...(otherConsoles > 0 + ? [ + { + icon: Send, + label: tr("fs_send_action", undefined, "Send to another console…"), + run: () => startSend(), + }, + ] + : []), + { + icon: KeyRound, + label: tr("fs_chmod_777", undefined, "Set permissions (777)"), + run: () => void runChmod777(), + disabled: bulkOp.op !== null || chmodBusy, + }, + { + icon: Archive, + label: tr("fs_snapshot_action", undefined, "Snapshot…"), + run: () => snapshotPaths(selectedEntries.map((x) => joinPath(path, x.name))), + disabled: !host?.trim(), + }, + ], + }; + return (
{properties && ( @@ -3400,47 +3666,18 @@ export default function FileSystemScreen() { y={moreMenu.bottom} anchor={moreMenu} onClose={() => setMoreMenu(null)} - items={[ - ...folderViewItems(), - { - icon: Link2, - label: tr("fs_link_download", undefined, "Download from a link"), - run: () => setLinkInto(path), - }, - // The size map of the drive you are on (Disk usage, a Files view). With the other - // whole-drive tools here, not among the drive chips, which only pick a drive. - { - icon: PieChart, - label: tr("fs_space_title", undefined, "What takes space?"), - run: () => openSpace(currentVolumePath ?? path), - }, - { - icon: Archive, - label: tr("fs_snapshots_open", undefined, "Snapshots"), - run: () => openView("snapshots"), - }, - { - icon: SearchIcon, - label: tr("fs_search_all_drives", undefined, "Search all drives"), - run: () => { - // An empty box only opens the view: what was typed there stays. - if (searchDraft.trim()) askSearch(searchDraft.trim(), undefined, false); - openView("search"); - }, - }, - ...(searchFolder - ? [ - { - icon: SearchIcon, - label: tr("fs_search_this_folder", undefined, "Search this folder"), - run: () => { - askSearch(searchDraft.trim(), undefined, true); - openView("search"); - }, - }, - ] - : []), - ]} + items={pageMoreItems()} + /> + )} + {phoneMenu && ( + setPhoneMenu(null)} + items={phoneMenus[phoneMenu.kind]} /> )} {confirmDialogNode} @@ -3472,6 +3709,8 @@ export default function FileSystemScreen() { icon={FolderTree} title={tr("file_system", undefined, "Files")} loading={loading} + // A phone has the compact header pinned over the list instead (#936). + className="phone:hidden" right={ // On a phone, Add folder / New folder / Refresh / ⋯ show their icon alone // so they fit one line under the title, and the search box takes the @@ -3723,7 +3962,8 @@ export default function FileSystemScreen() { chip jumps to that drive's root; external/USB drives get a USB icon + accent border so they stand out. The active drive is highlighted. */} {volumes && volumes.length > 0 && ( -
+ // A phone picks the drive from the header's drive button instead. +
{tr("fs_drives_label", undefined, "Drives")} @@ -3826,106 +4066,146 @@ export default function FileSystemScreen() { `overflow-y` compute to `auto` too (CSS spec), which would clip the dropdown's absolutely-positioned panel to the thin breadcrumb bar — the cramped/scrollbar'd overlay users saw. Keeping the dropdown - out of the scrolling row lets its panel open freely. */} -
-
- - {pathDraft !== null ? ( - setPathDraft(ev.target.value)} - onKeyDown={(ev) => { - if (ev.key === "Enter") { - const next = normalizeTypedPath(pathDraft); - if (next) { - setPath(next); - setPathDraft(null); - } - } - if (ev.key === "Escape") setPathDraft(null); - }} - onBlur={() => setPathDraft(null)} - spellCheck={false} - aria-label={tr("fs_go_to_path", undefined, "Go to path")} - className="input input-sm min-w-0 flex-1 font-mono text-xs" - /> - ) : ( - <> - {crumbs(path).map((c, i, arr) => ( - - + {pathDraft !== null ? ( + setPathDraft(ev.target.value)} + onKeyDown={(ev) => { + if (ev.key === "Enter") { + const next = normalizeTypedPath(pathDraft); + if (next) { + setPath(next); + setPathDraft(null); } + } + if (ev.key === "Escape") setPathDraft(null); + }} + onBlur={() => setPathDraft(null)} + spellCheck={false} + aria-label={tr("fs_go_to_path", undefined, "Go to path")} + className="input input-sm min-w-0 flex-1 font-mono text-xs" + /> + ) : ( + <> + {crumbs(path).map((c, i, arr) => ( + - {i === 0 ? ( - - ) : ( - c.label + + {i < arr.length - 1 && ( + )} - - {i < arr.length - 1 && ( - - )} - - ))} - - - )} + + ))} + + + )} +
+ setPath(p)} + currentPath={path} + onOpen={consolePins.refresh} + console={ + consolePins.pins + ? { + pins: consolePins.pins, + pinned: consolePins.isPinned(path), + onTogglePin: () => + void consolePins.toggle(path).catch((e: unknown) => + toast({ + tone: "warn", + message: tr( + "fs_console_pin_failed", + { error: humanizeCaught(e) }, + `Couldn't change the console's pinned folders: ${e instanceof Error ? e.message : String(e)}`, + ), + }), + ), + } + : undefined + } + />
- setPath(p)} - currentPath={path} - onOpen={consolePins.refresh} - console={ - consolePins.pins - ? { - pins: consolePins.pins, - pinned: consolePins.isPinned(path), - onTogglePin: () => - void consolePins.toggle(path).catch((e: unknown) => - toast({ - tone: "warn", - message: tr( - "fs_console_pin_failed", - { error: humanizeCaught(e) }, - `Couldn't change the console's pinned folders: ${e instanceof Error ? e.message : String(e)}`, - ), - }), - ), - } - : undefined - } - />
{/* Clipboard banner: non-empty clipboard shows what's staged and @@ -3979,6 +4259,8 @@ export default function FileSystemScreen() { )} clearLabel={tr("fs_clear_selection", undefined, "Clear selection")} onClear={() => setSelected(new Set())} + // A phone has the count in the header and the actions at the bottom (#936). + className="phone:hidden" >
+ {phoneSelecting && ( + <> + {/* Room under the last row: the bar floats over the bottom of the list. */} +
+ stageClipboard("copy"), + disabled: bulkOp.op !== null || selected.size === 0, + }, + { + id: "move", + icon: FolderInput, + label: tr("fs_move_to", undefined, "Move to…"), + run: () => startMove(), + disabled: bulkOp.op !== null || !volumes?.length || selected.size === 0, + }, + { + id: "rename", + icon: Pencil, + label: tr("fs_rename", "Rename"), + // One item: its name in place, as the row's own Rename. Several: the pattern. + run: () => { + const names = Array.from(selected); + if (names.length === 1) { + endSelection(); + startRename(names[0]); + } else void runBulkRename(names); + }, + disabled: bulkOp.op !== null || selected.size === 0, + }, + { + id: "delete", + icon: Trash2, + label: tr("library_delete", undefined, "Delete"), + run: () => void runBulkDelete(), + disabled: bulkOp.op !== null || selected.size === 0, + tone: "bad", + }, + { + id: "more", + icon: MoreHorizontal, + label: tr("fs_more", undefined, "More"), + run: (box) => togglePhoneMenu("selection", box), + disabled: selected.size === 0, + menu: phoneMenu?.kind === "selection", + }, + ]} + /> + + )} {preview && ( [0]> = {}) => + filesBackStep({ view: false, selecting: false, path, driveRoot: "/mnt/usb0", ...extra }); + +describe("system Back on the Files listing (#932)", () => { + it("leaves selection mode first, wherever the folder is", () => { + expect(at("/mnt/usb0/homebrew", { selecting: true })).toBe("end-selection"); + expect(at("/mnt/usb0", { selecting: true })).toBe("end-selection"); + }); + + it("then goes up one folder", () => { + expect(at("/mnt/usb0/homebrew/games")).toBe("up"); + expect(backUpTarget("/mnt/usb0/homebrew/games", "/mnt/usb0")).toBe("/mnt/usb0/homebrew"); + }); + + it("leaves Files from the drive's root", () => { + expect(at("/mnt/usb0")).toBeNull(); + expect(at("/mnt/usb0/")).toBeNull(); + }); + + it("goes up to / outside every known drive, and leaves from there", () => { + expect(at("/system_ex/app", { driveRoot: null })).toBe("up"); + expect(backUpTarget("/system_ex", null)).toBe("/"); + expect(at("/", { driveRoot: null })).toBeNull(); + }); + + it("takes no step while a view covers the listing (it is its own history entry)", () => { + expect(at("/mnt/usb0/homebrew", { view: true, selecting: true })).toBeNull(); + }); +}); + +describe("the compact header's title (#936)", () => { + it("is the open folder's own name", () => { + expect(folderTitle("/mnt/usb0/homebrew")).toBe("homebrew"); + expect(folderTitle("/data/")).toBe("data"); + }); + + it("is left to the screen's name at /", () => { + expect(folderTitle("/")).toBeNull(); + }); +}); diff --git a/client/src/screens/FileSystem/phoneFiles.ts b/client/src/screens/FileSystem/phoneFiles.ts new file mode 100644 index 000000000..690a29e47 --- /dev/null +++ b/client/src/screens/FileSystem/phoneFiles.ts @@ -0,0 +1,48 @@ +// Files on a phone (#932, #936): what system Back does on the listing, and what the compact header +// shows. Kept apart from the screen so it can be tested on its own. + +/** What one press of system Back does on the Files listing once no menu, sheet or dialog is open + * (those close first, lib/systemBack). Null: nothing here, the press leaves Files. */ +export type FilesBackStep = "end-selection" | "up" | null; + +/** + * Leave selection mode first, then go up one folder, and leave Files from the top. + * + * The top is the drive's root (/data, /mnt/usb0): a phone's file manager stops at its storage, and + * the folders above a drive (/mnt) are not where anyone was. Outside every known drive it is "/". + * A view over the listing (search, space, snapshots) is its own history entry: it takes Back by + * itself, so there is no step while one is open. + */ +export function filesBackStep(s: { + /** A view covers the listing. */ + view: boolean; + /** Selection mode: something is selected, or "Select" was picked. */ + selecting: boolean; + path: string; + /** The drive the path is on, or null outside every known drive. */ + driveRoot: string | null; +}): FilesBackStep { + if (s.view) return null; + if (s.selecting) return "end-selection"; + return backUpTarget(s.path, s.driveRoot) === null ? null : "up"; +} + +/** Where Back goes up to from `path`, or null at the top (see filesBackStep). */ +export function backUpTarget(path: string, driveRoot: string | null): string | null { + const here = trimSlash(path); + if (here === "/" || here === "") return null; + if (driveRoot !== null && here === trimSlash(driveRoot)) return null; + const cut = here.lastIndexOf("/"); + return cut <= 0 ? "/" : here.slice(0, cut); +} + +/** The open folder's own name, for the compact header; null at "/" (the header says Files). */ +export function folderTitle(path: string): string | null { + const here = trimSlash(path); + if (here === "/" || here === "") return null; + return here.slice(here.lastIndexOf("/") + 1); +} + +function trimSlash(p: string): string { + return p.length > 1 && p.endsWith("/") ? p.replace(/\/+$/, "") || "/" : p; +} diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index c3f42bae2..f662f2969 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -3844,7 +3844,9 @@ "fs_search_placeholder": "56f50853 MyYWcPyQo7_phiMvONrJGhMGrB8dqixtikIARZ5IopzQhhRSCA4Tza6PmfXQ", "fs_search_this_folder": "86326f17 u9yEixPtbW0FbBIsoK7kNYJGsltwswkM2mN4tWYPDWsNDABf4m08QJX5u0fK", "fs_select_all": "1fc9a387 z3lkaTMfC9pFccpW2_gii5XYoyxJZJdXq9eX5MzbcVV_bi757wtH8hOlBH_5", + "fs_select_items": "2a78025d 9MjU-FC_HTsuSO8vsgDwE5PwPqQW2L5yHjRpLk_aldOKoTyzbKoEXHwRMpQN", "fs_selected_count": "529aacfd -mEKJl8o8H2mVjBzmu5HXVkpBQJQO01DyUhJHt4hsPYz8Nx8tETvNdFb1_r1", + "fs_selection_actions": "5c111752 bOvPJ8jidhF_10bKR_vZTC2zFUFIp10t5-vn_TO0gslWmF_e2t8ZS-mPY4u0", "fs_send_action": "f203646e Z_60tczfFXoPtT-WdIbQyMfDRgf_Cj2pp8h3QAzYV2rPQgTYvkvjFmMysPP-", "fs_send_console": "f4b06ef6 l_4rO2n5iVZrHE5GmCDRmWfEvyiVZrgk7jGCMAlI3sVq_Y0Io5cFLwVwYySw", "fs_send_dial_bad": "aa34d577 G_covqSCZmysBjJgquP1izcdAoHk9QdtobxYYjxWV-8JizgN1r_Cf9jbEO6n", From 8385c914c040da11fd37b3300a7add075554f8cb Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:20:43 -0800 Subject: [PATCH 21/27] Files on phones: long press holds up on Android, sideways header in one row, e2e A held finger on a row no longer turns into a drag (rows are not draggable in the phone layout), a file's name lets taps and long presses through to its row, and the click of the finger lifting is swallowed wherever it lands, so the bar of actions that comes up under it is not pressed. Two quick taps while selecting tick and untick a row instead of opening it. Held sideways, the path sits beside the folder row, so the pinned header takes one row of the short screen. Adds Playwright specs for phone portrait and both sideways sizes (header, long press, selection bar, Back, menus, drives) and the phone's browser, and checks the desktop layout keeps its header, drive chips and checkboxes. The phone row menu spec now selects through the menu's Select, since checkboxes show only in selection mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/e2e/files-phone-header.spec.ts | 307 ++++++++++++++++++++ client/e2e/files-phone-row-menu.spec.ts | 8 +- client/src/lib/backCoverage.test.ts | 25 +- client/src/lib/longPress.test.ts | 15 +- client/src/lib/longPress.ts | 40 ++- client/src/lib/phoneLayout.test.ts | 4 +- client/src/screens/FileSystem/PhoneBars.tsx | 12 +- client/src/screens/FileSystem/index.tsx | 49 +++- 8 files changed, 409 insertions(+), 51 deletions(-) create mode 100644 client/e2e/files-phone-header.spec.ts diff --git a/client/e2e/files-phone-header.spec.ts b/client/e2e/files-phone-header.spec.ts new file mode 100644 index 000000000..cf6182ee0 --- /dev/null +++ b/client/e2e/files-phone-header.spec.ts @@ -0,0 +1,307 @@ +import { expect, test, type Locator, type Page, type Route } from "@playwright/test"; + +// #936: on a phone, Files has a compact header pinned over the list (the folder, search, the drive +// and ⋮ on top, the path under it); a long press starts selection mode, whose actions take the +// bottom navigation's place. #932: system Back closes an open menu and stays in the folder, leaves +// selection mode, then goes up one folder. Tablets and computers keep their layout. + +const HOST = "192.168.0.5"; +const START = "/mnt/usb0/homebrew"; +const FILES = Array.from({ length: 30 }, (_, i) => `file-${String(i + 1).padStart(2, "0")}.pkg`); +const LISTINGS: Record = { + "/mnt/usb0/homebrew": [ + { name: "games", kind: "dir" }, + { name: "apps", kind: "dir" }, + ...FILES.map((name) => ({ name, kind: "file" as const })), + ], + "/mnt/usb0/homebrew/games": [{ name: "inner.pkg", kind: "file" }], + "/mnt/usb0": [{ name: "homebrew", kind: "dir" }], + "/data": [{ name: "data-file.bin", kind: "file" }], +}; +const VOLUMES = [ + { path: "/data", fs_type: "nullfs", total_bytes: 900e9, free_bytes: 400e9, writable: true, is_placeholder: false }, + { path: "/mnt/usb0", fs_type: "exfatfs", total_bytes: 1e12, free_bytes: 5e11, writable: true, is_placeholder: false }, +]; + +/** Files with a fake engine. `app`: the Android app (a fake Tauri, whose shell asks + * window.__ps5uBack on Back); else the web UI in a phone's browser (Back moves the history). */ +async function openFiles(page: Page, { app = true }: { app?: boolean } = {}) { + if (app) { + await page.addInitScript( + ({ listings, volumes }) => { + const w = window as unknown as Record; + let id = 0; + w.__TAURI_INTERNALS__ = { + invoke: async (cmd: string, args?: { path?: string }) => { + if (cmd === "ps5_list_dir") + return { + entries: (listings[args?.path ?? ""] ?? []).map((e) => ({ ...e, size: 1000, mtime: 1791360199 })), + truncated: false, + }; + if (cmd === "ps5_volumes") return { volumes }; + if (cmd === "payload_check") + return { + ok: true, + reachable: true, + engine: true, + status: { version: "7.0.29", instance_id: 1, ucred_elevated: true }, + }; + return null; + }, + transformCallback: () => ++id, + unregisterCallback: () => {}, + convertFileSrc: (p: string) => p, + metadata: { currentWindow: { label: "main" }, currentWebview: { windowLabel: "main", label: "main" } }, + plugins: {}, + }; + w.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; + }, + { listings: LISTINGS, volumes: VOLUMES }, + ); + } + await page.addInitScript( + ({ host, start }) => { + window.localStorage.setItem("ps5upload.host", host); + window.localStorage.setItem("ps5upload.fs.lastPath", JSON.stringify({ [host]: start })); + }, + { host: HOST, start: START }, + ); + const json = (route: Route, body: unknown) => + route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(body) }); + await page.route( + (u) => u.pathname.startsWith("/api/"), + async (route) => { + const url = new URL(route.request().url()); + const p = url.pathname; + if (p === "/api/version") return json(route, { caps: {}, version: "7.0.29" }); + if (p === "/api/ps5/status") + return json(route, { + command_count: 1, + instance_id: 1, + max_transfer_streams: 8, + prior_instance: "clean", + ps5_kernel: "r229358/releases/13.60 Jul 17 2026 02:16:29", + started_at_unix: 1791360198, + ucred_elevated: true, + version: "7.0.29", + }); + if (p === "/api/ps5/volumes") return json(route, { volumes: VOLUMES }); + if (p === "/api/ps5/list-dir") { + const path = url.searchParams.get("path") ?? "/data"; + const entries = (LISTINGS[path] ?? []).map((e) => ({ ...e, size: 1000, mtime: 1791360199 })); + return json(route, { path, entries, truncated: false, total_scanned: entries.length, returned: entries.length }); + } + if (p === "/api/jobs") return json(route, []); + return json(route, {}); + }, + ); + await page.goto("/files", { waitUntil: "domcontentloaded" }); + await expect(row(page, "file-01.pkg")).toBeVisible({ timeout: 30_000 }); +} + +const main = (page: Page) => page.getByRole("main"); +const title = (page: Page) => main(page).getByTestId("fs-phone-title"); +const count = (page: Page) => main(page).getByTestId("fs-phone-count"); +const row = (page: Page, name: string) => main(page).locator(`li[data-fs-name="${name}"]`); +const actionsBar = (page: Page) => main(page).getByRole("toolbar", { name: "Actions for the selected items" }); +const menu = (page: Page) => page.getByTestId("fs-row-menu"); +const back = (page: Page) => page.evaluate(() => window.__ps5uBack?.() ?? null); + +/** A finger held on `target`, as the phone sends it (touch events: Chrome makes the pointer + * events, and its own long press, from them). */ +async function longPress(page: Page, target: Locator) { + await target.scrollIntoViewIfNeeded(); + const box = await target.boundingBox(); + if (!box) throw new Error("no box"); + const x = box.x + Math.min(40, box.width / 2); + const y = box.y + box.height / 2; + const cdp = await page.context().newCDPSession(page); + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + await page.waitForTimeout(800); + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + await cdp.detach(); +} + +async function shot(page: Page, name: string) { + const dir = process.env.FILES_PHONE_SHOTS; + if (dir) await page.screenshot({ path: `${dir}/${name}.png` }); +} + +const PHONES = [ + { name: "portrait", viewport: { width: 360, height: 800 } }, + { name: "sideways 915x412", viewport: { width: 915, height: 412 } }, + { name: "sideways 844x390", viewport: { width: 844, height: 390 } }, +]; + +for (const phone of PHONES) { + test.describe(`phone ${phone.name}`, () => { + test.use({ viewport: phone.viewport, hasTouch: true, isMobile: true }); + + test("the compact header stays pinned over the list, with the path (#936)", async ({ page }) => { + await openFiles(page); + await expect(title(page)).toHaveText("homebrew"); + // The page header and the drive chips give way to the compact header. + await expect(main(page).getByRole("button", { name: "Add files", exact: true })).toBeHidden(); + await expect(main(page).getByRole("button", { name: /^\/mnt\/usb0/ })).toBeHidden(); + const header = main(page).getByTestId("fs-header"); + await expect(header.getByRole("button", { name: "Search" })).toBeVisible(); + await expect(header.getByRole("button", { name: "Drives" })).toBeVisible(); + await expect(header.getByRole("button", { name: "More" })).toBeVisible(); + await expect(header.getByRole("button", { name: "usb0" })).toBeVisible(); + // No boxes until selecting. + await expect(row(page, "file-01.pkg").getByRole("checkbox")).toBeHidden(); + await shot(page, `header-${phone.viewport.width}x${phone.viewport.height}`); + + const scroller = page.locator("[data-scroll-root]"); + await scroller.evaluate((el) => (el.scrollTop = 600)); + await expect.poll(() => scroller.evaluate((el) => el.scrollTop)).toBeGreaterThan(300); + const top = (await scroller.boundingBox())!.y; + const box = (await header.boundingBox())!; + expect(Math.abs(box.y - top)).toBeLessThan(2); + await expect(header.getByRole("button", { name: "usb0" })).toBeInViewport(); + // Room for the list: two short rows; held sideways, where height is short, one (the path + // beside the folder instead of under it). + const sideways = phone.viewport.width > phone.viewport.height; + expect(box.height).toBeLessThan(sideways ? 70 : 120); + const path = (await header.getByRole("button", { name: "usb0" }).boundingBox())!; + const folder = (await title(page).boundingBox())!; + if (sideways) expect(path.x).toBeGreaterThan(folder.x + folder.width); + else expect(path.y).toBeGreaterThan(folder.y + folder.height); + await shot(page, `header-scrolled-${phone.viewport.width}x${phone.viewport.height}`); + }); + + test("a long press selects; the bar of actions takes the navigation's place; Back leaves selection, then goes up (#936, #932)", async ({ + page, + }) => { + await openFiles(page); + // A folder: held, it is selected, not opened. + await longPress(page, row(page, "games")); + await expect(count(page)).toHaveText("1 selected"); + await expect(title(page)).toBeHidden(); + await expect(row(page, "games").getByRole("checkbox")).toBeChecked(); + await expect(row(page, "file-01.pkg").getByRole("checkbox")).toBeVisible(); + await expect(page.locator("[data-bottom-nav]")).toBeHidden(); + const bar = actionsBar(page); + await expect(bar).toBeInViewport(); + // The finger lifting is not a tap on what selecting put under it (held low on a short + // screen, the bar comes up under the finger): nothing was copied. + await expect(main(page).getByRole("button", { name: "Paste here" })).toHaveCount(0); + for (const name of ["Copy", "Move to…", "Rename", "Delete", "More"]) + await expect(bar.getByRole("button", { name, exact: true })).toBeVisible(); + + // Selecting, a tap ticks a row instead of opening it; a file's name too (a disabled button, + // which would swallow the tap). + await row(page, "apps").getByRole("button", { name: "apps", exact: true }).tap(); + await expect(count(page)).toHaveText("2 selected"); + await expect(title(page)).toBeHidden(); + await row(page, "file-02.pkg").getByText("file-02.pkg").tap({ force: true }); + await expect(count(page)).toHaveText("3 selected"); + await shot(page, `selecting-${phone.viewport.width}x${phone.viewport.height}`); + // A long press on a file's name ticks it as well. + await row(page, "file-02.pkg").tap(); + await expect(count(page)).toHaveText("2 selected"); + await longPress(page, row(page, "file-02.pkg").getByText("file-02.pkg")); + await expect(count(page)).toHaveText("3 selected"); + + // More: the selection's other actions, in a menu that Back closes first. + await bar.getByRole("button", { name: "More", exact: true }).tap(); + await expect(menu(page).getByRole("menuitem", { name: "Cut" })).toBeVisible(); + await expect(menu(page).getByRole("menuitem", { name: "Set permissions (777)" })).toBeVisible(); + expect(await back(page)).toBe(true); + await expect(menu(page)).toHaveCount(0); + await expect(count(page)).toHaveText("3 selected"); + + await main(page).getByRole("button", { name: "Select all" }).tap(); + await expect(count(page)).toHaveText(`${LISTINGS[START].length} selected`); + + // Back: selection mode ends, the folder stays. + expect(await back(page)).toBe(true); + await expect(title(page)).toHaveText("homebrew"); + await expect(row(page, "file-01.pkg").getByRole("checkbox")).toBeHidden(); + await expect(actionsBar(page)).toHaveCount(0); + if (phone.viewport.width < 768) await expect(page.locator("[data-bottom-nav]")).toBeVisible(); + + // Back: up one folder; at the drive's root the press is the app's (it leaves Files). + expect(await back(page)).toBe(true); + await expect(title(page)).toHaveText("usb0"); + expect(await back(page)).toBe(false); + }); + + test("Back closes a row's menu and stays in the folder (#932)", async ({ page }) => { + await openFiles(page); + await main(page).getByRole("button", { name: "Actions for file-01.pkg" }).tap(); + await expect(menu(page).getByRole("menuitem", { name: "Rename", exact: true })).toBeVisible(); + expect(await back(page)).toBe(true); + await expect(menu(page)).toHaveCount(0); + await expect(title(page)).toHaveText("homebrew"); + await expect(row(page, "file-01.pkg")).toBeVisible(); + }); + + test("⋮ holds the page's actions and Select; the drive button switches drives", async ({ page }) => { + await openFiles(page); + const header = main(page).getByTestId("fs-header"); + await header.getByRole("button", { name: "More" }).tap(); + for (const name of ["Add files", "Add folder", "New folder", "Refresh", "Select", "Snapshots"]) + await expect(menu(page).getByRole("menuitem", { name, exact: true })).toBeVisible(); + await shot(page, `more-menu-${phone.viewport.width}x${phone.viewport.height}`); + // Select: selection mode with nothing ticked yet, for a keyboard or a D-pad. + await menu(page).getByRole("menuitem", { name: "Select", exact: true }).click(); + await expect(count(page)).toHaveText("0 selected"); + const box = row(page, "file-03.pkg").getByRole("checkbox"); + await box.focus(); + await page.keyboard.press("Space"); + await expect(count(page)).toHaveText("1 selected"); + // Rename with one item: its name in place. + await actionsBar(page).getByRole("button", { name: "Rename", exact: true }).tap(); + await expect(main(page).locator('input[value="file-03.pkg"]')).toBeVisible(); + expect(await back(page)).toBe(true); + await expect(main(page).locator('input[value="file-03.pkg"]')).toHaveCount(0); + + await header.getByRole("button", { name: "Drives" }).tap(); + const current = menu(page).getByRole("menuitem", { name: /^\/mnt\/usb0 ·/ }); + await expect(current).toHaveAttribute("aria-current", "true"); + await expect(menu(page).getByRole("menuitem", { name: "Eject /mnt/usb0" })).toBeVisible(); + await menu(page).getByRole("menuitem", { name: /^\/data ·/ }).click(); + await expect(title(page)).toHaveText("data"); + }); + }); +} + +test.describe("phone browser (the web UI)", () => { + test.use({ + viewport: { width: 360, height: 800 }, + hasTouch: true, + isMobile: true, + userAgent: + "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36", + }); + + test("Back closes the menu, then goes up a folder, before it leaves Files (#932)", async ({ page }) => { + // Somewhere to go back to first, as a person arrives at Files. + await openFiles(page, { app: false }); + await main(page).getByRole("button", { name: "Actions for file-01.pkg" }).tap(); + await expect(menu(page)).toBeVisible(); + await page.goBack(); + await expect(menu(page)).toHaveCount(0); + await expect(title(page)).toHaveText("homebrew"); + await page.goBack(); + await expect(title(page)).toHaveText("usb0"); + expect(new URL(page.url()).pathname).toBe("/files"); + }); +}); + +test.describe("desktop width", () => { + test.use({ viewport: { width: 1280, height: 800 } }); + + test("keeps the page header, the drive chips and the boxes; no phone bars", async ({ page }) => { + await openFiles(page); + await expect(main(page).getByRole("button", { name: "Add files", exact: true })).toBeVisible(); + await expect(main(page).getByRole("button", { name: /^\/mnt\/usb0/ })).toBeVisible(); + await expect(main(page).getByTestId("fs-phone-row")).toBeHidden(); + await expect(row(page, "file-01.pkg").getByRole("checkbox")).toBeVisible(); + await row(page, "file-01.pkg").getByRole("checkbox").check(); + await expect(main(page).getByTestId("fs-selection-bar")).toBeVisible(); + await expect(actionsBar(page)).toHaveCount(0); + await shot(page, "desktop-1280x800"); + }); +}); diff --git a/client/e2e/files-phone-row-menu.spec.ts b/client/e2e/files-phone-row-menu.spec.ts index e5e65d395..9cc679f76 100644 --- a/client/e2e/files-phone-row-menu.spec.ts +++ b/client/e2e/files-phone-row-menu.spec.ts @@ -83,9 +83,13 @@ test("phone width: row names show, ⋮ opens the row's actions, the selection ba await expect(main.locator(`input[value="${LONG}"]`)).toBeVisible(); await page.keyboard.press("Escape"); - // Selecting a row: "1 selected" on one line. + // Selecting a row (#936: the boxes show in selection mode, here by ⋮ → Select, the way + // without a long press): "1 selected" on one line, in the header. + await expect(main.locator("li input[type=checkbox]").first()).toBeHidden(); + await main.getByTestId("fs-phone-more").click(); + await page.getByTestId("fs-row-menu").getByRole("menuitem", { name: "Select", exact: true }).click(); await main.locator("li input[type=checkbox]").first().check(); - const count = main.getByTestId("fs-selection-bar").getByText("1 selected"); + const count = main.getByTestId("fs-phone-count").getByText("1 selected"); await expect(count).toBeVisible(); const countBox = await count.boundingBox(); expect(countBox?.height ?? 99).toBeLessThan(30); diff --git a/client/src/lib/backCoverage.test.ts b/client/src/lib/backCoverage.test.ts index 0a5120f59..58424e2c0 100644 --- a/client/src/lib/backCoverage.test.ts +++ b/client/src/lib/backCoverage.test.ts @@ -1,13 +1,12 @@ +// @ts-expect-error -- the app tsconfig has no node types; Vitest runs this under Node. import { readdirSync, readFileSync, statSync } from "node:fs"; -import { join, relative } from "node:path"; -import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; // System Back on a phone closes what is open on top (lib/systemBack), but only what registered // for it. The Files row menu did not, and Back left the Files tab with the menu still up (#932). // Every menu has to take part: through useBackDismiss, or a modal surface's focus trap. -const SRC = fileURLToPath(new URL("..", import.meta.url)); +const SRC = new URL("../", import.meta.url); /** Menus that handle Back another way. */ const OWN_BACK: Record = { @@ -15,19 +14,23 @@ const OWN_BACK: Record = { "screens/Play/StreamPanel.tsx": "popstate", }; -function sources(dir: string): string[] { - return readdirSync(dir).flatMap((name) => { - const p = join(dir, name); - if (statSync(p).isDirectory()) return name === "console" ? [] : sources(p); - return /\.tsx$/.test(name) && !/\.test\.tsx$/.test(name) ? [p] : []; +/** The app's .tsx files (not tests, not the console's own page), relative to src/. */ +function sources(rel = ""): string[] { + return (readdirSync(new URL(rel, SRC)) as string[]).flatMap((name) => { + const path = rel + name; + if (statSync(new URL(path, SRC)).isDirectory()) return name === "console" ? [] : sources(`${path}/`); + return /\.tsx$/.test(name) && !/\.test\.tsx$/.test(name) ? [path] : []; }); } describe("system Back reaches every menu", () => { it("each file that draws a menu registers it for Back", () => { - const missing = sources(SRC) - .filter((p) => readFileSync(p, "utf8").includes('role="menu"')) - .map((p) => ({ rel: relative(SRC, p).split("\\").join("/"), text: readFileSync(p, "utf8") })) + const menus = sources() + .map((rel) => ({ rel, text: readFileSync(new URL(rel, SRC), "utf8") as string })) + .filter(({ text }) => text.includes('role="menu"')); + // The scan sees them at all (the Files row menu among them). + expect(menus.map((m) => m.rel)).toContain("screens/FileSystem/RowActions.tsx"); + const missing = menus .filter(({ rel, text }) => { const own = OWN_BACK[rel]; if (own) return !text.includes(own); diff --git a/client/src/lib/longPress.test.ts b/client/src/lib/longPress.test.ts index 66bd7638c..3eb3f7db5 100644 --- a/client/src/lib/longPress.test.ts +++ b/client/src/lib/longPress.test.ts @@ -6,11 +6,12 @@ function setup() { const fired: string[] = []; let pending: { fn: () => void; at: number } | null = null; let now = 0; - const timers = { + const clock = { set: (fn: () => void, ms: number) => (pending = { fn, at: now + ms }), clear: () => void (pending = null), + now: () => now, }; - const lp = createLongPress((t) => fired.push(t), { timers }); + const lp = createLongPress((t) => fired.push(t), { clock }); const wait = (ms: number) => { now += ms; if (pending && pending.at <= now) { @@ -44,6 +45,16 @@ describe("long press", () => { expect(lp.takeClick()).toBe(false); }); + it("lets a later tap through when the lift made no click (Android after its own long press)", () => { + const { lp, wait } = setup(); + lp.down("a", 0, 0, "touch"); + wait(LONG_PRESS_MS); + lp.end(); + wait(2000); + // A tap on the bar of actions: no pointer went down on a row first. + expect(lp.takeClick()).toBe(false); + }); + it("is a tap when the finger lifts early", () => { const { lp, fired, wait } = setup(); lp.down("a", 0, 0, "touch"); diff --git a/client/src/lib/longPress.ts b/client/src/lib/longPress.ts index 810a5e698..4ab8303d7 100644 --- a/client/src/lib/longPress.ts +++ b/client/src/lib/longPress.ts @@ -2,13 +2,16 @@ // on a phone (#936), as a phone's own file managers do. // // The browser can report the same press as a `contextmenu` event too (Android does, about when the -// hold is long enough), so either one ends the press, once. The tap that lifts the finger is not -// a tap: the click after a long press is swallowed, or it would also open the folder under it. +// hold is long enough), so either one ends the press, once. The finger lifting is not a tap: the +// click right after a long press is swallowed wherever it lands, or it would open the folder under +// it, or press a button of the bar that selecting just put under the finger. /** How long a finger holds still before it counts (Android's own long press is 400-500 ms). */ export const LONG_PRESS_MS = 500; /** How far a finger may drift and still be holding still. More is a scroll. */ export const LONG_PRESS_SLOP_PX = 10; +/** How long after the finger lifts its click may still arrive. */ +const CLICK_AFTER_MS = 600; export interface LongPress { /** A pointer went down on `target`. Only a finger (touch) starts a press. */ @@ -19,53 +22,57 @@ export interface LongPress { /** The browser's own long press (`contextmenu`) for the press under way. True when it was * this press's, and its menu should not open. */ contextMenu(): boolean; - /** Call for each click: true for the one right after a long press, to swallow. */ + /** Call for each click: true for the one the finger lifting after a long press makes. */ takeClick(): boolean; /** Stop any timer (unmount). */ dispose(): void; } -type Timers = { +type Clock = { set: (fn: () => void, ms: number) => unknown; clear: (id: unknown) => void; + now: () => number; }; -const realTimers: Timers = { +const realClock: Clock = { set: (fn, ms) => setTimeout(fn, ms), clear: (id) => clearTimeout(id as ReturnType), + now: () => Date.now(), }; export function createLongPress( onLongPress: (target: T) => void, - options: { ms?: number; slop?: number; timers?: Timers } = {}, + options: { ms?: number; slop?: number; clock?: Clock } = {}, ): LongPress { const ms = options.ms ?? LONG_PRESS_MS; const slop = options.slop ?? LONG_PRESS_SLOP_PX; - const timers = options.timers ?? realTimers; + const clock = options.clock ?? realClock; let press: { target: T; x: number; y: number; fired: boolean } | null = null; let timer: unknown = null; - let swallowClick = false; + /** After a long press: until when its click may come (while the finger is still down: always). */ + let swallowUntil: number | null = null; const stopTimer = () => { - if (timer !== null) timers.clear(timer); + if (timer !== null) clock.clear(timer); timer = null; }; const fire = () => { stopTimer(); if (!press || press.fired) return; press.fired = true; - swallowClick = true; + swallowUntil = Infinity; onLongPress(press.target); }; + const swallowing = () => swallowUntil !== null && clock.now() <= swallowUntil; return { down(target, x, y, pointerType) { stopTimer(); - swallowClick = false; + swallowUntil = null; press = null; if (pointerType !== "touch") return; press = { target, x, y, fired: false }; - timer = timers.set(fire, ms); + timer = clock.set(fire, ms); }, move(x, y) { if (!press || press.fired) return; @@ -76,18 +83,19 @@ export function createLongPress( }, end() { stopTimer(); + if (press?.fired) swallowUntil = clock.now() + CLICK_AFTER_MS; press = null; }, contextMenu() { - // Already a long press (the timer won): its menu stays shut even after the finger lifted. - if (swallowClick) return true; + // Already a long press (the timer won): its menu stays shut, even just after the lift. + if (swallowing()) return true; if (!press) return false; fire(); return true; }, takeClick() { - const swallow = swallowClick; - swallowClick = false; + const swallow = swallowing(); + swallowUntil = null; return swallow; }, dispose() { diff --git a/client/src/lib/phoneLayout.test.ts b/client/src/lib/phoneLayout.test.ts index d065753b0..704627207 100644 --- a/client/src/lib/phoneLayout.test.ts +++ b/client/src/lib/phoneLayout.test.ts @@ -1,10 +1,10 @@ +// @ts-expect-error -- the app tsconfig has no node types; Vitest runs this under Node. import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { PHONE_LAYOUT_QUERY } from "./phoneLayout"; -const css = readFileSync(fileURLToPath(new URL("../index.css", import.meta.url)), "utf8"); +const css: string = readFileSync(new URL("../index.css", import.meta.url), "utf8"); describe("the phone layout's query", () => { it("is the `phone:` variant's, so the script and the styles agree on what a phone is", () => { diff --git a/client/src/screens/FileSystem/PhoneBars.tsx b/client/src/screens/FileSystem/PhoneBars.tsx index 3f3ee2dc3..64c257524 100644 --- a/client/src/screens/FileSystem/PhoneBars.tsx +++ b/client/src/screens/FileSystem/PhoneBars.tsx @@ -83,7 +83,12 @@ export function PhoneFolderRow({ disabled: boolean; }) { return ( -
+

{title} @@ -127,7 +132,10 @@ export function PhoneSelectionRow({ onSelectAll: () => void; }) { return ( -
+
() => longPress.dispose(), [longPress]); + useEffect(() => { + const end = () => longPress.end(); + // The finger lifting after a long press is not a tap on whatever is under it now (the row, + // or the bar of actions that selecting just put there). + const onClick = (ev: MouseEvent) => { + if (!longPress.takeClick()) return; + ev.preventDefault(); + ev.stopPropagation(); + }; + window.addEventListener("pointerup", end, true); + window.addEventListener("pointercancel", end, true); + window.addEventListener("click", onClick, true); + return () => { + window.removeEventListener("pointerup", end, true); + window.removeEventListener("pointercancel", end, true); + window.removeEventListener("click", onClick, true); + longPress.dispose(); + }; + }, [longPress]); // What the row actions (desktop buttons and the phone ⋮ menu) need. const [properties, setProperties] = useState<{ @@ -4070,10 +4088,11 @@ export default function FileSystemScreen() { On a phone this sits in a compact header pinned over the list (#936): the open folder with search, the drive and ⋮ on top (or the selection, while selecting), - the path under it. Wider windows keep the page header and the drive chips. */} + the path under it (beside it on a phone held sideways, where height is short). + Wider windows keep the page header and the drive chips. */}
{phoneSelecting ? ( )} -
+
)} + {props.unpack && props.make !== "image" && props.make !== "folder" && !ps4Package && ( + + )} {props.onLanguage && props.make !== "image" && props.make !== "folder" && !ps4Package && (
diff --git a/client/src/screens/FpkgConvert/QueueCard.tsx b/client/src/screens/FpkgConvert/QueueCard.tsx index 2ef8008e1..be921df16 100644 --- a/client/src/screens/FpkgConvert/QueueCard.tsx +++ b/client/src/screens/FpkgConvert/QueueCard.tsx @@ -106,6 +106,8 @@ export function QueueCard(p: QueueCardProps) { return tr("cq_tag_lz4", undefined, "LZ4"); case "unpack": return tr("cq_tag_unpack", undefined, "unpacked"); + case "no-emulator": + return tr("cq_tag_no_emulator", undefined, "no AMPR emulator"); case "level": return t.level === "fast" ? tr("cq_tag_level_fast", undefined, "fast") diff --git a/client/src/screens/FpkgConvert/QueueItemOptions.tsx b/client/src/screens/FpkgConvert/QueueItemOptions.tsx index a8da8a1d9..91db10e0b 100644 --- a/client/src/screens/FpkgConvert/QueueItemOptions.tsx +++ b/client/src/screens/FpkgConvert/QueueItemOptions.tsx @@ -40,7 +40,9 @@ export function kindsFor(source: string, isDir?: boolean): Kind[] { } /** The change for choosing `kind`: an image keeps its own format choice when it was one, and an - * image or folder keeps the asset packs it had (#905: they are no longer lost on the way). */ + * image or folder keeps the asset packs it had (#905: they are no longer lost on the way). + * Writing a packed game's files out plain goes along into any kind (#933); leaving its AMPR + * emulator out is a package's choice only, so it stays behind. */ export function changeForKind(item: ConvertItem, kind: Kind, canInstall: boolean, host: string | null): ConvertItemChange { const base: ConvertBuild = kind === "image" @@ -49,8 +51,9 @@ export function changeForKind(item: ConvertItem, kind: Kind, canInstall: boolean : { kind: "image", format: "exfat", compress: false } : { kind }; const packs = packsOf(item.build); + const plain: ConvertBuild = item.build?.unpackPacks && !base.unpackPacks ? { ...base, unpackPacks: true } : base; // The kind it already is (its segment picked again) keeps the build whole, packs included. - const build = item.build && kind === item.build.kind ? item.build : packs.kind === "none" ? base : withPacks(base, packs); + const build = item.build && kind === item.build.kind ? item.build : packs.kind === "none" ? plain : withPacks(base, packs); const then = thenFor(kind, item.then, canInstall); return { build, then, host: then !== "keep" ? (item.host ?? host) : null }; } diff --git a/client/src/screens/FpkgConvert/cards.test.tsx b/client/src/screens/FpkgConvert/cards.test.tsx index f8ae5c638..2a9fb2cb6 100644 --- a/client/src/screens/FpkgConvert/cards.test.tsx +++ b/client/src/screens/FpkgConvert/cards.test.tsx @@ -258,6 +258,56 @@ describe("OptionsCard for an image", () => { }); }); +describe("OptionsCard for a package of a game in asset packs (#933)", () => { + const props = { + outputDir: "/out", + onChangeOutput: () => {}, + onOutputTyped: () => {}, + canBrowse: true, + compression: "balanced" as const, + onCompression: () => {}, + estimates: undefined, + locked: false, + }; + const pkgUnpack = (on: boolean, leaveOut = false) => ({ + kind: "zstd" as const, + on, + onToggle: () => {}, + leaveOutEmulator: { on: leaveOut, onToggle: () => {} }, + }); + it("offers the plain files beside the compression, and leaving the emulator out only under them", () => { + const on = renderToStaticMarkup(); + expect(on).toMatch(/data-testid="unpack-option"[^>]*>\s*]*checked/); + expect(on).toContain("the package holds every file as a plain file"); + expect(on).toContain('role="radiogroup"'); + expect(on).toContain('data-testid="leave-out-ampr-emu"'); + expect(on).toContain("Leave out the AMPR emulator"); + expect(on).not.toMatch(/data-testid="leave-out-ampr-emu"[^>]*>\s*]*checked/); + const left = renderToStaticMarkup(); + expect(left).toMatch(/data-testid="leave-out-ampr-emu"[^>]*>\s*]*checked/); + // Unticked, the packs go in as they are and the emulator has to stay. + const off = renderToStaticMarkup(); + expect(off).toContain('data-testid="unpack-option"'); + expect(off).not.toMatch(/data-testid="unpack-option"[^>]*>\s*]*checked/); + expect(off).not.toContain("leave-out-ampr-emu"); + }); + it("offers no emulator choice for an image, and nothing for a PS4 package", () => { + const image = renderToStaticMarkup( + {} }} + unpack={{ kind: "lz4", on: true, onToggle: () => {} }} + />, + ); + expect(image).toContain('data-testid="unpack-option"'); + expect(image).toContain("no longer needs ShadowMount+ to read packs"); + expect(image).not.toContain("leave-out-ampr-emu"); + const ps4 = renderToStaticMarkup(); + expect(ps4).not.toContain("unpack-option"); + }); +}); + describe("OptionsCard verification", () => { const props = { outputDir: "/out", @@ -670,6 +720,17 @@ describe("a waiting game's own options (#669)", () => { expect(changeForKind(waitingItem({ build: folder }), "folder", true, null).build).toEqual(folder); const unpacked: ConvertBuild = { kind: "folder", unpackPacks: true }; expect(changeForKind(waitingItem({ build: unpacked }), "folder", true, null).build).toEqual(unpacked); + // #933: plain files go along into another kind; leaving the emulator out is a package's own. + const pkg: ConvertBuild = { kind: "pkg", unpackPacks: true, leaveOutAmprEmu: true }; + expect(changeForKind(waitingItem({ source: "/dl/game.exfat", build: pkg }), "folder", true, null).build).toEqual({ + kind: "folder", + unpackPacks: true, + }); + expect(changeForKind(waitingItem({ source: "/dl/game.exfat", build: unpacked }), "pkg", true, null).build).toEqual({ + kind: "pkg", + unpackPacks: true, + }); + expect(changeForKind(waitingItem({ build: pkg }), "pkg", true, null).build).toEqual(pkg); }); it("a game on a server or the PS5 has no folder here to be saved next to", async () => { diff --git a/client/src/screens/FpkgConvert/index.tsx b/client/src/screens/FpkgConvert/index.tsx index 099e2c5e9..0f4b7052b 100644 --- a/client/src/screens/FpkgConvert/index.tsx +++ b/client/src/screens/FpkgConvert/index.tsx @@ -221,6 +221,10 @@ export default function WorkshopScreen() { const [lz4Profile, setLz4Profile] = useState<{ name: string; text: string; measured?: boolean } | null>(null); // A game in asset packs written as plain files again; the game's own, off for the next one. const [unpackPacks, setUnpackPacks] = useState(false); + // The same for a package (#933): on for each new game, since a package is installed and read + // by the console itself; its AMPR emulator stays unless the user leaves it out. + const [pkgUnpack, setPkgUnpack] = useState(true); + const [leaveOutEmu, setLeaveOutEmu] = useState(false); const [packKind, setPackKind] = useState<"lz4" | "zstd">("lz4"); const [emuAddedTo, setEmuAddedTo] = useState(null); const [zstdUpdatedTo, setZstdUpdatedTo] = useState(null); @@ -242,6 +246,8 @@ export default function WorkshopScreen() { zstd?: ZstdPacks, /** Write this game's asset packs out as plain files (the game under ①, when ticked). */ unpack?: boolean, + /** With `unpack`, a package's: leave its AMPR emulator out. */ + leaveOutAmprEmu?: boolean, ): boolean | QueueSkip => { // A later part of a multi-part archive is read through its first part. if (isRarLaterVolume(src)) return "later-part"; @@ -276,7 +282,9 @@ export default function WorkshopScreen() { ? { ...build, lz4 } : build.kind === "folder" && unpack ? { ...build, unpackPacks: true } - : build, + : build.kind === "pkg" && unpack + ? { kind: "pkg", unpackPacks: true, ...(leaveOutAmprEmu ? { leaveOutAmprEmu: true } : {}) } + : build, imageDest: build.kind === "image" ? { volume: u.destinationVolume, subpath: u.destinationSubpath || DEFAULT_IMAGE_SUBPATH } @@ -453,6 +461,8 @@ export default function WorkshopScreen() { setLz4On(false); setLz4Profile(null); setUnpackPacks(false); + setPkgUnpack(true); + setLeaveOutEmu(false); void check(path); }, [check, reset, setSource, setPassword], @@ -663,6 +673,9 @@ export default function WorkshopScreen() { language: language || undefined, keepBoth: out.keepBoth, update, + ...(pkgUnpackOn && !update + ? { unpackPacks: true, ...(pkgLeavesOutEmu ? { leaveOutAmprEmu: true } : {}) } + : {}), }, { install, @@ -709,6 +722,8 @@ export default function WorkshopScreen() { setLz4On(false); setLz4Profile(null); setUnpackPacks(false); + setPkgUnpack(true); + setLeaveOutEmu(false); setInspection(null); setEstimates(null); setChecking(false); @@ -798,6 +813,19 @@ export default function WorkshopScreen() { ? { kind: inspection.packs, on: unpackPacks, onToggle: setUnpackPacks } : undefined; const unpackOn = !!unpackChoice?.on; + // A package of a packed game (#933): its files plain unless unticked, and under that the + // choice to leave its AMPR emulator out. + const pkgUnpackChoice: UnpackChoice | undefined = + inspection?.packs && build.kind === "pkg" && !inspection.ps4_game + ? { + kind: inspection.packs, + on: pkgUnpack, + onToggle: setPkgUnpack, + leaveOutEmulator: { on: leaveOutEmu, onToggle: setLeaveOutEmu }, + } + : undefined; + const pkgUnpackOn = !!pkgUnpackChoice?.on; + const pkgLeavesOutEmu = pkgUnpackOn && leaveOutEmu; // "Remove backport libraries" is for an image or folder of the one game checked, when its // fakelib holds any; not with an update merged in (the merged game is another source). const backport = @@ -1217,7 +1245,7 @@ export default function WorkshopScreen() { // A game's own: nothing to offer until the next game is checked. lz4: locked ? undefined : lz4Choice, }} - unpack={locked ? undefined : unpackChoice} + unpack={locked ? undefined : (unpackChoice ?? pkgUnpackChoice)} language={locked ? nextLanguage : language} onLanguage={locked ? setNextLanguage : setLanguage} onCompression={setCompression} @@ -1318,7 +1346,8 @@ export default function WorkshopScreen() { ? folderLz4Options(lz4Choice, packProfile) : undefined, build.kind === "folder" ? folderPackOptions(lz4Choice, packProfile) : undefined, - unpackOn, + build.kind === "pkg" ? pkgUnpackOn : unpackOn, + build.kind === "pkg" && pkgLeavesOutEmu, ); if (r === "not-image" || r === "not-folder" || r === "later-part") setError(skippedText(r, 1)); else if (!r) setError(tr("cq_already", undefined, "This game is already in the queue.")); diff --git a/client/src/state/convertQueue.test.ts b/client/src/state/convertQueue.test.ts index 8ab9aea1c..66f1c8adb 100644 --- a/client/src/state/convertQueue.test.ts +++ b/client/src/state/convertQueue.test.ts @@ -380,6 +380,12 @@ describe("a queued game's asset packs (#905)", () => { expect(queueTags({ ...base, build: { kind: "pkg" }, language: "en-US" })).toEqual([ { kind: "language", code: "en-US" }, ]); + // #933: a package's plain files, and its emulator left out (only ever with them). + expect( + queueTags({ ...base, build: { kind: "pkg", unpackPacks: true, leaveOutAmprEmu: true }, language: "de-DE" }), + ).toEqual([{ kind: "unpack" }, { kind: "no-emulator" }, { kind: "language", code: "de-DE" }]); + expect(queueTags({ ...base, build: { kind: "pkg", unpackPacks: true } })).toEqual([{ kind: "unpack" }]); + expect(queueTags({ ...base, build: { kind: "pkg", leaveOutAmprEmu: true } })).toEqual([]); }); it("keeps packs set while waiting through a restart, and the build gets them", async () => { diff --git a/client/src/state/convertQueue.ts b/client/src/state/convertQueue.ts index edaa096e5..862f7a727 100644 --- a/client/src/state/convertQueue.ts +++ b/client/src/state/convertQueue.ts @@ -19,9 +19,10 @@ export type ConvertStatus = "pending" | "running" | "installing" | "handed" | "d * package). An image's `lz4`: pack the game's data into asset packs first (LZ4, or zstd with * `zstdLevel`), in any format, compressed or not. A folder's `zstd` / `lz4`: its files in zstd * or LZ4 packs (then a game folder can be the source too). `unpackPacks`: a game in asset - * packs written as plain files again (a game folder can then be a folder's source too). */ + * packs written as plain files again (a game folder can then be a folder's source too); a + * package of it can also leave the AMPR emulator out (`leaveOutAmprEmu`, #933). */ export type ConvertBuild = - | { kind: "pkg" } + | { kind: "pkg"; unpackPacks?: boolean; leaveOutAmprEmu?: boolean } | { kind: "image"; format: ImageFormat; compress: boolean; lz4?: AmprLz4Options; unpackPacks?: boolean } | { kind: "folder"; zstd?: ZstdPacks; lz4?: AmprLz4Options; unpackPacks?: boolean }; @@ -109,6 +110,7 @@ export type QueueTag = | { kind: "zstd"; level: number } | { kind: "lz4" } | { kind: "unpack" } + | { kind: "no-emulator" } | { kind: "level"; level: FfpfscLevel } | { kind: "language"; code: string }; @@ -118,7 +120,8 @@ export function queueTags(item: ConvertItem): QueueTag[] { const packs = packsOf(b); if (packs.kind === "zstd") tags.push({ kind: "zstd", level: packs.level ?? DEFAULT_ZSTD_LEVEL }); if (packs.kind === "lz4") tags.push({ kind: "lz4" }); - if ((b?.kind === "image" || b?.kind === "folder") && b.unpackPacks) tags.push({ kind: "unpack" }); + if (b?.unpackPacks) tags.push({ kind: "unpack" }); + if (b?.kind === "pkg" && b.unpackPacks && b.leaveOutAmprEmu) tags.push({ kind: "no-emulator" }); if (b?.kind === "image" && b.compress && item.imageLevel) tags.push({ kind: "level", level: item.imageLevel }); if ((!b || b.kind === "pkg") && item.language) tags.push({ kind: "language", code: item.language }); return tags; diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index f662f2969..ba14cd872 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -1482,6 +1482,7 @@ "cq_tag_level_fast": "115dc360 k4Y4C4qLHj9Sx-sjL-w1P17T7r63SYOZGMqgtawj9S3Nh9MhZNFniu25R25R", "cq_tag_level_smallest": "3ccda332 M9VYvJXHxw9jlQyxtFDvK5oyaESPem2AwMOZytJWDFN1dbTDldKkRe2Aw2Aw", "cq_tag_lz4": "b0f2d0b1 sPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPLsPL", + "cq_tag_no_emulator": "c7aa6252 rlMHkiTtcn1gkW6ZBPIgUjuX-DkfA02lw5slNvvwmrEXwAcgUnA9wyr5WKE4", "cq_tag_unpack": "83055ac7 z6m32OoV-JdrjQDl3JAhSyEfdWs2Uf4IYyoOk0aCpq7zIRtAlFOTx_e6ee6e", "cq_tag_zstd": "04c35dad hoFhoFhoFhoFhoFhoFhoFhoFhoFhoFtuMhoFhoFhoFhoFhoFhoFhoFtuMtuM", "cq_then_keep": "7d27518d 14p3dogluRUwazvEAfTsrxBlcZBE__Dqm9xFO3oixi-ucB2PbNwzU3uBkc0-", @@ -3453,6 +3454,8 @@ "fpkg.languageHint": "15f63c11 T7S0hmW14Ojw60FYeUE7f_3xHuDsv35eerAlfmhhmhV5U44U-tI0fUjbcmo8", "fpkg.launch": "d61fdda2 ejVNQeK5PEo2Knv8U2MBEadvUaKteZRqeOgawjednCvVT2aq7_7iyjMrOhaJ", "fpkg.launchUnknown": "b991ea93 SCK-nrwD3eQ-aWoK3Up_nh1QPCoFHKvRfHNsqnFCqH_TQLSWIBm1i6efGRzU", + "fpkg.leave_out_ampr_emu": "4b22f4da -Hd5vCPiTV_FF6xqCVhvl7PZCoSETTyHdeOIUukhXZ00NQqcAbS6I8dTsoIk", + "fpkg.leave_out_ampr_emu_body": "84bf2023 0ziIqspIj1TZnNn8DvPipt6g1CkpJiAmess4UwvE1sKQH4bZ362ZUX9bw6KV", "fpkg.lowSpace": "3becc3e9 tofsSOyqvVu1FQFkRAk3TbqCUMXrStPxL4ZnQvitvpy5E7FSsc64CswUF7Xe", "fpkg.lowSpaceCompressed": "de1adbb8 PJ9syyOjadvZnBafQIm6ynjVU1WMnKQlqpFueYh5yPYCCQz9uFMiyn-3I-hG", "fpkg.lz4_saved_nothing": "efc7b859 DLMAJckMoJ0hD_H0tsFsbM2__A-N3K8QLksw6hxG71hX1DgSNzhLS_c97_kn", @@ -3555,6 +3558,7 @@ "fpkg.unpack_lost": "a9bd1e41 3Geme-Vsah3bDShxa7fucYTSULJ21AZe9Dv12j6Drt3o8Jn_zUSscyEViNAO", "fpkg.unpack_packs": "1d695e78 ggudtOiDZos4sgc-DkDxHu7l44kTCKodI-T4oac6i7VISyaRXISq5C6qIPot", "fpkg.unpack_packs_body": "c32fb69a dwomeXyab5QBXs1k_XX3dXSUQ-IIMNde4q71rHXWKvA9r7jm8Rxm89Ws_vLH", + "fpkg.unpack_packs_pkg_body": "f6c5e4ee PqXkG0KZQVv6a_KLOBieiZtWsnt9NIoYKX3gfFTtH49ylWk-VWAupZYmyzYw", "fpkg.uploadImage": "f676f9d4 WFDNV4H_xvxXzi5Gej4VJUy0kP4mHNfIvkszyRxnMkcBPWazCXksOt7wC0WC", "fpkg.uploadImageDelete": "b47424f4 0av1E-Kh5AEzWPCRWwhxeNQs-sd_-u-q_idlLkaGJ1fDQLyhPyT9GatlVqce", "fpkg.uploadInstall": "c980e84c t_vdM8ZH0I0Rn6c7SxuxwAMInzDUC2QW8LPIMCWyaPqj89v4aasKeEEPr8P_", From 6cf69ea10c706d7ed74635c9acf5572c59cc7d69 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:23:20 -0800 Subject: [PATCH 24/27] Convert e2e: a packed game's .pkg is unpacked by default, emulator left out on request (#933) Checks the Convert screen end to end against a mocked engine: a plain game gets no unpack option, a packed one has it ticked, "Leave out the AMPR emulator" is under it (hidden while unpacking is off), and both reach the package build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/e2e/workshop-pkg-unpack.spec.ts | 75 ++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 client/e2e/workshop-pkg-unpack.spec.ts diff --git a/client/e2e/workshop-pkg-unpack.spec.ts b/client/e2e/workshop-pkg-unpack.spec.ts new file mode 100644 index 000000000..a30cddc58 --- /dev/null +++ b/client/e2e/workshop-pkg-unpack.spec.ts @@ -0,0 +1,75 @@ +// #933: a game in asset packs made into a .pkg. "Unpack the asset packs" is ticked by default, +// "Leave out the AMPR emulator" sits under it unticked (and goes away when unpacking is off), and +// both reach the engine's package build. A plain game is offered neither. +import { expect, test } from "@playwright/test"; + +test("a packed game's package is unpacked by default and can leave the emulator out", async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 1400 }); + const builds: Record[] = []; + const json = (body: unknown, status = 200) => ({ status, contentType: "application/json", body: JSON.stringify(body) }); + const inspection = (source: string) => ({ + source: `folder ${source}`, + files: 3, + bytes: 3 << 20, + content_id: "UP9000-PPSA01234_00-PACKEDGAME000000", + title: source.endsWith("Packed") ? "Packed Game" : "Plain Game", + planned_size: 3 << 20, + output_free: 1 << 40, + checks: [{ name: "eboot.bin", ok: true, detail: "ok" }], + ...(source.endsWith("Packed") ? { packs: "zstd" } : {}), + }); + await page.route( + (u) => u.pathname.startsWith("/api/"), + async (route) => { + const req = route.request(); + const path = new URL(req.url()).pathname; + const body = req.postDataJSON?.() as Record | null; + if (path === "/api/fpkg/inspect") return route.fulfill(json(inspection(String(body?.source ?? "")))); + if (path === "/api/fpkg/estimate") return route.fulfill(json({ error: "no" }, 500)); + if (path === "/api/fpkg/build") { + builds.push(body ?? {}); + return route.fulfill(json({ job_id: `job-${builds.length}` })); + } + if (/^\/api\/jobs\/[^/]+$/.test(path)) + return route.fulfill( + json({ + status: "done", + started_at_ms: 0, + completed_at_ms: 1, + elapsed_ms: 1, + tx_id_hex: "PPSA01234", + bytes_sent: 10, + dest: "/out/PPSA01234.pkg", + }), + ); + return route.fulfill(json({ error: "down" }, 503)); + }, + ); + await page.goto("/workshop"); + const main = page.getByRole("main"); + await expect(main.getByText("① Game")).toBeVisible({ timeout: 30_000 }); + + // A plain game: nothing to unpack. + const source = main.locator("#fpkg-source"); + await source.fill("/games/Plain"); + await source.blur(); + await expect(main.getByText("Plain Game").first()).toBeVisible(); + await expect(main.getByTestId("unpack-option")).toHaveCount(0); + + // A packed game: unpacked unless unticked; the emulator stays unless left out. + await source.fill("/games/Packed"); + await source.blur(); + await expect(main.getByText("Packed Game").first()).toBeVisible(); + const unpack = main.getByTestId("unpack-option").getByRole("checkbox"); + await expect(unpack).toBeChecked(); + const leaveOut = main.getByTestId("leave-out-ampr-emu").getByRole("checkbox"); + await expect(leaveOut).not.toBeChecked(); + await unpack.uncheck(); + await expect(main.getByTestId("leave-out-ampr-emu")).toHaveCount(0); + await unpack.check(); + await leaveOut.check(); + + await main.getByRole("button", { name: "Convert only" }).first().click(); + await expect.poll(() => builds.length).toBe(1); + expect(builds[0]).toMatchObject({ source: "/games/Packed", unpack_packs: true, leave_out_ampr_emu: true }); +}); From c8e306d15af1d53b441ef7e10bfeb5510fa7b350 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:24:59 -0800 Subject: [PATCH 25/27] 12.6.30 release notes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- CHANGELOG.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11f6101d0..9aa93e24a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,39 @@ What's new in ps5upload, written for humans. --- +## Unreleased + +**Files on phones** +- **Back closes what's open first (#932).** On Android, Back used to leave Files even with a menu open. Now it closes the open menu or dialog, then leaves selection, then goes up one folder, and only leaves Files at the top of a drive. +- **More room for your files (#936).** On a phone, the top of Files is now one compact bar that stays put while you scroll: the folder name, Search, the drive switcher and ⋮ for the rest, with the path below it (beside it when the phone is sideways). +- **Long-press to select.** Checkboxes stay hidden until you long-press a row (or pick ⋮ → Select). While selecting, the top bar shows the count and Select all, and a bar at the bottom offers Copy, Move, Rename, Delete and More. Tablets and computers look the same as before. + +**Play Together on a TV (#926)** +- **The join screen works with a TV remote.** The arrows move between buttons, OK presses one, and the first useful button already has focus. Back steps out in order: it closes a dialog, then shows the buttons, then leaves full screen. During the game the remote's arrows and OK play the game. +- **On Android TV**, the app's first screen offers a big "Join Play Together" button, the game opens in full screen, and the focus ring is easy to see from the couch. + +**Convert** +- **A packed game can become a plain package (#933).** When you make a .pkg from a game whose files are in asset packs (zstd or LZ4), Convert now writes the files out plain again, on by default. A second option leaves out the AMPR emulator files. That one is off by default, because it isn't known yet whether every game runs without them. + +**Games** +- **Updated PS4 games show their real version (#934).** PS4 games with an update installed showed no version and were offered the update again. The app now reads the version where PS4 games keep it, so the game page, update installs and cheat matching see 01.32 instead of 01.00. + +**Backups and cheats** +- **A restore that put nothing back no longer says it worked.** If only some files came back, the Backup screen says how many couldn't be restored. +- **XML game patches check they're writing into the game itself**, as other game patches already do. +- **The console page stays usable during big transfers.** One worker is always kept free for the page. + +**Safety fixes from an audit** +- The app only installs an update file that matches the checksum of the release it checked, and checks it again right before installing. +- The app's pages can only read the files they show (screenshot previews and game covers), not any file on disk. +- Sending a payload by its path only sends payload files. +- Adding the app to an AI agent only passes a clean web address, and a failed move keeps the agent's old entry. +- NAS and FTP file names that aren't standard text now list and copy instead of failing. +- A save restore can never write outside the save folder it names. +- Replies from consoles and servers have size limits, so a bad reply can't fill memory. +- Extracting from an .ffpkg image refuses a folder that contains itself instead of running forever. +- Release builds check the tools they download and pin their base images. + ## 12.6.29 **Fake packages (FPKG)** From f8d3a42c5ad229d2679ce9ba0207f7bc4b75dffb Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 04:48:41 -0800 Subject: [PATCH 26/27] Rebuild the join and pad pages with the combined changes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- engine/crates/ps5upload-engine/src/join_page.html | 2 +- engine/crates/ps5upload-engine/src/pad_page.html | 2 +- site/join/index.html | 2 +- site/pad/index.html | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/engine/crates/ps5upload-engine/src/join_page.html b/engine/crates/ps5upload-engine/src/join_page.html index b5d815491..a60fa417f 100644 --- a/engine/crates/ps5upload-engine/src/join_page.html +++ b/engine/crates/ps5upload-engine/src/join_page.html @@ -270,7 +270,7 @@ z AÍp\Ž0N˜HJê´ªØ^U I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var E={a:v};this.setModule=t=>{e.setModule(bi,t)},this.getModule=()=>e.getModule(bi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,E)).then(e=>{let t=e.exports;y(t),a=t.g,o(),T(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=C,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var xi=o((()=>{}));function Si(e={}){Si.errors||Object.defineProperties(Si,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(Si.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var Ci=o((()=>{yi(),xi()})),wi,Ti=o((()=>{yi(),xi(),Ci(),wi=class extends hi{constructor(e){super(e,`opus-decoder`,Si,bi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ei=c({OpusDecoder:()=>Si,OpusDecoderWebWorker:()=>wi}),Di=o((()=>{Ci(),Ti(),yi(),_i(Si,`OpusDecoder`),_i(wi,`OpusDecoderWebWorker`)})),Oi=[8e3,12e3,16e3,24e3,48e3],ki=null;function Ai(){return ki??=Xn(()=>Promise.resolve().then(()=>(Di(),Ei)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw ki=null,e}),ki}function ji(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function Mi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ni=class{constructor(e,t=Ai){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!ji())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Oi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(Mi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Pi={makeDecoder:e=>new Ni(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Fi(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Ii(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var Li=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ri(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Li)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function zi(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Bi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Vi(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function F(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Hi=(e,t,n,...r)=>Vi(e,F([t,1],[n,3]),...r),Ui=F([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Wi(e){let t=e.handler===`vide`,n=Vi(`ftyp`,new TextEncoder().encode(`isom`),F([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Vi(`moov`,Hi(`mvhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Ui,new Uint8Array(24),F([2,4])),Vi(`trak`,Hi(`tkhd`,0,3,F([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Ui,F([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Vi(`mdia`,Hi(`mdhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Hi(`hdlr`,0,0,F([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),F([0,1])),Vi(`minf`,t?Hi(`vmhd`,0,1,new Uint8Array(8)):Hi(`smhd`,0,0,F([0,4])),Vi(`dinf`,Hi(`dref`,0,0,F([1,4]),Hi(`url `,0,1))),Vi(`stbl`,Hi(`stsd`,0,0,F([1,4]),e.sampleEntry),Hi(`stts`,0,0,F([0,4])),Hi(`stsc`,0,0,F([0,4])),Hi(`stsz`,0,0,F([0,4],[0,4])),Hi(`stco`,0,0,F([0,4])))))),Vi(`mvex`,Hi(`trex`,0,0,F([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Gi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Hi(`trun`,0,1793,F([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Vi(`traf`,Hi(`tfhd`,0,131072,F([1,4])),Hi(`tfdt`,1,0,F([t,8])),o(e)),c=Hi(`mfhd`,0,0,F([e,4])),l=Vi(`moof`,c,s(0)).length,u=Vi(`moof`,c,s(l+8)),d=Vi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Ki(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=zi(e).filter(e=>!r.includes(Bi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var qi=e=>e.toString(16).padStart(2,`0`),Ji=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Yi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Xi(e){let t=zi(e),n=t.filter(e=>Bi(e,!1)===7),r=t.filter(e=>Bi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Yi([F([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(Ji),F([r.length,1]),...r.map(Ji)])}function Zi(e,t,n){let r=zi(e),i=e=>r.filter(n=>Bi(n,t)===e),a=(e,t)=>Vi(e,new Uint8Array(6),F([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),F([24,2],[65535,2]),t);if(!t){let t=i(7),r=Xi(e);return r?{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Vi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${qi(t[0][1])}${qi(t[0][2])}${qi(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Xr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Yi([F([128|e,1],[t.length,2]),...t.map(Ji)]),m=Vi(`hvcC`,F([1,1]),u,F([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Qi(e,t,n,r,i,a){return Gi(e,t,n,Ki(r,i),a)}function $i(e,t){let n=Vi(`dOps`,F([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Wi({handler:`soun`,timescale:48e3,sampleEntry:Vi(`Opus`,new Uint8Array(6),F([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function ea(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function ta(e,t,n){return Gi(e,t,ea(n),n,!0)}var na={watch:30,player:4},ra={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ia={seek:.8,speed:.25,target:.12};function aa(e,t,n){let r=typeof n==`string`?ra[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function oa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ha(e,t,n):new ka(e,t,n)}var sa=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function I(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var L=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ca(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function la(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ua=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+da;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},da=.02;async function fa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var pa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},ma=[`pointerup`,`touchend`,`click`,`keydown`],ha=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():la(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new pa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new sa(n),this.clock=new ua(t===`player`?.05:.08),typeof AudioDecoder>`u`&&va()&&(this.mseSound=new ya(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=ni(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!xa())return!1;let e=new ka(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,ga(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=ni(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await Aa(e):Ii(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Xi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=ri(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Fi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>na[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Ki(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];fa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return va()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new si((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ca(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new ya(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new si((e,n)=>this.play(e,n,t.sampleRate),Pi,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ca(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function ga(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function _a(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function va(){let e=typeof window>`u`?null:xa();return!!e&&(_a(e,`audio/mp4; codecs="Opus"`)||_a(e,`audio/mp4; codecs="opus"`))}var ya=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new L,this.el=n,this.track=new Ta(n,()=>this.fail(),e===`player`?ia:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=I(e);if(!t||!this.order.take(t.index))return;let n=ta(this.track.nextSeq(),this.time,t.packet);this.time+=ea(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=$i(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},ba=class{constructor(e,t,n=Pi){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ua(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,ga();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new si((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ca(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function xa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var Sa=10,Ca=3;function wa(e,t,n,r=Ca){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var Ta=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=xa();if(!n||!_a(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=Ea(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=aa(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>Sa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-Ca;if(this.keys){if(r=wa(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Ca&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function Ea(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Da=1e4,Oa=class{constructor(e=3,t=Da,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ka=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new pa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new sa(n),this.fails=new Oa(3,Da,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new ya(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new Ta(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!va())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ba(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?la(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=ni(e,this.hevc)??{w:1920,h:1080},r=Zi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Fi(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>na[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Qi(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function Aa(e){let t=ii(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ri(1920,1080)}var R={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},ja={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ma(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Na={ArrowUp:{button:R.UP},ArrowDown:{button:R.DOWN},ArrowLeft:{button:R.LEFT},ArrowRight:{button:R.RIGHT},Enter:{button:R.CROSS},Space:{button:R.CROSS},Backspace:{button:R.CIRCLE},Escape:{button:R.CIRCLE},KeyQ:{button:R.SQUARE},KeyE:{button:R.TRIANGLE},KeyZ:{button:R.L1},KeyC:{button:R.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:R.L3},KeyG:{button:R.R3},Tab:{button:R.OPTIONS},Backquote:{button:R.SHARE},KeyH:{button:R.PS},KeyT:{button:R.TOUCHPAD},KeyW:{stick:`ly`,dir:-1},KeyS:{stick:`ly`,dir:1},KeyA:{stick:`lx`,dir:-1},KeyD:{stick:`lx`,dir:1},KeyI:{stick:`ry`,dir:-1},KeyK:{stick:`ry`,dir:1},KeyJ:{stick:`rx`,dir:-1},KeyL:{stick:`rx`,dir:1}};R.UP,R.DOWN,R.LEFT,R.RIGHT,R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD;var Pa=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Fa(e,t=Na){let n={...ja};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Pa(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Ia=[R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,0,0,R.SHARE,R.OPTIONS,R.L3,R.R3,R.UP,R.DOWN,R.LEFT,R.RIGHT,R.PS,R.TOUCHPAD];function La(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Ra=[0,1,1,1,0,-1,-1,-1],za=[-1,-1,0,1,1,1,0,-1];function Ba(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=La(n);return e===null?0:(t.hat===`x`?Ra:za)[e]}return t.inv?-n:n}var Va={buttons:Ia.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function Ha(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=La(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ua(e){if(e.mapping===`standard`)return Va;let t=Wa.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Va;let r={...Va,buttons:[...Va.buttons,[R.UP,{h:n,at:0}],[R.RIGHT,{h:n,at:2}],[R.DOWN,{h:n,at:4}],[R.LEFT,{h:n,at:6}]]};return Wa.set(e.id,r),r}var Wa=new Map;function Ga(e,t=Ua){let n={...ja},r=e=>Math.abs(e)<.08?0:Pa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(Ba(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Ha(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Ha(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Ha(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Ka(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Pa(e.lx+t.lx),ly:Pa(e.ly+t.ly),rx:Pa(e.rx+t.rx),ry:Pa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function qa(e,t,n,r=()=>globalThis.navigator?.getGamepads?.()??[]){let i=e=>e?.vibrationActuator;for(let a of e.some(i)?e:r()){let e=i(a);e&&(t===0&&n===0?e.reset?.():e.playEffect?.(`dual-rumble`,{duration:1e3,strongMagnitude:t/255,weakMagnitude:n/255}))}}var Ja=new Map;function Ya(e,t){return{id:`${e.id} (app)`,index:3+e.slot,connected:!0,mapping:`standard`,timestamp:0,axes:e.axes,buttons:e.buttons.map(e=>({pressed:e>.5,touched:e>0,value:e})),vibrationActuator:t?.vibrationActuator??null,hapticActuators:t?.hapticActuators??[]}}function Xa(e){let t=e?.getGamepads?.()??[];return Ja.size===0||t.some(e=>!!e?.connected)?[...t]:[...Ja.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ya(e))}var Za=`b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,,,,,,,a0,a1(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,,,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b3,b0,b1,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1(b1,b0,b2,b3,,b7,a3,a4,,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,b4,b5,,b9,,,b12,b14,b15,b13,,,a0,a1,a5~,a2~(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,,,b7,b5,b4,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b3,b4,b6,b5,b7,b2,b8,,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b9,b10,b2,b8,,,h0.1,h0.4,h0.8,h0.2,b5,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b5,b7,b2,,b8,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b12,b13,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b14,b13,b15,b12,b10,b11,b8,b9,b0,b3,b1,b2,b4,b6,b7,b5,b16,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,a2,a5,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,,,b8,b9,,,b12,b13,b15,b14,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,b11,b12,b13,b14,b15,b16,b10,,a0,a1,a2,a3(b0,b1,b3,b2,,b6,a2,a5,,b7,,,b8,b9,b10,b11,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,,,b8,b9,,,b10,b11,b12,b13,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,,,b13,b8,b10,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,,,b12,b9,b11,,,,,,,,hx,hy(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,b14,b15,b16,b17,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,,,,b2,,b4,,b5,,,h0.1,h0.4,h0.8,h0.2,b6(b0,b1,b2,b3,b12,b4,b13,b5,b14,b6,b15,b7,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b1,b3,b0,b2,b13,b5,b12,b4,,b6,,,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b33,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b16,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b15,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,,,,,b8,,a0,a1,a3,a4(b1,b0,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,,h0.1,h0.4,h0.8,h0.2,b12,b13(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b12,b13,b14,b15,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b14,b13,b14,b13,,,a0,a1,a3,a4(b1,b0,b2,b3,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b2,b3,b1,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b10(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,+a2,+a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,a2,a5,b6,b7,,,h0.1,h0.4,h0.8,h0.2,b8(b1,b2,,,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b21,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,b13,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,a5,a4,,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b7,b6,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b7,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a5,a4,b9,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b22,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a3,b6,b7,b9,,b12,b14,b15,b13,b8,,a0,a1(b3,b4,b5,b6,b7,b8,a9,a8,b11,b12,b14,b15,b16,b17,b18,b19,b13,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b7,b9,b6,b8,b10,b11,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b4,b3,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b3,b1,b4,,b10,a5,a4,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,,,,,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b10,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a4,+a4,-a3,+a3(b4,b8,b0,b12,b16,b20,b24,b28,b32,b36,b40,b44,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a8,a12(b8,b12,b0,b4,b16,b20,b24,b28,b32,b36,,,h0.1,h0.4,h0.8,h0.2,b44,,a0,a4,a8,a12(b4,b0,b8,b12,,b28,a12,a16,,b36,,,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a20,a8(b1,b2,b0,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b4,b0,b8,b12,,b28,a12,a16,,b36,,,b48,b56,b60,b52,,,a0,a4,a20,a8(b1,b2,,,b7,b5,a3,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a5,b9,b8,b6,b7,b11,b12,b13,b14,b10,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,,,b5,b8,,,-a1,+a1,-a0,+a0,b2(b0,b1,b2,b3,b4,b5,b6,b15,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b13,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,a5,a4,b12,b13,b15,b16,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,-a1,+a1,-a0,+a0,b2(b0,b1,b3,b4,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,b8,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a31(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,b6,b7,b16,b15,b8,b9,b10,b11,b13,b12,b17,,a0,a1~,a2,a3~(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a4(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b33,b5,,,b6,b7,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b2,,,,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b2,,,b6,,b9,b7,,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a2(b2,b1,b3,b0,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b4,,b6,,b2,b7,b9,,,b2,b14,b15,b13(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b5,b7,b2,b10,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,a5~,a2~,b2,b8,b8,b5,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b4,,b9,b10,b6,b7,b8,,b5,b2,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b5,b4,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b2,b6,b7,b4,b5,b8,b9,b11,b12,b13,b14,b15,b16,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b16,b19,b17,b18,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b8,b9,b6,b7,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b10,b5,b11,b7,b8,b9,b4,b6,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b5,b7,b4,b6,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b13,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b0,b4,b2,b1,b3,b6,,,b11,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a2,a5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b9,b10,a4,a5,b4,b6,b7,b8,b11,b12,b13,b14,,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b3,b2,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,b11,b14,b12,b13,b10,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,a4,a3,,,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b6,b7,b9,b10,b12,b13,b14,b15,b16,b17,b19,b20,h0.1,h0.4,h0.8,h0.2,b18,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,,,,,,,b7,b6,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,a0,a1(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a5(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a3,a4(b1,b0,b4,b3,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a5`.split(`(`),Qa={l00790006:0,l00790011:1,l00790016:2,l00790122:3,l00790126:4,l00791800:5,l00791803:6,l0079181a:7,l0079181b:8,l0079181c:9,l00791830:10,l00791843:11,l00791844:12,l00791845:11,l00791846:13,l007918d2:7,l007918d4:14,l0079954e:15,l046dc20a:16,l046dc211:17,l046dc216:5,l046dc218:5,l046dc219:5,l046dc21a:18,l046dc21d:14,l046dc21e:14,l046dc21f:14,l046dcad1:5,l046dcad2:5,l04b4010a:19,l04b42411:20,l04b42412:21,l054c0268:22,l054c05c4:23,l054c09cc:24,l054c0ba0:24,l054c0cda:25,l054c0ce6:24,l054c0df2:24,l054c0e5f:24,l054c1337:26,l057e0330:27,l057e0337:28,l057e1337:29,l057e2006:30,l057e2007:31,l057e2008:32,l057e2009:33,l057e2017:34,l057e201e:35,l057e2069:36,l057e2073:37,l05ac022d:38,l05ac055b:39,l05ac057a:40,l05ac061a:41,l0e6f0109:42,l0e6f011e:7,l0e6f011f:14,l0e6f0128:5,l0e6f012f:7,l0e6f0130:7,l0e6f0131:14,l0e6f0139:14,l0e6f0146:43,l0e6f0164:14,l0e6f0180:7,l0e6f0181:7,l0e6f0184:7,l0e6f0185:44,l0e6f0187:7,l0e6f0188:7,l0e6f0203:45,l0e6f0207:46,l0e6f0213:14,l0e6f0214:7,l0e6f02a7:14,l0e6f02a8:47,l0e6f02b2:48,l0e6f02b8:14,l0e6f02c8:14,l0e6f02d7:49,l0e6f02d8:14,l0e6f02da:14,l0e6f02ef:14,l0e6f02f1:14,l0e6f0301:14,l0e6f0315:14,l0e6f0401:14,l0e6f0413:14,l0e6f1112:50,l0e6f1113:51,l0e6ff501:14,l0f0d0009:7,l0f0d0010:42,l0f0d0011:7,l0f0d0016:52,l0f0d0022:42,l0f0d004d:7,l0f0d005e:53,l0f0d005f:54,l0f0d0066:24,l0f0d0067:14,l0f0d006a:8,l0f0d006b:7,l0f0d006d:55,l0f0d006e:7,l0f0d0084:8,l0f0d0085:7,l0f0d0086:47,l0f0d0087:56,l0f0d0088:57,l0f0d0092:58,l0f0d00aa:39,l0f0d00c1:7,l0f0d00ee:59,l0f0d00f6:60,l0f0d00fb:39,l0f0d0137:61,l0f0d0138:62,l0f0d0150:14,l0f0d0185:14,l0f0d0196:63,l0f0d01ab:63,l15320401:24,l15320402:7,l15320705:64,l15320900:65,l15320a03:14,l15320a14:14,l15320a29:14,l15321000:8,l15321008:66,l1532100a:59,l1532100b:24,l15321100:24,l18d19400:65,l20d60dad:67,l20d62002:68,l20d62005:14,l20d6200b:14,l20d6200f:69,l20d62065:14,l20d62802:14,l20d64001:70,l20d64002:70,l20d64005:14,l20d66271:71,l20d6792a:24,l20d689e5:71,l20d6a710:5,l20d6a711:7,l20d6a712:7,l20d6a713:7,l20d6a714:7,l20d6ca6d:7,l24c65300:14,l24c6531a:14,l24c6541a:14,l24c6543a:14,l24c6581a:14,l24c65b02:14,l24c65d04:14,l24c6891a:63,l24c6891b:63,l24c6892a:72,l24c6892b:63,l24c6fafe:14,l27f80bbf:63,l28de1102:73,l28de1105:73,l28de1106:73,l28de1142:73,l28de11fc:43,l28de11ff:14,l28de1201:73,l28de1202:73,l28de1205:74,l2dc80651:75,l2dc81003:76,l2dc81080:76,l2dc82000:14,l2dc82003:14,l2dc8200a:77,l2dc82019:14,l2dc82025:14,l2dc82101:63,l2dc82830:78,l2dc82862:79,l2dc82865:79,l2dc82869:80,l2dc8286a:81,l2dc83010:82,l2dc83011:63,l2dc83012:63,l2dc83013:63,l2dc83015:63,l2dc83016:63,l2dc83017:63,l2dc83019:83,l2dc8301b:63,l2dc8301d:63,l2dc83100:84,l2dc83101:85,l2dc83102:85,l2dc83103:85,l2dc83104:85,l2dc83106:14,l2dc8310a:14,l2dc8310b:14,l2dc83230:86,l2dc83810:79,l2dc83820:87,l2dc85006:88,l2dc85101:89,l2dc85103:86,l2dc85104:90,l2dc85107:91,l2dc85108:91,l2dc85109:90,l2dc85111:92,l2dc85112:82,l2dc86000:92,l2dc86001:93,l2dc86002:92,l2dc86006:82,l2dc86007:94,l2dc86009:82,l2dc86012:63,l2dc86100:87,l2dc86101:93,l2dc86102:92,l2dc86728:95,l2dc89000:96,l2dc89001:96,l2dc89012:93,l2dc89015:79,l2dc89018:78,l2dc89020:97,l2dc89025:98,l2dc8ab21:78,l35371004:14,l35371007:63,l3537100b:14,l35371046:63,l35371058:63,l35371094:63,l35371097:63,l358a0102:63,l358a0202:63,l358a0203:63,l358a0204:63,m00790006:99,m00790011:100,m00791800:101,m00791803:102,m0079181c:41,m00791843:103,m00791844:104,m00791846:105,m007918d2:39,m0079954e:106,m046dc216:5,m046dc218:5,m046dc219:5,m046dc21a:18,m046dc21f:107,m04b4010a:108,m04b42411:20,m04b42412:20,m054c0268:22,m054c05c4:24,m054c09cc:24,m054c0ba0:24,m054c0cda:25,m054c0ce6:24,m054c0df2:24,m054c0e5f:24,m054c1337:26,m057e2006:30,m057e2007:31,m057e2009:60,m057e2017:109,m057e2069:36,m057e2073:37,m05ac061a:41,m0e6f0109:42,m0e6f0184:110,m0e6f0187:5,m0e6f0201:107,m0e6f0203:45,m0e6f0207:46,m0e6f0401:107,m0f0d002d:54,m0f0d004d:7,m0f0d005e:111,m0f0d005f:7,m0f0d0066:24,m0f0d006e:7,m0f0d0084:8,m0f0d0085:7,m0f0d0087:112,m0f0d0088:57,m0f0d0092:58,m0f0d00aa:39,m0f0d00c1:7,m0f0d00ee:113,m0f0d00f6:3,m0f0d0138:62,m0f0d0200:7,m15320401:24,m15320402:7,m15320705:64,m15320900:65,m15320a03:107,m15321000:8,m15321100:24,m18d19400:65,m20d66271:71,m20d6792a:24,m20d6a710:7,m20d6a711:44,m20d6ca6d:7,m24c6543a:107,m24c65d04:107,m24c6891a:114,m24c6891b:63,m24c6892a:64,m24c6892b:63,m24c6fafe:107,m2dc80651:115,m2dc82820:116,m2dc82830:78,m2dc82840:78,m2dc82865:87,m2dc82869:80,m2dc8286a:81,m2dc83011:63,m2dc83012:63,m2dc83013:63,m2dc83015:117,m2dc83016:63,m2dc83017:118,m2dc83019:83,m2dc8301b:63,m2dc8301d:63,m2dc83100:9,m2dc83101:85,m2dc83102:85,m2dc83103:85,m2dc83104:85,m2dc83105:84,m2dc83230:119,m2dc83810:94,m2dc85006:120,m2dc85101:89,m2dc85103:86,m2dc85104:90,m2dc85107:121,m2dc85108:122,m2dc85109:90,m2dc85111:82,m2dc85112:82,m2dc86001:79,m2dc86002:85,m2dc86006:82,m2dc86009:123,m2dc86101:85,m2dc86102:85,m2dc86728:95,m2dc89000:96,m2dc89001:79,m2dc89012:78,m2dc89015:124,m2dc89018:78,m2dc89020:125,m2dc89025:126,m2dc89026:127,m2dc8ab12:116,m35371022:63,m35371041:63,m35371046:63,m35371104:63,m358a0102:63,m358a0201:128,m358a0202:128,m358a0203:128,m358a0204:63,w00790002:129,w00790007:129,w0079000a:129,w00790016:18,w00790122:99,w00790126:130,w00791804:131,w0079181a:7,w0079181b:113,w00791824:132,w00791830:133,w00791845:11,w00791847:12,w0079184f:134,w00791879:135,w0079188f:136,w007918ae:137,w007918d4:138,w046dc209:139,w046dc20a:16,w046dc20b:140,w046dc211:141,w046dc21d:138,w046dc21e:142,w046dc242:142,w046dca84:143,w046dca88:143,w046dcad1:5,w046dcad2:7,w04b42410:144,w04b4c681:130,w054c05c5:145,w057e0330:146,w05ac022d:144,w05ac033d:147,w05ac044d:147,w05ac055b:39,w05ac057a:148,w0e6f0003:149,w0e6f0111:7,w0e6f0114:7,w0e6f0119:7,w0e6f011a:7,w0e6f011e:7,w0e6f011f:150,w0e6f0124:42,w0e6f0128:7,w0e6f012f:7,w0e6f0130:7,w0e6f0132:7,w0e6f0146:138,w0e6f0164:151,w0e6f0180:7,w0e6f0181:7,w0e6f0185:44,w0e6f0188:7,w0e6f0189:7,w0e6f0214:7,w0e6f0301:138,w0e6f1113:51,w0e6f6302:7,w0f0d0009:7,w0f0d000a:152,w0f0d000c:153,w0f0d000d:154,w0f0d0010:155,w0f0d0011:57,w0f0d0013:155,w0f0d001b:152,w0f0d0021:155,w0f0d0022:54,w0f0d0025:42,w0f0d0026:155,w0f0d0027:42,w0f0d0032:155,w0f0d003d:156,w0f0d0040:157,w0f0d0042:155,w0f0d0049:7,w0f0d004b:155,w0f0d0051:155,w0f0d0054:7,w0f0d0055:8,w0f0d005b:113,w0f0d005c:7,w0f0d0064:155,w0f0d0067:70,w0f0d006a:8,w0f0d006b:7,w0f0d006f:158,w0f0d0070:57,w0f0d007b:155,w0f0d008a:8,w0f0d008b:7,w0f0d008c:138,w0f0d009c:8,w0f0d00a0:159,w0f0d00a5:160,w0f0d00a6:111,w0f0d00ad:161,w0f0d00ae:142,w0f0d00af:162,w0f0d00c0:138,w0f0d00c9:5,w0f0d00d8:163,w0f0d00dc:138,w0f0d0101:5,w0f0d0104:142,w0f0d0123:144,w0f0d0137:164,w0f0d0162:165,w0f0d0164:166,w0f0d0196:134,w0f0d0202:167,w0f0d1011:168,w153202a6:169,w15320300:170,w15320707:147,w15320a14:138,w15321004:145,w15321007:145,w15321009:145,w1532100a:5,w18d12c40:171,w20d60060:7,w20d60dad:142,w20d6319f:7,w20d64026:134,w20d64033:134,w20d6571d:7,w20d6576d:7,w20d65795:7,w20d657c7:7,w20d657e5:7,w20d689e5:172,w20d6a712:7,w20d6a713:7,w20d6a714:7,w20d6a720:7,w24c6531a:153,w24c65b02:138,w27f80bbf:173,w28de11fc:70,w28de11ff:174,w2dc802e0:175,w2dc81003:176,w2dc81080:176,w2dc82100:144,w2dc82810:177,w2dc82862:78,w2dc83000:78,w2dc83001:178,w2dc8301c:134,w2dc8310a:134,w2dc83820:179,w2dc85001:180,w2dc86000:79,w2dc86003:123,w2dc86012:134,w2dc86100:85,w2dc86103:123,w2dc8ab11:179,w2dc8ab20:178,w2dc8ab21:78,w35371004:138,w35371007:134,w35371094:134,w35371116:134},$a=e=>e.toLowerCase().padStart(4,`0`);function eo(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:$a(t[2]),product:$a(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:$a(n[1]),product:$a(n[2]),name:n[3].trim()}:null}function to(e){return(eo(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function no(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function ro(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Qa[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Za[n]??null}return null}function io(e){return e.mapping!==`standard`&&eo(e.id)?.vendor===`2dc8`}var ao={6003:`switch`,6006:`switch`,6103:`switch`,3010:`switch`,6001:`startx`,6002:`startx`,6101:`startx`,6102:`startx`,3011:`receiver`,3012:`receiver`,3013:`receiver`,3015:`receiver`,3016:`receiver`,3017:`receiver`,"301b":`receiver`,"301c":`receiver`,"301d":`receiver`,6012:`receiver`,5112:`none`,9020:`none`};function oo(e){let t=eo(e);return t&&ao[t.product]||`manual`}var so={1:0,2:2,4:4,8:6};function co(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function lo(e,t,n){let{n:r,hat:i}=co(t),a=Ia.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function uo(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=so[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function fo(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function po(e,t,n){let r=e.split(`,`),i=lo(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&_o(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(_o)}function yo(){try{let e=Lt(go),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>vo(e[1])))}catch{return{}}}function bo(e,t){let n=yo();return t?n[e]=t:delete n[e],It(go,JSON.stringify(n)),xo=n,n}var xo=null;function So(e){return xo??=yo(),xo[e.id]??To(xo,e.id)??ho(e)??Ua(e)}function Co(e){return xo??=yo(),xo[e.id]?`saved`:e.mapping===`standard`?`standard`:ho(e)?`known`:`guess`}function wo(e){return ho(e)??Ua(e)}function To(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(xo=bo(t,e[i]),e[i]):null}function Eo(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Do(e,t){let n=null;if(t.buttons.forEach((t,r)=>{let i=t-(e.buttons[r]??0);t>.5&&i>.5&&(!n||i>n.amount)&&(n={src:{b:r},amount:i})}),n)return n.src;for(let n=0;n1.05?La(t.axes[n]):null;if(r!==null)return{h:n,at:r}}return t.axes.forEach((t,r)=>{let i=e.axes[r]??0,a=t-i;if(!(Math.abs(a)<.6)&&(!n||Math.abs(a)>n.amount)){let e=a>0?1:-1;n={src:Math.abs(i)>.5?{a:r,d:e,rest:i}:{a:r,d:e},amount:Math.abs(a)}}}),n?n.src:null}function Oo(e,t){let n=null;if(t.axes.forEach((t,r)=>{let i=t-(e.axes[r]??0);Math.abs(i)>=.6&&(!n||Math.abs(i)>Math.abs(n.moved))&&(n={a:r,moved:i})}),!n)return null;let r=n;return r.moved>0?{a:r.a}:{a:r.a,inv:!0}}var ko=[{kind:`button`,bit:R.CROSS,name:`✕`},{kind:`button`,bit:R.CIRCLE,name:`○`},{kind:`button`,bit:R.SQUARE,name:`□`},{kind:`button`,bit:R.TRIANGLE,name:`△`},{kind:`button`,bit:R.UP,name:`↑`},{kind:`button`,bit:R.DOWN,name:`↓`},{kind:`button`,bit:R.LEFT,name:`←`},{kind:`button`,bit:R.RIGHT,name:`→`},{kind:`button`,bit:R.L1,name:`L1`},{kind:`button`,bit:R.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:R.L3,name:`L3`},{kind:`button`,bit:R.R3,name:`R3`},{kind:`button`,bit:R.OPTIONS,name:`Options`},{kind:`button`,bit:R.SHARE,name:`Create`},{kind:`button`,bit:R.PS,name:`PS`},{kind:`button`,bit:R.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}];function Ao(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function jo(e,t,n){return t.kind===`button`?{...e,buttons:[...e.buttons.filter(([e])=>e!==t.bit),[t.bit,n]]}:(t.kind,{...e,[t.which]:n})}function Mo(e,t=Va){let n=new Set(e.buttons.map(([e])=>e)),r=e=>`b`in e?`b${e.b}`:`h`in e?`h${e.h}.${e.at}`:`a${e.a}${e.d}`,i=new Set([...e.buttons.map(([,e])=>r(e)),...[e.l2,e.r2].filter(e=>!!e).map(r)]);return{buttons:[...e.buttons,...t.buttons.filter(([e,t])=>!n.has(e)&&!i.has(r(t)))],l2:e.l2??t.l2,r2:e.r2??t.r2,lx:e.lx??t.lx,ly:e.ly??t.ly,rx:e.rx??t.rx,ry:e.ry??t.ry}}var No=ko.filter(e=>e.kind!==`button`||![R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD].includes(e.bit));function Po(e,t){return t.buttons.every((t,n)=>Math.abs(t-(e.buttons[n]??0))<.3)&&t.axes.every((t,n)=>Math.abs(t-(e.axes[n]??0))<.3)}var Fo=class{constructor(e=ko){this.steps=e,this.step=0,this.prof=Ao(),this.rest=null,this.waiting=!0}get done(){return this.step>=this.steps.length}get current(){return this.steps[this.step]??null}feed(e){if(this.done)return!1;if(!this.rest)return this.rest=e,this.waiting=!1,!1;if(this.waiting)return Po(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Oo(this.rest,e):Do(this.rest,e);return n?(this.prof=jo(this.prof,t,n),this.go(this.step+1),!0):!1}skip(){this.go(this.step+1)}back(){this.step>0&&this.go(this.step-1)}go(e){this.waiting=!0,this.step=Math.min(e,this.steps.length)}profile(e=Va){return Mo(this.prof,e)}};function Io(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}function Lo(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Ro=e=>`ps5upload.join.token.${e??`app`}`,zo=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...ja},this.lastSent=0,this.neutral=!1,this.stopped=!1,this.attempt=0,this.deadline=0,this.raf=0,this.keepalive=null,this.pinger=null,this.retry=null,this.lastHeard=0,this.hostAway=!1,this.pings=0,this.now=e.now??(()=>Date.now()),this.storage=e.storage===void 0?Lo():e.storage,this.WS=e.WebSocketImpl??WebSocket,this.seq=this.now()>>>0;try{this.token=this.storage?.getItem(this.key)??null}catch{this.token=null}}get key(){return Ro(this.o.invite??this.o.code??null)}get current(){return this.stage}get socket(){return this.ws}get resumeToken(){return this.token}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.stopped=!1,this.setStage({kind:`connecting`}),this.connect(),this.stopped)return;let e=()=>{this.sendPad(!1),this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e)};this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e),this.keepalive=setInterval(()=>this.sendPad(!1),100),this.pinger=setInterval(()=>this.ping(),1e3)}connect(){let e;try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,e.onopen=()=>{if(this.ws!==e)return;this.lastHeard=this.now();let t={name:this.o.name};this.o.invite&&(t.invite=this.o.invite),this.o.code&&(t.code=this.o.code),this.token&&(t.resume=this.token),e.send(JSON.stringify({hello:t}))},e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),typeof t.data==`string`?this.onText(t.data):t.data instanceof ArrayBuffer&&this.stage.kind===`joined`&&this.o.onFrame?.(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Ue(t);n===`mismatch`?(this.forgetToken(),this.finish({kind:`ended`,why:n})):n&&this.stage.kind!==`joined`&&this.stage.kind!==`reconnecting`?this.finish({kind:`ended`,why:n}):this.dropped()},e.onerror=()=>{}}onText(e){let t=Je(e);if(t)switch(t.kind){case`pong`:{let e=this.now()-t.t;e>=0&&e<6e4&&this.o.onRtt?.(e);return}case`asking`:this.stage.kind!==`reconnecting`&&this.setStage({kind:`asking`});return;case`waiting`:this.hostAway||(this.hostAway=!0,this.deadline=this.now()+et),this.attempt=0,this.setStage(this.reconnectingStage());return;case`joined`:this.token=t.token,this.player=t.player,this.attempt=0,this.hostAway=!1;try{this.storage?.setItem(this.key,t.token)}catch{}{let e=t.track&&this.ws?.media||null;this.o.onCodec?.(t.hevc,e,!!e&&t.audio&&!!e.audio)}this.setStage({kind:`joined`,player:t.player,hevc:t.hevc}),this.sendPad(!0);return;case`refused`:this.forgetToken(),this.hostAway&&t.why!==`seat_taken`?this.finish({kind:`ended`,why:`host_stopped`}):this.finish({kind:`refused`,why:t.why});return;case`bye`:if(t.why===`host_stopped`&&this.token){this.hostWait();return}this.forgetToken(),this.finish({kind:`ended`,why:t.why});return;case`status`:this.stage.kind===`joined`&&t.status.player>0&&t.status.player!==this.stage.player&&(this.player=t.status.player,this.setStage({...this.stage,player:t.status.player})),this.o.onStatus?.(t.status);return;case`feedback`:t.rumble&&this.o.onRumble?.(t.rumble[0],t.rumble[1]),t.light&&this.o.onLight?.(t.light);return}}hostWait(){this.hostAway=!0,this.deadline=this.now()+et,this.attempt=0;let e=this.ws;this.ws=null;try{e?.close()}catch{}this.scheduleRetry()}reconnectingStage(){return{kind:`reconnecting`,player:this.player,attempt:this.attempt,deadline:this.deadline,...this.hostAway?{hostStopped:!0}:{}}}giveUp(){this.forgetToken(),this.finish({kind:`ended`,why:this.hostAway?`host_stopped`:`gave_up`})}dropped(){if(this.stopped)return;let e=this.stage;e.kind===`joined`||e.kind===`reconnecting`&&this.token?(e.kind===`joined`&&(this.deadline=this.now()+$e),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Qe(this.attempt);this.setStage(this.reconnectingStage()),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.stopped||(this.now()>=this.deadline?this.giveUp():this.connect())},e)}forgetToken(){this.token=null;try{this.storage?.removeItem(this.key)}catch{}}ping(){if(this.hostAway&&!this.stopped&&this.now()>=this.deadline+5e3||!this.stopped&&this.stage.kind===`reconnecting`&&this.now()>=this.deadline+5e3){this.giveUp();return}let e=this.ws;if(e&&e.readyState===this.WS.OPEN){if(this.stage.kind===`joined`&&this.now()-this.lastHeard>3500){this.ws=null;try{e.close()}catch{}this.dropped()}else if(e.send(JSON.stringify({ping:this.now()})),this.stage.kind===`joined`&&this.o.readStats&&++this.pings%2==0){let t=this.o.readStats();t&&e.send(JSON.stringify({stats:t}))}}}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.sendPad(!0))}sendPad(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||this.stage.kind!==`joined`)return;let n=this.neutral?{...ja,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Io(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Ze(this.seq,n)))}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.pinger&&clearInterval(this.pinger),this.retry&&clearTimeout(this.retry),this.keepalive=this.pinger=this.retry=null}finish(e){this.stopped=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&e.send(JSON.stringify({keyframe:!0}))}leave(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&(this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),e.send(JSON.stringify({leave:1}))),this.forgetToken(),this.finish({kind:`ended`,why:`left`})}stop(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},Bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),z=s(((e,t)=>{t.exports=Bo()}))(),Vo=`ps5upload.openIn`,Ho=`ps5upload.openIn.tab`;function Uo(){try{return sessionStorage.getItem(Ho)===`browser`}catch{return!1}}function B(){try{sessionStorage.setItem(Ho,`browser`)}catch{}}function V(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Wo({appLink:e,children:t}){let n=Ie(),[r,i]=(0,D.useState)(()=>Uo()?`browser`:V(Lt(Vo))),[a,o]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,z.jsx)(z.Fragment,{children:t});let s=()=>{a&&It(Vo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?It(Vo,`browser`):r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&Rt(Vo),B(),i(`browser`)};return(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,z.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,z.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}var Go=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type='hidden'])`,`select:not([disabled])`,`textarea:not([disabled])`,`summary`,`[contenteditable='true']`,`[tabindex]`].map(e=>`${e}:not([tabindex='-1'])`).join(`, `),Ko=new Set,qo=[];function Jo(){for(let e of Ko)e()}function Yo(){return qo.length}function Xo(e){return qo.push(e),Jo(),()=>{let t=qo.lastIndexOf(e);t!==-1&&qo.splice(t,1),Jo()}}function Zo(e,t,n){switch(n){case`down`:return t.top-e.bottom;case`up`:return e.top-t.bottom;case`right`:return t.left-e.right;case`left`:return e.left-t.right}}function H(e,t,n){let r=(e.left+e.right)/2,i=(e.top+e.bottom)/2,a=(t.left+t.right)/2,o=(t.top+t.bottom)/2;switch(n){case`down`:return o>i&&t.top>=e.top+1;case`up`:return or&&t.left>=e.left+1;case`left`:return a0?{gap:0,overlap:c}:{gap:-c,overlap:0}}function $o(e,t,n){let r=null,i=1/0,a=!1;for(let o of t){if(!H(e,o.rect,n))continue;let t=Math.max(0,Zo(e,o.rect,n)),s=Qo(e,o.rect,n),c=s.overlap>0;if(a&&!c)continue;let l=c?t-s.overlap/1e6:Math.hypot(t,2*s.gap);(c&&!a||l`u`?void 0:window){try{return!!e?.PS5UploadTv?.isTv()}catch{return!1}}function rs(e=typeof document>`u`?void 0:document){return e?.documentElement.dataset.tv===`1`}function is(e,t){if(!e)return!1;if(e.closest(`[data-own-arrows]`))return!0;let n=e.tagName;if(n===`TEXTAREA`||e.isContentEditable)return!0;let r=t===`left`||t===`right`;if(n===`INPUT`){let t=(e.type||`text`).toLowerCase();if(t===`range`||ts.test(t))return r}return!1}var as=`[aria-modal="true"], [role="dialog"], [role="alertdialog"]`;function os(e){let t=e.activeElement?.closest(as);if(t)return t;if(Yo()>0){let t=e.querySelectorAll(as);if(t.length)return t[t.length-1]}return e}function ss(e){let t=[];return e.querySelectorAll(Go).forEach(e=>{if(e.closest(`[inert], [aria-hidden='true']`)||e.disabled)return;let n=e.getBoundingClientRect();n.width<=0||n.height<=0||t.push({el:e,rect:n})}),t}function cs(e){return(e.find(e=>e.el.getAttribute(`aria-current`)===`page`)??e[0])?.el??null}function ls(e,t=document){let n=es[e.key];if(!n||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return!1;let r=t.activeElement;if(is(r,n))return!1;let i=ss(os(t));if(!i.length)return!1;let a=i.find(e=>e.el===r),o=a?$o(a.rect,i.filter(e=>e!==a),n):cs(i);return o?(e.preventDefault(),o.focus(),typeof o.scrollIntoView==`function`&&o.scrollIntoView({block:`nearest`,inline:`nearest`}),!0):!1}var us=!1;function ds(e){us||(us=!0,e.addEventListener(`keydown`,t=>void ls(t,e.document)))}function fs(e=typeof window>`u`?void 0:window){e&&(ns(e)&&(e.document.documentElement.dataset.tv=`1`),ds(e))}function ps({id:e,className:t}){let n=Ie(),r=oo(e);if(r===`none`)return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_no_xinput`,void 0,`This 8BitDo has no X-input mode. If a button is wrong, check the controller.`)});let i=r===`switch`?n(`pad_8bitdo_how_switch`,void 0,`set the switch on the back to X, then press Start`):r===`startx`?n(`pad_8bitdo_how_startx`,void 0,`turn it off, then hold Start + X to turn it on`):r===`receiver`?n(`pad_8bitdo_how_receiver`,void 0,`use its 2.4G receiver or a USB cable`):n(`pad_8bitdo_how_manual`,void 0,`its manual says how`);return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_xinput`,{how:i},`For the best result, switch your 8BitDo to X-input mode: ${i}.`)})}var ms=new Set,hs={held:new Set,touch:null,touchPad:ja,mapping:!1,get paused(){return ms.size>0},motion:null},gs={s:.85,m:1,l:1.15},_s=.25;function vs(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(_s,e))}var ys={overlay:{width:844,height:390},deck:{width:390,height:480}},bs=.7,xs=1.4;function Ss(e,t,n,r){let i=gs[e]??1;if(!(t>0)||!(n>0))return i;let a=r?ys.deck:ys.overlay,o=Math.min(xs,Math.max(bs,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var Cs=34;function ws(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+Cs>t}function Ts(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var Es=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,Ds=32767,Os=12;function ks({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Ie(),s=(0,D.useRef)(new Map),c=(0,D.useRef)({...ja}),[l,u]=(0,D.useState)({...ja}),[d,f]=(0,D.useState)({l:!1,r:!1,touchpad:!1}),p=(0,D.useRef)(null),[m,h]=(0,D.useState)({width:0,height:0});(0,D.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,D.useEffect)(()=>()=>{hs.touchPad={...ja}},[]);let g=()=>{let t={...ja,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=R.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,hs.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*Ds),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*Ds)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ma((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ma((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Os&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,C=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,w=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,T={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},E=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),te=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ne={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},re=(e,t,n,r)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${te} ${n}`,style:ne,children:r}),ie=(e,t,n,r)=>(0,z.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${w} ${C(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),ae=(e,t,n,r)=>re(e,t,`h-[44px] w-[84px]`,ie(e,ee(t),n,r)),oe=(e,t,n)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${te} h-[44px] w-[84px]`,style:ne,children:ie(e,l[t]>0,n,!0)}),se=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:(0,z.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...E(ee(t)),children:[(0,z.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,z.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ce=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:[(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...E(ee(t))}),(0,z.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),le=(e,t)=>re(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,z.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${w} ${C(ee(t))}`,children:e})),ue=(e,t)=>re(e,t,`h-[44px] w-[44px]`,(0,z.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),de=e=>{let{dx:t,dy:n}=Ts(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,z.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,z.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${C(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},O=t===`deck`,fe=Ss(r,m.width,m.height,O),pe=e=>`${e}px * var(--k)`,k=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=O?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${pe(t)}, ${n}px))`:`calc(${e} + ${pe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=O&&ws(fe,m.height),A=O?void 0:`58%`,j=e=>O?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?k:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?k:me},xe=e=>({bottom:be?he:_e(he,O?56:0,44),[e]:be?`calc(${e===`left`?k:me} + 8px + max(${pe(80)}, 44px))`:_e(e===`left`?k:me,O?40:168)}),Se=!!a&&!O;return(0,z.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${O?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:O?i:void 0,"--k":fe},"data-testid":`rp-touch`,"data-layout":t,"data-scale":fe,onContextMenu:e=>e.preventDefault(),children:[(0,z.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:vs(n)},children:[(0,z.jsx)(`div`,{style:ye(`top left`,{top:ge,left:k}),children:(0,z.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:O?void 0:`6deg`,transformOrigin:`top left`},children:[oe(`L2`,`l2`,`l`),ae(`L1`,R.L1,`l`,!1)]})}),(0,z.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,z.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:O?void 0:`-6deg`,transformOrigin:`top right`},children:[oe(`R2`,`r2`,`r`),ae(`R1`,R.R1,`r`,!1)]})}),(0,z.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:O?{top:_e(ge,6),left:_e(k,104),right:_e(me,104),height:`max(44px, calc(${pe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${pe(250)}), 34vw)`,height:`max(44px, calc(${pe(56)}))`}}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top left`:`left center`,j(`left`)),children:[(0,z.jsx)(`span`,{}),se(`↑`,R.UP,0),(0,z.jsx)(`span`,{}),se(`←`,R.LEFT,-90),(0,z.jsx)(`span`,{}),se(`→`,R.RIGHT,90),(0,z.jsx)(`span`,{}),se(`↓`,R.DOWN,180),(0,z.jsx)(`span`,{})]}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top right`:`right center`,j(`right`)),children:[(0,z.jsx)(`span`,{}),ce(`△`,R.TRIANGLE,(0,z.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,z.jsx)(`span`,{}),ce(`□`,R.SQUARE,(0,z.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,z.jsx)(`span`,{}),ce(`○`,R.CIRCLE,(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,z.jsx)(`span`,{}),ce(`✕`,R.CROSS,(0,z.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:de(`l`)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:de(`r`)}),(0,z.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:k}),children:le(`Create`,R.SHARE)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:le(`Options`,R.OPTIONS)}),(0,z.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:Es,translate:`-50% 0`}),children:ue(`PS`,R.PS)})]}),Se&&(0,z.jsx)(`div`,{style:{...ye(`bottom center`,{bottom:he,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,vs(n))},children:(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${te} h-[44px] w-[56px]`,style:ne,"data-testid":`rp-menu-handle`,children:(0,z.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,z.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var As=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,js=null,Ms=null;function Ns(e){e.play().catch(()=>{if(Ms||js!==e)return;let t=()=>{Ps(),js===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),Ms=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Ps(){Ms?.(),Ms=null}function Fs(){if(typeof document<`u`){if(!js){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=As,document.body.appendChild(e),js=e}Ns(js)}}function Is(){Ps(),js&&=(js.pause(),js.removeAttribute(`src`),js.remove(),null)}function Ls(){return typeof navigator>`u`?null:navigator.wakeLock??null}function Rs(){return dt()||!Pn()}var zs=new Set,Bs=null,Vs=Promise.resolve(),Hs=!1;async function Us(){if(zs.size===0||Bs&&!Bs.released)return;let e=Ls();if(!e)dt()&&Fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{Bs===t&&(Bs=null)}),Bs=t}catch{}}async function Ws(){Is();let e=Bs;if(Bs=null,e&&!e.released)try{await e.release()}catch{}}function Gs(){Hs||typeof document>`u`||(Hs=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&zs.size>0&&(Vs=Vs.then(Us))}))}function Ks(e,t){if(!Rs())return;Gs();let n=zs.size>0;t?zs.add(e):zs.delete(e);let r=zs.size>0;n!==r&&(Vs=Vs.then(r?Us:Ws))}var qs=new Set;function Js(){if(typeof window<`u`)return window.PS5UploadPad}function Ys(e,t){let n=qs.size>0;t?qs.add(e):qs.delete(e);let r=qs.size>0;if(n!==r)try{Js()?.setActive(r)}catch{}}var Xs=class e{constructor(e){this.receiver=e,this.last=null,this.was={}}get frames(){return Number(this.last?.frames??0)}static report(e,t){let n=t=>e[t]??0,r=e=>n(e)-(t[e]??0),i=(e,t)=>r(t)>0?Math.round(r(e)/r(t)*1e4)/10:0;return{frames:n(`framesDecoded`),dropped:n(`framesDropped`),stalls:n(`freezeCount`),stall_ms:Math.round(n(`totalFreezesDuration`)*1e3),decode_ms:i(`totalDecodeTime`,`framesDecoded`),jitter_ms:i(`jitterBufferDelay`,`jitterBufferEmittedCount`),nacks:n(`nackCount`),plis:n(`pliCount`),decoder:`track`}}snapshot(){return this.receiver.getStats().then(t=>{t.forEach(t=>{t.type===`inbound-rtp`&&t.kind===`video`&&(this.last=e.report(t,this.was),this.was={...t})})}).catch(()=>{}),this.last}},Zs=class{constructor(e){this.inner=e,this.video=document.createElement(`video`),this.wrap=document.createElement(`div`),this.media=null,this.trackStats=null,this.audio=!1,this.soundOn=!1,this.muted=!1;let t=this.video;t.muted=t.autoplay=t.playsInline=!0,t.className=`block h-full w-full object-contain`,t.dataset.testid=`track-video`,this.wrap.className=`h-full w-full`,this.wrap.append(t,e.element),this.setTrack(null)}get element(){return this.wrap}get stats(){return this.trackStats??this.inner.stats}setTrack(e,t=!1){this.media=e,this.audio=!!e&&t,this.applySound(),this.trackStats=e?new Xs(e.receiver):null,this.video.style.display=e?``:`none`,this.inner.element.style.display=e?`none`:``,this.video.srcObject!==(e?.stream??null)&&(this.video.srcObject=e?.stream??null),e&&this.play()}play(){try{this.video.play()?.catch?.(()=>{})}catch{}}onMessage(e){let t=new Uint8Array(e)[0];this.media&&t<=1||(!this.audio||t!==3&&t!==4)&&this.inner.onMessage(e)}applySound(){this.video.muted=!(this.audio&&this.soundOn&&!this.muted)}setHevc(e){this.inner.setHevc(e)}set onSoundFail(e){this.inner.onSoundFail=e}soundReport(){return this.inner.soundReport()}startSound(){this.inner.startSound(),this.soundOn=!0,this.applySound(),this.media&&this.play()}setMuted(e){this.inner.setMuted(e),this.muted=e,this.applySound()}resumeSound(){this.inner.resumeSound(),this.media&&this.video.paused&&this.play()}stop(){this.inner.stop(),this.video.srcObject=null}},Qs=`ps5upload.join.muted`,$s=5e3,ec=Object.fromEntries(Object.entries(Na).filter(([e])=>e!==`Escape`)),tc=new Set;function nc(e){if(!(e.code in ec)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||rc(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||rc(t))}function rc(e){let t=e?.tagName;if(t===`BUTTON`||t===`A`)return!0;let n=e?.getAttribute?.(`role`);return n===`button`||n===`link`||n===`menuitem`||n===`tab`||n===`switch`}var ic=!1;function ac(e){ic=e}function oc(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function sc(){if(ic)return{...ja};let e=Ga(Xa(typeof navigator>`u`?void 0:navigator),So),t=hs.touchPad;return{...Ka(Ka(e,Fa(tc,ec)),t),touch:t.touch??null,motion:hs.motion??null}}var cc=class{constructor(e){this.opts=e,this.player=null,this.listeners=new Set,this.cleanups=[],this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.snap={stage:{kind:`connecting`},status:null,rttMs:null,light:null,problem:null,sound:!1,noSound:!1,host:e.host,muted:uc(),path:null},this.client=new zo({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:sc,onStage:e=>{this.set({stage:e}),e.kind===`joined`&&this.readPath(),(e.kind===`refused`||e.kind===`ended`)&&this.teardown()},onStatus:e=>this.set({status:e,host:e.host??this.snap.host}),onRtt:e=>this.set({rttMs:e}),onFrame:e=>this.picture().onMessage(e),readStats:()=>oc(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Zs&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Xa(typeof navigator>`u`?void 0:navigator);qa(n,e,t),n.some(e=>e?.connected)||navigator.vibrate?.(e||t?200:0)},onLight:e=>this.set({light:e})})}picture(){if(!this.player){let e=oa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Zs(e):e,this.player.onSoundFail=()=>this.set({noSound:!0}),this.player.setMuted(this.snap.muted)}return this.player}async readPath(){let e=this.client.socket,t=this.opts.path??null;if(e?.netPath)try{t=await e.netPath()??this.opts.path??null}catch{t=null}t!==this.snap.path&&this.set({path:t})}get element(){return this.picture().element}start(){let e=()=>{document.visibilityState===`hidden`?tc.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{tc.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&nc(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),tc.add(e.code))},r=e=>{tc.delete(e.code)&&nc(e)&&e.preventDefault()};window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r);let i=()=>{this.client.setNeutral(document.visibilityState===`hidden`),document.visibilityState!==`hidden`&&this.player?.resumeSound()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`blur`,t),window.addEventListener(`focus`,i);let a=setInterval(()=>{this.client.current.kind===`joined`&&this.readPath()},$s);this.cleanups.push(()=>{clearInterval(a),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`blur`,t),window.removeEventListener(`focus`,i),window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),tc.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(Qs,e?`1`:`0`)}catch{}this.set({muted:e})}startSound(){this.snap.sound||(this.picture().startSound(),this.set({sound:!0}))}leave(){this.client.leave(),this.teardown()}stop(){this.client.stop(),this.teardown()}teardown(){for(let e of this.cleanups.splice(0))e();hs.touchPad={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};let e=this.player;this.player=null,e&&(e.stop(),e.element.remove())}sendPad(){this.client.sendPad(!1)}get snapshot(){return this.snap}set(e){this.snap={...this.snap,...e};for(let e of this.listeners)e()}};function lc(e){return(0,D.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function uc(){try{return typeof localStorage<`u`&&localStorage.getItem(Qs)===`1`}catch{return!1}}function dc(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Ks(`play-together`,n),Ys(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Ks(`play-together`,!1),Ys(`play-together`,!1)}}var fc=3e3,pc=class{constructor(e,t=fc){this.onChange=e,this.delay=t,this.enabled=!1,this.pinned=!1,this.sticky=!1,this.shown=!0,this.timer=null}get visible(){return!this.enabled||this.pinned||this.shown}set(e,t,n=!1){let r=this.enabled&&!this.pinned,i=this.enabled,a=this.sticky;this.enabled=e,this.pinned=t,this.sticky=n,!e||t?(this.stop(),this.show(!0)):n?(this.stop(),!i||!a?this.show(!1):r||this.show(!0)):(!r||a)&&(this.show(!0),this.arm())}poke(){this.show(!0),this.enabled&&!this.pinned&&!this.sticky&&this.arm()}toggle(){this.visible?this.hide():this.poke()}hide(){this.enabled&&!this.pinned&&(this.stop(),this.show(!1))}dispose(){this.stop()}arm(){this.stop(),this.timer=setTimeout(()=>{this.timer=null,this.show(!1)},this.delay)}stop(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}show(e){this.shown!==e&&(this.shown=e,this.onChange(e))}};function mc(e,t,n=!1){let[r,i]=(0,D.useState)(!0),a=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=new pc(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,D.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,D.useCallback)(()=>a.current?.poke(),[]),s=(0,D.useCallback)(()=>a.current?.hide(),[]),c=(0,D.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var hc=3e4,gc=class{constructor(e,t=hc){this.onChange=e,this.ms=t,this.picking=!1,this.over=!1,this.timer=null}get shown(){return this.picking&&!this.over}set(e){e!==this.picking&&(this.picking=e,this.over=!1,this.stop(),e&&(this.timer=setTimeout(()=>{this.timer=null,this.over=!0,this.onChange()},this.ms)))}stop(){this.timer&&clearTimeout(this.timer),this.timer=null}reset(){this.stop(),this.picking=!1,this.over=!1}};function _c(e){let[,t]=(0,D.useState)(0),[n]=(0,D.useState)(()=>new gc(()=>t(e=>e+1)));return(0,D.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,D.useEffect)(()=>()=>n.reset(),[n]),n.shown}var vc=()=>Xa(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function yc(e,t){if(t.kind===`axis`)return t.which===`lx`?e(`rp_pad_step_lx`,void 0,`Push the left stick right`):t.which===`ly`?e(`rp_pad_step_ly`,void 0,`Push the left stick down`):t.which===`rx`?e(`rp_pad_step_rx`,void 0,`Push the right stick right`):e(`rp_pad_step_ry`,void 0,`Push the right stick down`);if(t.kind===`button`){if(t.bit===R.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===R.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===R.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===R.TRIANGLE)return e(`join_check_top`,void 0,`Press the top face button (△)`)}return e(`rp_pad_press`,{name:t.name},`Press ${t.name}`)}function bc(e,t){let n=(0,D.useRef)(t);(0,D.useEffect)(()=>{n.current=t}),(0,D.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(vc().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var xc=[[R.CROSS,`✕`],[R.CIRCLE,`○`],[R.SQUARE,`□`],[R.TRIANGLE,`△`],[R.UP,`↑`],[R.DOWN,`↓`],[R.LEFT,`←`],[R.RIGHT,`→`],[R.L1,`L1`],[R.R1,`R1`],[R.L3,`L3`],[R.R3,`R3`],[R.SHARE,`Create`],[R.OPTIONS,`Options`],[R.PS,`PS`],[R.TOUCHPAD,`Touchpad`]];function Sc({pad:e}){let t=e=>`flex h-8 min-w-8 items-center justify-center rounded-md px-1.5 text-xs font-medium ${e?`bg-white text-black`:`bg-white/10 text-white/70`}`,n=(e,t,n)=>(0,z.jsxs)(`span`,{className:`relative flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-[10px] text-white/50`,children:[n,(0,z.jsx)(`span`,{className:`absolute h-3 w-3 rounded-full bg-white`,style:{left:`calc(50% + ${e/32767*18}px - 6px)`,top:`calc(50% + ${t/32767*18}px - 6px)`}})]});return(0,z.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[xc.map(([n,r])=>(0,z.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,z.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,z.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,z.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function Cc({onClose:e}){let t=Ie(),[n,r]=(0,D.useState)(()=>vc().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,D.useState)(()=>vc()[0]?.index??null),[o,s]=(0,D.useState)(ja),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(yo),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useRef)(null);(0,D.useEffect)(()=>(ac(!0),()=>ac(!1)),[]),(0,D.useEffect)(()=>{(v.current?.querySelector(`[data-testid="join-pad-learn-start"]`)??v.current?.querySelector(`[data-testid="join-pad-check-close"]`))?.focus({preventScroll:!0})},[]),(0,D.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||v.current?.querySelector(`button:not([disabled])`)?.focus({preventScroll:!0})},[c,u]),(0,D.useEffect)(()=>{let e=()=>{let e=vc();r(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n].id&&t.index===e[n].index)?t:e.map(e=>({index:e.index,id:e.id}))),a(t=>t!==null&&e.some(e=>e.index===t)?t:e[0]?.index??null)},t=window.setInterval(e,500);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(t),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),bc(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(Eo(e))&&y(c,e);return}let t=Ga([e],So);s(e=>e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry?e:t)});let y=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(bo(r,e.profile(n?wo(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},b=()=>{h(null),d(0),l(new Fo(No))},x=g,S=x?Co(x):null,ee=!!(x&&f[x.id]);return(0,z.jsx)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":t(`join_check_title`,void 0,`Check your controller`),className:`absolute inset-0 z-40 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm`,"data-testid":`join-pad-check`,onPointerDown:e=>e.stopPropagation(),children:(0,z.jsxs)(`div`,{className:`w-[min(26rem,100%)] space-y-3 rounded-2xl border border-white/10 bg-neutral-900/95 p-4 text-sm text-white shadow-2xl`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(me,{size:16,className:`text-white/70`}),(0,z.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t(`join_done`,void 0,`Done`),className:`flex h-8 w-8 items-center justify-center rounded-full bg-white/10 hover:bg-white/20`,"data-testid":`join-pad-check-close`,children:(0,z.jsx)(De,{size:15})})]}),x?(0,z.jsxs)(z.Fragment,{children:[n.length>1&&(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,z.jsx)(`button`,{type:`button`,disabled:!!c,onClick:()=>a(e.index),className:`rounded-full px-2.5 py-1 text-xs ${e.index===i?`bg-white text-black`:`bg-white/10`}`,children:to(e.id)},`${e.index}-${e.id}`))}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:to(x.id)}),(0,z.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":S??``,children:S===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):S===`guess`?t(`join_check_unknown`,void 0,`This controller isn't on our list, so its buttons may be mixed up. Setting it up takes a few seconds.`):t(`rp_pad_standard`,void 0,`Recognized`)}),io(x)&&(0,z.jsx)(ps,{id:x.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`rp_pad_progress`,{n:u+1,total:c.steps.length},`${u+1} of ${c.steps.length}`)}),(0,z.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?yc(t,c.current):``}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),y(c,x)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-learn-skip`,children:t(`rp_pad_skip`,void 0,`Skip`)}),u>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.back(),d(c.step)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,children:t(`rp_pad_back`,void 0,`Back`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>l(null),className:`rounded-full px-3 py-1.5 text-xs text-white/70 hover:bg-white/10`,children:t(`rp_pad_cancel`,void 0,`Cancel`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`join_check_try`,void 0,`Press buttons and move the sticks: what you press lights up.`)}),(0,z.jsx)(Sc,{pad:o}),m&&(0,z.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:b,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:ee?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),ee&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{p(bo(x.id,null)),h(null)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-reset`,children:t(`rp_pad_reset`,void 0,`Reset`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-check-done`,children:t(`join_done`,void 0,`Done`)})]})]})]}):(0,z.jsx)(`p`,{className:`text-white/70`,children:t(`rp_pads_none`,void 0,`No controller seen yet. Connect one and press any button on it.`)})]})})}function wc(e,t){let[n,r]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(!e||!t)return;let n=!0;return Be(e,Le).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function Tc({href:e}){let t=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,z.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function Ec(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var Dc=`ps5upload.join.guided`,Oc=1;function kc(e){return e.player!==Oc&&(!e.guided||e.movedOff)&&!e.reconnecting}function Ac(e,t){switch(t){case`lan`:return e(`join_path_lan`,void 0,`Home network`);case`tailscale`:return e(`join_path_tailscale`,void 0,`Tailscale`);default:return e(`join_path_internet`,void 0,`Internet`)}}function jc(e,t){return e(`join_seat_taken`,{host:t},`${t} needed their controller back and no other controller was free on the PS5, so you're out of the game. Ask ${t} to let you in again.`)}function Mc(e,t,n,r=!1){if(t.kind===`refused`)switch(t.why){case`key`:return e(`join_refused_key`,{host:n},`This invite has expired. Ask ${n} for a new link.`);case`expired`:return e(`join_refused_expired`,{host:n},`Your place in the game was lost. Ask ${n} to let you in again.`);case`full`:return e(`join_refused_full`,void 0,`The game is full: four players already.`);case`denied`:return e(`join_refused_denied`,{host:n},`${n} didn't let you in this time.`);case`no_answer`:return e(`join_refused_no_answer`,{host:n},`${n} didn't answer in time. Tell ${n}, then try again.`);case`closed`:return e(`join_refused_closed`,{host:n},`${n} isn't hosting Play Together right now.`);case`old_helper`:return e(`join_refused_old_helper`,{host:n},`${n}'s PS5 needs an updated helper for Play Together.`);case`not_playing`:return e(`join_refused_not_playing`,{host:n},`${n} isn't playing right now. Ask ${n} to start Play first.`);case`unreachable`:return e(`join_refused_unreachable`,{host:n},`${n}'s computer couldn't reach their PS5. Try again in a moment.`);case`slow_down`:return e(`join_refused_slow_down`,void 0,`Too many wrong codes. Wait a minute, then try again.`);case`address`:return e(`join_refused_address`,{host:n},`This link's address is outside your home network, so the app will not use it. Ask ${n} for a link with their computer's IP address.`);case`seat_taken`:return jc(e,n);default:return e(`join_refused_other`,{host:n},`${n} didn't let you in.`)}if(t.kind===`ended`)switch(t.why){case`kicked`:return e(`join_ended_kicked`,{host:n},`${n} took you out of the game.`);case`closed`:return e(`join_ended_closed`,{host:n},`${n} closed Play Together.`);case`host_stopped`:return e(`join_ended_host_stopped`,void 0,`The host stopped playing.`);case`replaced`:return e(`join_ended_replaced`,void 0,`This game was opened in another tab or on another device, so it stopped here.`);case`pad_lost`:return e(`join_ended_pad_lost`,{host:n},`The PS5 lost your controller, so you're out of the game. Ask ${n} to let you in again.`);case`gave_up`:return e(`join_ended_gave_up`,{host:n},`The connection to ${n} didn't come back in time.`);case`lost`:return r?e(`join_net_lost`,{host:n},`The connection to ${n} dropped. Check your internet connection, then ask again.`):e(`join_ended_lost`,{host:n},`Couldn't reach ${n}. Check that you're on the same network.`);case`left`:return e(`join_ended_left`,void 0,`You left the game.`);case`seat_taken`:return jc(e,n);case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`join_net_no_room`,{host:n},`This invite isn't open any more. Ask ${n} for a new link.`);case`net_full`:return e(`join_net_full`,{host:n},`${n}'s game has no room for another friend right now. Try again in a moment.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:return e(`join_net_offer`,{host:n},`${n}'s computer couldn't connect to this browser. Try another browser.`);case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`)}return``}function Nc(e){let[t,n]=(0,D.useState)(()=>Date.now());return(0,D.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function Pc(){let[e,t]=(0,D.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,D.useEffect)(()=>{let e=()=>{let e=Xa(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?sc():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?Co(e):null,s=!!e&&io(e);t(e=>e.ready===n&&e.pressed===i&&e.id===a&&e.kind===o&&e.weak8BitDo===s?e:{ready:n,pressed:i,id:a,kind:o,weak8BitDo:s})};e();let n=window.setInterval(e,120);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(n),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),e}function Fc(e){return!!e?.closest?.(`[data-testid="rp-touch"]`)}var Ic=14,Lc=()=>typeof window<`u`&&!rs()&&!!window.matchMedia?.(`(pointer: coarse)`).matches;function Rc(e,t,n){return!e||e===t||e.closest?.(`[data-join-game]`)?`game`:n?.contains(e)?`controls`:`page`}function zc(e){return e.checking?`close-check`:e.guide?`close-guide`:e.where===`game`?`show-controls`:e.full?`leave-full`:null}var Bc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function Vc({text:e,body:t,onCancel:n}){let r=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,z.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,z.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,z.jsx)(Se,{size:26})})]}),(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!0,className:`rounded-full bg-white/15 px-4 py-2 text-sm hover:bg-white/25`,"data-testid":`join-cancel`,children:r(`join_cancel`,void 0,`Cancel`)})]})}function Hc({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Ie(),c=lc(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,D.useRef)(null),p=(0,D.useRef)(null),m=(0,D.useRef)(null),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(()=>Lt(Dc)===`1`),[y,b]=(0,D.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),x=Pc(),[S,ee]=(0,D.useState)(!1),C=l.kind===`reconnecting`,w=Nc(C),T=l.kind===`joined`||C,E=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[ne,re]=(0,D.useState)(!1),ie=(0,D.useRef)(te);(0,D.useEffect)(()=>{ie.current===Oc&&te>Oc&&re(!0),te&&(ie.current=te)},[te]);let[ae,oe]=(0,D.useState)(!1),[se,ce]=(0,D.useState)(!1),le=T&&(h||!t),de=Lc(),fe=_c(E),k=mc(le,C||fe&&!de||ae||se,de),{poke:he}=k,_e=(0,D.useRef)(null),ve=()=>{_e.current&&clearTimeout(_e.current.timer),_e.current=null};(0,D.useEffect)(()=>ve,[]);let[ye,A]=(0,D.useState)(!1),xe=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(!le||!de||k.shown||!_||xe.current)return;xe.current=!0,A(!0);let e=setTimeout(()=>A(!1),6e3);return()=>clearTimeout(e)},[le,de,k.shown,_]),(0,D.useEffect)(()=>{if(!T)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[T,e]),(0,D.useEffect)(()=>{if(!T||c.sound)return;let t=()=>e.startSound(),n=[`pointerup`,`touchend`,`click`,`keydown`];for(let e of n)window.addEventListener(e,t,!0);return()=>{for(let e of n)window.removeEventListener(e,t,!0)}},[T,c.sound,e]),(0,D.useEffect)(()=>{let e=()=>b(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,D.useEffect)(()=>{if(h)return()=>void i?.(!1)},[h,i]);let Ce=(0,D.useRef)(h);(0,D.useEffect)(()=>{Ce.current=h},[h]),(0,D.useEffect)(()=>{if(!t||!T||!Lc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!Ce.current&&(g(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,T,i]),(0,D.useEffect)(()=>{t&&T&&rs()&&!Ce.current&&(g(!0),i?.(!0))},[t,T,i]),(0,D.useEffect)(()=>{if(!T)return;let e=e=>{if(e.key!==`Escape`)return;if(S)return void Le.current();if(he(),h)return g(!1);let t=Rc(document.activeElement,document.body,p.current);t===`game`?Le.current():t===`controls`&&m.current?.focus({preventScroll:!0})};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[T,h,he,S]),(0,D.useEffect)(()=>{if(!h||!Lc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,g(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[h]),(0,D.useEffect)(()=>{if(!h||typeof document>`u`)return;let e=()=>{document.fullscreenElement||Lc()||g(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[h]);let Te=rs(),Ee=T&&kc({player:te,guided:_,movedOff:ne,reconnecting:C})&&!u?.playsAs,De=async e=>{g(e),await i?.(e)},Oe=()=>m.current?.focus({preventScroll:!0}),ke=()=>{It(Dc,`1`),v(!0),re(!1)},Ae=()=>{he();let e=C?`[data-testid="join-reconnecting-leave"]`:`[data-testid="join-bar"] button`;p.current?.querySelector(e)?.focus({preventScroll:!0})},je=()=>{let e=p.current?.querySelector(`[data-testid="join-check-open"]`);e?e.focus({preventScroll:!0}):Oe(),ee(!1)},Me=()=>Rc(document.activeElement,document.body,p.current),[Ne,Pe]=(0,D.useState)(`game`);(0,D.useEffect)(()=>{if(!T)return;let e=()=>Pe(Me()),t=()=>window.setTimeout(e,0);return e(),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t)}},[T]);let Fe=()=>{switch(T?zc({checking:S,guide:Ee,where:Me(),full:h}):null){case`close-check`:return je(),!0;case`close-guide`:return ke(),Oe(),!0;case`show-controls`:return Ae(),!0;case`leave-full`:return De(!1),!0;default:return!1}},Le=(0,D.useRef)(Fe);(0,D.useEffect)(()=>{Le.current=Fe});let Re=t&&!de&&T&&zc({checking:S,guide:Ee,where:Ne,full:h})!==null;(0,D.useEffect)(()=>{if(Re)return Xo(()=>void Le.current())},[Re]);let ze=!t&&T&&!de;(0,D.useEffect)(()=>{if(!ze)return;let e=window.location.href;window.history.pushState(window.history.state,``);let t=!0,n=()=>{if(t=!1,!Le.current())return window.history.back();window.history.pushState(window.history.state,``),t=!0};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),t&&window.location.href===e&&window.history.back()}},[ze]);let Be=l.kind===`joined`;(0,D.useEffect)(()=>{if(!Be)return;let e=document.activeElement;if(e&&e!==document.body)return;let t=Te&&Ee?p.current?.querySelector(`[data-testid="join-guide-ok"]`):null;t?t.focus({preventScroll:!0}):Oe()},[Be]),(0,D.useEffect)(()=>{x.pressed&&T&&!S&&Me()===`controls`&&Oe()},[x.pressed]);let Ve=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,z.jsxs)(`div`,{className:t?`rounded-[var(--radius-card)] bg-neutral-900 text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black text-white`,"data-join-ui":``,children:[l.kind===`connecting`&&o&&a&&(0,z.jsx)(Tc,{href:a}),(0,z.jsx)(Vc,{text:l.kind===`connecting`?s(`join_connecting`,{host:d},`Connecting to ${d}…`):s(`join_waiting`,{host:d},`Waiting for ${d} to let you in`),body:l.kind===`asking`?s(`join_waiting_body`,{host:d},`${d} sees your name on their screen and taps Allow.`):void 0,onCancel:Ve})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,z.jsxs)(`div`,{className:t?`flex flex-col items-center gap-4 rounded-[var(--radius-card)] bg-neutral-900 px-6 py-10 text-center text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black px-6 text-center text-white`,"data-testid":`join-ended`,"data-why":l.why,"data-join-ui":``,children:[(0,z.jsx)(Se,{size:28,className:`text-white/60`}),(0,z.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:Mc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,z.jsx)(Tc,{href:a}),(0,z.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,z.jsx)(`button`,{type:`button`,onClick:r,autoFocus:!0,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`join-again`,children:l.kind===`refused`&&l.why===`not_playing`?s(`join_retry`,void 0,`Try again`):s(`join_again`,void 0,`Ask to join again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!i,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let He=l.player,Ue=c.light??at(He),We=c.rttMs??u?.rttMs??null,Ge=it(We),Ke=Lc(),qe=T&&!C&&!x.ready&&Ke&&(!t||h),Je=kc({player:He,guided:_,movedOff:ne,reconnecting:C}),Ye=He===Oc,Xe=u?.playsAs??null,Ze=C?(l.deadline-w)/1e3:0,Qe=()=>De(!h),$e=t&&!h&&Ke&&T,et=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`span`,{className:`flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 font-medium`,"data-testid":`join-player`,children:[(0,z.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`}}),t&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:He},`You are Player ${He}`)]}),We!=null&&(0,z.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:Bc[Ge]},"data-testid":`join-delay`,"data-tone":Ge,"data-path":c.path??void 0,children:[c.path&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[Ac(s,c.path),` · `]}),Math.round(We),` ms`]}),Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-stream`,children:s(`join_seat_stream`,{host:d},`You're playing as ${d}'s PS5 user. No need to pick one.`)}),Xe&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-plays-as`,children:s(`join_plays_as`,{profile:Xe},`You're playing as ${Xe}. No need to pick one.`)}),E&&!Ye&&u?.seatNote&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-note`,children:s(`join_seat_tv_asks`,{host:d},`${d} chose a profile for you, but it couldn't be used. The TV will ask who you are.`)}),E&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-picking`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)})]}),tt=(0,z.jsxs)(z.Fragment,{children:[le&&de&&k.shown&&!C&&(0,z.jsxs)(`button`,{type:`button`,onClick:k.hide,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 font-medium`,"data-testid":`join-hide-controls`,children:[(0,z.jsx)(pe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex items-center gap-1 rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-sound`,children:[(0,z.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-mute`,children:[c.muted?(0,z.jsx)(M,{size:13}):(0,z.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,z.jsxs)(`span`,{className:`flex items-center gap-1 rounded-full bg-black/60 px-2.5 py-1 text-white/80`,"data-testid":`join-no-sound`,children:[(0,z.jsx)(M,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>void Qe(),"aria-label":h?s(`join_exit_fullscreen`,void 0,`Leave full screen`):s(`pad_fill`,void 0,`Full screen`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-full`,children:h?(0,z.jsx)(be,{size:13}):(0,z.jsx)(O,{size:13})}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),"aria-label":s(`join_check_title`,void 0,`Check your controller`),title:s(`join_check_title`,void 0,`Check your controller`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-check-open`,children:(0,z.jsx)(me,{size:13})}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex items-center gap-1 rounded-full bg-[var(--color-danger,#dc2626)] px-3 py-1 font-medium`,"data-testid":`join-leave`,children:[(0,z.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),nt=k.shown?`opacity-100`:`pointer-events-none opacity-0`,rt={"data-testid":`join-bar`,"data-shown":k.shown?`1`:`0`,onFocus:e=>{(Te||e.target.matches?.(`:focus-visible`))&&ce(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||ce(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&oe(!0)},onPointerLeave:()=>oe(!1)},ot=h||!t?`fixed inset-0 z-[200] bg-black`:`relative mx-auto aspect-video w-full max-w-[max(20rem,calc((100dvh_-_22rem)*16/9))] overflow-hidden rounded-[var(--radius-card)] bg-black shadow-[var(--shadow-2)]`,st=t&&h;return(0,z.jsxs)(`div`,{className:`space-y-2`,ref:p,"data-join-ui":``,children:[(0,z.jsxs)(`div`,{className:`${ot} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},role:st?`dialog`:void 0,"aria-modal":st?!0:void 0,"aria-label":st?s(`pad_fill`,void 0,`Full screen`):void 0,onPointerMove:e=>{if(e.pointerType===`mouse`)return he();let t=_e.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>Ic&&ve()},onPointerDown:e=>{if(Fc(e.target))return;if(e.pointerType===`mouse`||!de)return he();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;ve();let{pointerId:t,clientX:n,clientY:r}=e;_e.current={id:t,x:n,y:r,timer:setTimeout(()=>{_e.current=null,navigator.vibrate?.(15),k.toggle()},450)}},onPointerUp:ve,onPointerCancel:ve,onPointerLeave:ve,"data-testid":`join-stage-view`,children:[(0,z.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),le&&!k.shown&&!C&&We!=null&&(0,z.jsxs)(`span`,{className:`pointer-events-none absolute z-10 rounded-full bg-black/40 px-1.5 py-0.5 text-[10px] leading-none tabular-nums`,style:{color:Bc[Ge],top:`max(0.5rem, env(safe-area-inset-top))`,right:`max(0.5rem, env(safe-area-inset-right))`},"data-testid":`join-delay-corner`,children:[Math.round(We),` ms`]}),qe?(0,z.jsxs)(`div`,{className:`absolute left-1/2 top-1/2 z-20 flex w-max max-w-[min(24rem,calc(100%-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-2 rounded-2xl bg-black/70 p-3 text-xs backdrop-blur-sm transition-opacity duration-300 ${nt}`,...rt,children:[(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:et}),(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:tt})]}):$e?null:(0,z.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex flex-wrap items-center gap-2 bg-gradient-to-b from-black/70 to-transparent px-3 pb-5 pt-[max(8px,env(safe-area-inset-top))] text-xs transition-opacity duration-300 ${nt}`,...rt,children:[et,(0,z.jsx)(`span`,{className:`flex-1`}),tt]}),!k.shown&&!qe&&(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},"aria-label":s(`join_show_controls`,void 0,`Show controls`),className:`absolute left-1/2 top-[max(6px,env(safe-area-inset-top))] z-20 flex h-7 w-11 -translate-x-1/2 items-center justify-center rounded-full bg-black/40 text-white/70 opacity-60 hover:opacity-100 focus-visible:opacity-100`,"data-testid":`join-show-controls`,children:(0,z.jsx)(ue,{size:16,"aria-hidden":!0})}),ye&&!k.shown&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-[max(10px,env(safe-area-inset-top))] z-20 -translate-x-1/2 rounded-full bg-black/60 px-3 py-1 text-xs text-white/85`,"data-testid":`join-hold-hint`,children:s(`join_hold_hint`,void 0,`Press and hold the picture to show the buttons`)}),c.problem&&(0,z.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`join-problem`,children:c.problem===`no_hevc`?s(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):s(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),S&&(0,z.jsx)(Cc,{onClose:je}),qe&&(0,z.jsx)(ks,{stream:e,layout:`overlay`,onMenu:()=>k.shown?k.hide():he()}),!qe&&!C&&(0,z.jsxs)(`div`,{className:`absolute bottom-3 left-3 z-20 flex items-center gap-2 rounded-2xl bg-black/70 px-3 py-1.5 text-xs transition-opacity duration-300 ${nt}`,"data-testid":`join-pad`,children:[(0,z.jsx)(me,{size:14,style:{color:x.pressed?`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`:void 0}}),x.ready?(0,z.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),x.weak8BitDo&&x.id&&(0,z.jsx)(ps,{id:x.id,className:`text-amber-200/90`}),x.kind===`guess`&&no()&&(0,z.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2 text-white/75`,"data-testid":`join-pad-unknown`,children:[s(`join_check_unknown_short`,void 0,`Not on our list: buttons may be mixed up.`),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),className:`rounded-full bg-white px-2.5 py-0.5 font-medium text-black`,"data-testid":`join-pad-unknown-check`,children:s(`join_check_title`,void 0,`Check your controller`)})]})]}):Ke&&t&&!h?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,z.jsxs)(`span`,{className:`flex flex-col`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,z.jsx)(`span`,{className:`text-white/60`,"data-testid":`join-pad-keys`,children:s(`join_pad_keys`,void 0,`Or use the keyboard: WASD move, arrows D-pad, Enter ✕, Backspace ○, Q □, E △, Tab Options.`)})]}),Te&&(0,z.jsx)(`span`,{className:`max-w-[14rem] border-l border-white/20 pl-2 text-white/70`,"data-testid":`join-tv-back`,children:s(`join_tv_back_hint`,void 0,`Press Back on the remote for the buttons.`)})]}),u?.blockSystem&&u.state===`playing`&&!qe&&(0,z.jsx)(`p`,{className:`absolute bottom-3 right-3 z-20 rounded-full bg-black/60 px-3 py-1 text-[11px] text-white/70 transition-opacity duration-300 ${nt}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),fe&&!Ye&&de&&!k.shown&&!C&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-2 z-20 -translate-x-1/2 whitespace-nowrap rounded-full bg-white/90 px-2.5 py-1 text-xs font-medium text-black`,"data-testid":`join-picking-note`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)}),Je&&!Xe&&(0,z.jsxs)(`div`,{className:`absolute bottom-14 left-1/2 z-30 w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-2xl border border-white/10 bg-neutral-900/90 p-4 text-sm shadow-2xl backdrop-blur-md`,"data-testid":`join-guide`,children:[(0,z.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/75`,children:s(`join_guide_body`,void 0,`On your controller, press PS once. The TV asks "Who's using this controller?". Pick Quick Play or your own user. The host doesn't need to do anything.`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/60`,children:s(`join_guide_menus`,void 0,`On the PS5's home screen only the host controls the menus; your controller plays inside games.`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>{ke(),Oe()},className:`mt-3 rounded-full bg-white px-3 py-1 text-xs font-medium text-black`,"data-testid":`join-guide-ok`,children:s(`join_guide_ok`,void 0,`Got it`)})]}),C&&(0,z.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-black/70 px-6 text-center`,"data-testid":`join-reconnecting`,children:[(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`absolute right-3 top-[max(10px,env(safe-area-inset-top))] flex items-center gap-1 rounded-full bg-white/15 px-3 py-1.5 text-sm font-medium hover:bg-white/25`,"data-testid":`join-reconnecting-leave`,children:[(0,z.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,z.jsx)(`span`,{className:`h-7 w-7 animate-spin rounded-full border-2 border-white/30 border-t-white`,"aria-hidden":!0}),l.hostStopped?(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:Ec(Ze)},`The host stopped playing — waiting for them to start again (${Ec(Ze)})`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:Ec(Ze)},`Your place is kept for ${Ec(Ze)}.`)})]})]}),!t&&T&&y&&Ke&&(0,z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,z.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,z.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})}),(0,z.jsx)(`div`,{ref:m,tabIndex:0,"data-own-arrows":``,"data-join-game":``,"aria-label":s(`join_game_label`,{host:d},`${d}'s game`),className:`pointer-events-none absolute inset-0 outline-none`,"data-testid":`join-game`})]}),$e&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-[var(--radius-card)] bg-neutral-900 px-3 py-2 text-xs text-white`,"data-testid":`join-bar`,"data-shown":`1`,"data-below":`1`,children:[(0,z.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:et}),(0,z.jsxs)(`button`,{type:`button`,onClick:()=>void Qe(),className:`flex h-11 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full bg-white/15 px-3 text-sm font-medium hover:bg-white/25`,"data-testid":`join-fullscreen-below`,children:[(0,z.jsx)(O,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,z.jsx)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,"aria-label":c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`),className:`flex h-11 w-11 items-center justify-center rounded-full bg-white/15 hover:bg-white/25`,children:c.muted?(0,z.jsx)(M,{size:16}):(0,z.jsx)(we,{size:16})}):c.sound?null:(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-white px-3 text-sm font-medium text-black`,children:[(0,z.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-[var(--color-danger,#dc2626)] px-4 text-sm font-medium`,"data-testid":`join-leave-below`,children:[(0,z.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var Uc=`ps5upload.join.name`;function Wc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function Gc(e){return e.trim().slice(0,32)}function Kc(e=``){return Gc(Lt(`ps5upload.join.name`)??``)||e}function qc(e){let t=Gc(e);return t&&It(Uc,t),t}function Jc(e){try{return!!sessionStorage.getItem(Ro(e))}catch{return!1}}async function Yc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Xc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Ie(),c=wc(r&&o!==!1?e:null,i),[l,u]=(0,D.useState)(()=>Kc(Wc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(0),h=(0,D.useCallback)(e=>{if(!e)return;let t=typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,n=e.querySelector(`[data-testid="join-name"]`)?.value.trim()?`join-go`:t?null:`join-name`;n&&e.querySelector(`[data-testid="${n}"]`)?.focus({preventScroll:!0})},[]),g=i=>{let s=qc(i);if(!s)return;let c=new cc({url:e,invite:t,name:s,host:n,transport:r,path:a,...o===void 0?{}:{internet:o}});f(c),m(e=>e+1),c.start()};if((0,D.useEffect)(()=>{!d&&Jc(t)&&l.trim()&&g(l)},[]),(0,D.useEffect)(()=>d?dc(d):void 0,[d]),(0,D.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,z.jsx)(Hc,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),g(l)},onFullscreen:Yc},p);let _=n??s(`join_host_fallback`,void 0,`your friend`),v=(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,"data-join-ui":``,children:(0,z.jsxs)(`form`,{ref:h,className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),g(l)},children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,z.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,z.jsx)(Se,{size:20})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:_},`Play on ${_}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,z.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,z.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,z.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),maxLength:32,autoComplete:`nickname`,className:`block w-full rounded-lg border border-white/15 bg-black px-3 py-2 text-base outline-none focus:border-white/50`,"data-testid":`join-name`}),(0,z.jsx)(`span`,{className:`block text-xs text-white/50`,children:s(`join_name_hint`,void 0,`Your friend sees this when you ask to join.`)})]}),(0,z.jsx)(`button`,{type:`submit`,disabled:!l.trim(),className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black disabled:opacity-40`,"data-testid":`join-go`,children:s(`join_button`,void 0,`Join`)}),c&&i&&(0,z.jsx)(Tc,{href:i})]})});return t?(0,z.jsx)(Wo,{appLink:rt(location.href),children:v}):v}function Zc(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Qc(e,t){let n=Zc(e),r=Zc(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function $c(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Zc(t);return n===0?`lan`:n===1?`tailscale`:null}function el(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Qc(a(i.localCandidateId),a(i.remoteCandidateId))}function tl(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function nl(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function rl(e,t){let n=nl(e);return n!==null&&n===t.toUpperCase()}var il=16777216;function al(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function sl(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var cl=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],ll=1500,ul=2e4;function dl(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var fl=null;function pl(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function ml(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||fl)return;let r=tl(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};fl=a;let o=()=>{fl===a&&(fl=null,a.timer&&clearTimeout(a.timer),pl(i))};i.onopen=()=>i.send(JSON.stringify({v:1,t:`join`,room:e.room})),i.onmessage=e=>{if(typeof e.data==`string`)try{a.msgs.push(JSON.parse(e.data))}catch{}},i.onclose=o,i.onerror=()=>{},a.timer=setTimeout(o,t.keepMs??6e4)}function hl(e,t){let n=fl;return n?(fl=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(pl(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function gl(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new ol,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??tl(e.hub),a=t.signalUrl||t.lan?null:hl(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:cl}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=dl(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!rl(t.sdp,e.fp):nl(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(sl(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return el(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of al(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+ul,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},ll),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(He,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}var _l=3e3;function vl(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var U=e=>vl(e,`api/join/signal`);function yl(e){let t=[];if(e.rtc){let n=e.net??{room:``,key:``,fp:e.fp??``,hub:``};for(let[r,i]of[[`lan`,e.lan],[`tailscale`,e.ts]]){let a=i?U(i):null;if(!a)continue;let o=e.rtcMake(n,{signalUrl:e.reach(a),...e.net?{}:{lan:!0}});t.push({via:r,make:()=>new o(``),pinned:!!n.fp})}if(e.net){let n=e.rtcMake(e.net,{});t.push({via:`hub`,make:()=>new n(``),pinned:!0})}}let n=e.lan?vl(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var bl=new Map;function xl(e,t,n=300,r=_l){let i=e.some(e=>e===`lan`||e===`tailscale`),a=e.some(e=>e!==`socket`);return e.map(e=>e===t?0:e===`hub`&&i?n:e===`socket`&&a?r:0)}function Sl(e){let t=e.find(e=>e.via===`hub`),n=e.find(e=>(e.via===`lan`||e.via===`tailscale`)&&[`no_direct`,`net_full`,`offer`].includes(Ue(e.e)??``));return t&&(Ue(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function Cl(e,t){var n;let r=t.log??(()=>{}),i=t.headStartMs??300,a=t.socketAfterMs??3e3;class o{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.live=[],this.waiting=[],this.pinned=new Set,this.t0=0,this.closes=[],this.winner=null,setTimeout(()=>this.begin(),0)}get via(){return this.winner?.via??null}get media(){return this.winner?.s?.media??null}async netPath(){let e=this.winner?.s;return e?.netPath?e.netPath():null}begin(){if(this.readyState!==0)return;let n=e();if(!n.length){this.end({type:`close`,code:1006,reason:``,wasClean:!1});return}this.t0=Date.now();for(let e of n)e.pinned&&this.pinned.add(e.via);let r=xl(n.map(e=>e.via),bl.get(t.room)??null,i,a);n.forEach((e,t)=>{r[t]===0?this.launch(e.via,e.make):this.waiting.push({via:e.via,make:e.make,timer:setTimeout(()=>this.startWaiting(e.via),r[t])})})}startWaiting(e){let t=this.waiting.findIndex(t=>t.via===e);if(t<0)return;let[n]=this.waiting.splice(t,1);clearTimeout(n.timer),this.launch(n.via,n.make)}launch(e,t){if(this.readyState!==0)return;let n;try{n=t()}catch{this.tryClosed(e,{type:`close`,code:1006,reason:``,wasClean:!1});return}r(`path: trying ${e}`);let i={via:e,s:n};this.live.push(i),n.binaryType=this.binaryType,n.onopen=e=>this.won(i,e),n.onclose=t=>{this.live=this.live.filter(e=>e!==i),this.tryClosed(e,t)},n.onerror=()=>{},n.onmessage=null}tryClosed(e,t){if(this.readyState===0){if(r(`path: ${e} failed after ${Date.now()-this.t0} ms${t?.reason?` (${t.reason})`:``}`),this.closes.push({via:e,e:t}),this.pinned.has(e)&&Ue(t)===`mismatch`){for(let e of this.waiting.filter(e=>e.via===`socket`))clearTimeout(e.timer);this.waiting=this.waiting.filter(e=>e.via!==`socket`)}!this.live.length&&this.waiting.length?this.startWaiting(this.waiting[0].via):!this.live.length&&!this.waiting.length&&this.end(Sl(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,bl.set(t.room,e.via),r(`path: playing by ${e.via} after ${Date.now()-this.t0} ms`);for(let e of this.waiting.splice(0))clearTimeout(e.timer);for(let t of this.live.splice(0))if(t!==e){t.s.onopen=t.s.onclose=t.s.onmessage=t.s.onerror=null;try{t.s.close()}catch{}}let i=e.s;i.onmessage=e=>this.onmessage?.(e),i.onerror=e=>this.onerror?.(e),i.onclose=e=>{this.readyState!==3&&(this.readyState=3,this.onclose?.(e))},this.readyState=1,t.onWin?.(e.via),this.onopen?.(n)}send(e){if(this.readyState!==1||!this.winner)throw Error(`not open`);this.winner.s.send(e)}close(e,t){if(this.readyState===3)return;let n=this.readyState===1;this.readyState=3;for(let e of this.waiting.splice(0))clearTimeout(e.timer);let r=this.winner?[this.winner,...this.live]:this.live.splice(0);for(let n of r){n.s.onopen=n.s.onclose=n.s.onmessage=n.s.onerror=null;try{n.s.close(e,t)}catch{}}let i=this.onclose;if(i){let r={type:`close`,code:e??1e3,reason:t??``,wasClean:n};setTimeout(()=>i(r),0)}}end(e){if(this.readyState===3)return;this.readyState=3;let t=this.onclose,n=e??{type:`close`,code:1006,reason:``,wasClean:!1};t&&setTimeout(()=>t(n),0)}}return n=o,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,o}fs();var wl=new URLSearchParams(location.hash.slice(1)),Tl=wl.get(`n`)?.trim()||null,El=nt(location.hash);El&&ml(El);var Dl=(0,x.createRoot)(document.getElementById(`root`));if(El){let e=gl(El,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Re(location.hash,`join`);Dl.render((0,z.jsx)(Xc,{url:tl(El.hub),invite:El.key,host:Tl,transport:e,lanUrl:t?ze(t,{key:El.key}):null}))}else{let e=wl.get(`i`)||null,t=location.pathname.replace(/\/join\/?$/,``),n=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${t}/api/join/ws`,r=e=>console.info(`[join] ${e}`),i=`${location.origin}${t}/join`,a=typeof RTCPeerConnection>`u`?void 0:Cl(()=>yl({net:null,lan:i,ts:null,fp:tt(wl.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>gl(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});Dl.render((0,z.jsx)(Xc,{url:n,invite:e,host:Tl,path:$c(location.hostname),transport:a,internet:!1}))} diff --git a/engine/crates/ps5upload-engine/src/pad_page.html b/engine/crates/ps5upload-engine/src/pad_page.html index a59852b02..78a6de820 100644 --- a/engine/crates/ps5upload-engine/src/pad_page.html +++ b/engine/crates/ps5upload-engine/src/pad_page.html @@ -270,7 +270,7 @@ z AÍp\Ž0N˜HJê´ªØ^U I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} diff --git a/site/join/index.html b/site/join/index.html index b5d815491..a60fa417f 100644 --- a/site/join/index.html +++ b/site/join/index.html @@ -270,7 +270,7 @@ z AÍp\Ž0N˜HJê´ªØ^U I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var E={a:v};this.setModule=t=>{e.setModule(bi,t)},this.getModule=()=>e.getModule(bi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,E)).then(e=>{let t=e.exports;y(t),a=t.g,o(),T(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=C,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var xi=o((()=>{}));function Si(e={}){Si.errors||Object.defineProperties(Si,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(Si.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var Ci=o((()=>{yi(),xi()})),wi,Ti=o((()=>{yi(),xi(),Ci(),wi=class extends hi{constructor(e){super(e,`opus-decoder`,Si,bi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ei=c({OpusDecoder:()=>Si,OpusDecoderWebWorker:()=>wi}),Di=o((()=>{Ci(),Ti(),yi(),_i(Si,`OpusDecoder`),_i(wi,`OpusDecoderWebWorker`)})),Oi=[8e3,12e3,16e3,24e3,48e3],ki=null;function Ai(){return ki??=Xn(()=>Promise.resolve().then(()=>(Di(),Ei)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw ki=null,e}),ki}function ji(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function Mi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ni=class{constructor(e,t=Ai){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!ji())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Oi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(Mi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Pi={makeDecoder:e=>new Ni(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Fi(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Ii(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var Li=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ri(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Li)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function zi(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Bi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Vi(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function F(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Hi=(e,t,n,...r)=>Vi(e,F([t,1],[n,3]),...r),Ui=F([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Wi(e){let t=e.handler===`vide`,n=Vi(`ftyp`,new TextEncoder().encode(`isom`),F([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Vi(`moov`,Hi(`mvhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Ui,new Uint8Array(24),F([2,4])),Vi(`trak`,Hi(`tkhd`,0,3,F([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Ui,F([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Vi(`mdia`,Hi(`mdhd`,0,0,F([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Hi(`hdlr`,0,0,F([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),F([0,1])),Vi(`minf`,t?Hi(`vmhd`,0,1,new Uint8Array(8)):Hi(`smhd`,0,0,F([0,4])),Vi(`dinf`,Hi(`dref`,0,0,F([1,4]),Hi(`url `,0,1))),Vi(`stbl`,Hi(`stsd`,0,0,F([1,4]),e.sampleEntry),Hi(`stts`,0,0,F([0,4])),Hi(`stsc`,0,0,F([0,4])),Hi(`stsz`,0,0,F([0,4],[0,4])),Hi(`stco`,0,0,F([0,4])))))),Vi(`mvex`,Hi(`trex`,0,0,F([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Gi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Hi(`trun`,0,1793,F([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Vi(`traf`,Hi(`tfhd`,0,131072,F([1,4])),Hi(`tfdt`,1,0,F([t,8])),o(e)),c=Hi(`mfhd`,0,0,F([e,4])),l=Vi(`moof`,c,s(0)).length,u=Vi(`moof`,c,s(l+8)),d=Vi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Ki(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=zi(e).filter(e=>!r.includes(Bi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var qi=e=>e.toString(16).padStart(2,`0`),Ji=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Yi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Xi(e){let t=zi(e),n=t.filter(e=>Bi(e,!1)===7),r=t.filter(e=>Bi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Yi([F([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(Ji),F([r.length,1]),...r.map(Ji)])}function Zi(e,t,n){let r=zi(e),i=e=>r.filter(n=>Bi(n,t)===e),a=(e,t)=>Vi(e,new Uint8Array(6),F([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),F([24,2],[65535,2]),t);if(!t){let t=i(7),r=Xi(e);return r?{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Vi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${qi(t[0][1])}${qi(t[0][2])}${qi(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Xr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Yi([F([128|e,1],[t.length,2]),...t.map(Ji)]),m=Vi(`hvcC`,F([1,1]),u,F([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Wi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Qi(e,t,n,r,i,a){return Gi(e,t,n,Ki(r,i),a)}function $i(e,t){let n=Vi(`dOps`,F([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Wi({handler:`soun`,timescale:48e3,sampleEntry:Vi(`Opus`,new Uint8Array(6),F([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function ea(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function ta(e,t,n){return Gi(e,t,ea(n),n,!0)}var na={watch:30,player:4},ra={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ia={seek:.8,speed:.25,target:.12};function aa(e,t,n){let r=typeof n==`string`?ra[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function oa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ha(e,t,n):new ka(e,t,n)}var sa=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function I(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var L=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ca(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function la(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ua=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+da;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},da=.02;async function fa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var pa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},ma=[`pointerup`,`touchend`,`click`,`keydown`],ha=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():la(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new pa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new sa(n),this.clock=new ua(t===`player`?.05:.08),typeof AudioDecoder>`u`&&va()&&(this.mseSound=new ya(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=ni(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!xa())return!1;let e=new ka(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,ga(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=ni(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await Aa(e):Ii(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Xi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=ri(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Fi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>na[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Ki(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];fa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return va()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new si((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ca(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new ya(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new si((e,n)=>this.play(e,n,t.sampleRate),Pi,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ca(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function ga(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function _a(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function va(){let e=typeof window>`u`?null:xa();return!!e&&(_a(e,`audio/mp4; codecs="Opus"`)||_a(e,`audio/mp4; codecs="opus"`))}var ya=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new L,this.el=n,this.track=new Ta(n,()=>this.fail(),e===`player`?ia:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=I(e);if(!t||!this.order.take(t.index))return;let n=ta(this.track.nextSeq(),this.time,t.packet);this.time+=ea(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=$i(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},ba=class{constructor(e,t,n=Pi){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ua(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,ga();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new si((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ca(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of ma)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of ma)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function xa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var Sa=10,Ca=3;function wa(e,t,n,r=Ca){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var Ta=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=xa();if(!n||!_a(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=Ea(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=aa(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>Sa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-Ca;if(this.keys){if(r=wa(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Ca&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function Ea(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Da=1e4,Oa=class{constructor(e=3,t=Da,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ka=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new pa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new sa(n),this.fails=new Oa(3,Da,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new ya(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new Ta(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!va())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ba(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?la(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=ni(e,this.hevc)??{w:1920,h:1080},r=Zi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Fi(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>na[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Qi(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function Aa(e){let t=ii(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ri(1920,1080)}var R={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},ja={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ma(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Na={ArrowUp:{button:R.UP},ArrowDown:{button:R.DOWN},ArrowLeft:{button:R.LEFT},ArrowRight:{button:R.RIGHT},Enter:{button:R.CROSS},Space:{button:R.CROSS},Backspace:{button:R.CIRCLE},Escape:{button:R.CIRCLE},KeyQ:{button:R.SQUARE},KeyE:{button:R.TRIANGLE},KeyZ:{button:R.L1},KeyC:{button:R.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:R.L3},KeyG:{button:R.R3},Tab:{button:R.OPTIONS},Backquote:{button:R.SHARE},KeyH:{button:R.PS},KeyT:{button:R.TOUCHPAD},KeyW:{stick:`ly`,dir:-1},KeyS:{stick:`ly`,dir:1},KeyA:{stick:`lx`,dir:-1},KeyD:{stick:`lx`,dir:1},KeyI:{stick:`ry`,dir:-1},KeyK:{stick:`ry`,dir:1},KeyJ:{stick:`rx`,dir:-1},KeyL:{stick:`rx`,dir:1}};R.UP,R.DOWN,R.LEFT,R.RIGHT,R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD;var Pa=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Fa(e,t=Na){let n={...ja};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Pa(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Ia=[R.CROSS,R.CIRCLE,R.SQUARE,R.TRIANGLE,R.L1,R.R1,0,0,R.SHARE,R.OPTIONS,R.L3,R.R3,R.UP,R.DOWN,R.LEFT,R.RIGHT,R.PS,R.TOUCHPAD];function La(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Ra=[0,1,1,1,0,-1,-1,-1],za=[-1,-1,0,1,1,1,0,-1];function Ba(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=La(n);return e===null?0:(t.hat===`x`?Ra:za)[e]}return t.inv?-n:n}var Va={buttons:Ia.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function Ha(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=La(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ua(e){if(e.mapping===`standard`)return Va;let t=Wa.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Va;let r={...Va,buttons:[...Va.buttons,[R.UP,{h:n,at:0}],[R.RIGHT,{h:n,at:2}],[R.DOWN,{h:n,at:4}],[R.LEFT,{h:n,at:6}]]};return Wa.set(e.id,r),r}var Wa=new Map;function Ga(e,t=Ua){let n={...ja},r=e=>Math.abs(e)<.08?0:Pa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(Ba(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Ha(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Ha(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Ha(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Ka(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Pa(e.lx+t.lx),ly:Pa(e.ly+t.ly),rx:Pa(e.rx+t.rx),ry:Pa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function qa(e,t,n,r=()=>globalThis.navigator?.getGamepads?.()??[]){let i=e=>e?.vibrationActuator;for(let a of e.some(i)?e:r()){let e=i(a);e&&(t===0&&n===0?e.reset?.():e.playEffect?.(`dual-rumble`,{duration:1e3,strongMagnitude:t/255,weakMagnitude:n/255}))}}var Ja=new Map;function Ya(e,t){return{id:`${e.id} (app)`,index:3+e.slot,connected:!0,mapping:`standard`,timestamp:0,axes:e.axes,buttons:e.buttons.map(e=>({pressed:e>.5,touched:e>0,value:e})),vibrationActuator:t?.vibrationActuator??null,hapticActuators:t?.hapticActuators??[]}}function Xa(e){let t=e?.getGamepads?.()??[];return Ja.size===0||t.some(e=>!!e?.connected)?[...t]:[...Ja.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ya(e))}var Za=`b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,,,,,,,a0,a1(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,,,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b2,b3,b0,b1,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1(b1,b0,b2,b3,,b7,a3,a4,,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b1,b0,b2,b3,,b7,b4,b5,,b9,,,b12,b14,b15,b13,,,a0,a1,a5~,a2~(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,,,b7,b5,b4,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b3,b4,b6,b5,b7,b2,b8,,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b9,b10,b2,b8,,,h0.1,h0.4,h0.8,h0.2,b5,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b5,b7,b2,,b8,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b12,b13,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b14,b13,b15,b12,b10,b11,b8,b9,b0,b3,b1,b2,b4,b6,b7,b5,b16,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,a2,a5,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,,,-a1,+a1,-a0,+a0(b1,b2,b0,b3,b4,b5,,,b8,b9,,,b12,b13,b15,b14,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,b11,b12,b13,b14,b15,b16,b10,,a0,a1,a2,a3(b0,b1,b3,b2,,b6,a2,a5,,b7,,,b8,b9,b10,b11,,,a0,a1,a3,a4(b0,b1,b3,b2,b4,b5,,,b8,b9,,,b10,b11,b12,b13,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,,,b13,b8,b10,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,,,b12,b9,b11,,,,,,,,hx,hy(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,b14,b15,b16,b17,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b5,b6,b7,b8,b9,b10,b12,b13,h0.1,h0.4,h0.8,h0.2,b11,,a0,a1,a2,a3(b0,b1,b3,b2,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,,,,b2,,b4,,b5,,,h0.1,h0.4,h0.8,h0.2,b6(b0,b1,b2,b3,b12,b4,b13,b5,b14,b6,b15,b7,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b1,b3,b0,b2,b13,b5,b12,b4,,b6,,,b11,b8,b10,b9,b16,,a0,a1~,a2,a3~(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b33,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b16,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b15,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,,,,,b8,,a0,a1,a3,a4(b1,b0,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,,h0.1,h0.4,h0.8,h0.2,b12,b13(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b11,b12,h0.1,h0.4,h0.8,h0.2,b10,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b12,b13,b14,b15,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,b14,b13,b14,b13,,,a0,a1,a3,a4(b1,b0,b2,b3,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b2,b3,b1,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b10(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,+a2,+a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,a2,a5,b6,b7,,,h0.1,h0.4,h0.8,h0.2,b8(b1,b2,,,,,,,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b21,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a5,a4,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b8,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b13,b13,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,a5,a4,,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a5,b7,b6,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,b7,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a5,a4,b9,b6,b7,b8,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b22,,a0,a1,a2,a3(b0,b1,b2,b3,b4,b5,a2,a3,b6,b7,b9,,b12,b14,b15,b13,b8,,a0,a1(b3,b4,b5,b6,b7,b8,a9,a8,b11,b12,b14,b15,b16,b17,b18,b19,b13,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b7,b9,b6,b8,b10,b11,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b9,b10,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b4,b3,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b3,b1,b4,,b10,a5,a4,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,,,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,,,,,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b8,b6,b9,b7,,b10,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b6,b4,b7,b5,b8,b9,,,-a4,+a4,-a3,+a3(b4,b8,b0,b12,b16,b20,b24,b28,b32,b36,b40,b44,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a8,a12(b8,b12,b0,b4,b16,b20,b24,b28,b32,b36,,,h0.1,h0.4,h0.8,h0.2,b44,,a0,a4,a8,a12(b4,b0,b8,b12,,b28,a12,a16,,b36,,,h0.1,h0.4,h0.8,h0.2,,,a0,a4,a20,a8(b1,b2,b0,b3,,b7,a3,a4,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b4,b0,b8,b12,,b28,a12,a16,,b36,,,b48,b56,b60,b52,,,a0,a4,a20,a8(b1,b2,,,b7,b5,a3,,,b9,,,b12,b14,b15,b13,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a5,b9,b8,b6,b7,b11,b12,b13,b14,b10,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,,,b5,b8,,,-a1,+a1,-a0,+a0,b2(b0,b1,b2,b3,b4,b5,b6,b15,b8,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b13,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a5(b0,b1,b3,b4,b6,b7,a5,a4,b12,b13,b15,b16,h0.1,h0.4,h0.8,h0.2,b14,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,-a1,+a1,-a0,+a0,b2(b0,b1,b3,b4,b6,b7,,,b10,b11,,,-a1,+a1,-a0,+a0(b0,b1,b3,b4,b6,b7,b8,a4,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a31(b0,b1,b3,b4,b8,b6,b9,b7,,b11,,,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b0,b4,b3,b6,b7,a4,a5,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a3(b1,b0,b4,b3,b6,b7,a5,a4,b10,b11,,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,hx,hy(b0,b1,b2,b3,b4,b5,b6,b7,b16,b15,b8,b9,b10,b11,b13,b12,b17,,a0,a1~,a2,a3~(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a4(b2,b1,b3,b0,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b33,b5,,,b6,b7,,,h0.1,h0.4,h0.8,h0.2(b0,b1,b3,b4,b6,b2,,,,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b1,b2,,,b6,,b9,b7,,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a2(b2,b1,b3,b0,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b4,,b6,,b2,b7,b9,,,b2,b14,b15,b13(b0,b1,b2,b3,b4,b5,a2,a5,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b5,b7,b2,b10,b8,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,a5~,a2~,b2,b8,b8,b5,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b4,,b9,b10,b6,b7,b8,,b5,b2,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b5,b4,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b3,b2,b6,b7,b4,b5,b8,b9,b11,b12,b13,b14,b15,b16,,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b16,b19,b17,b18,b6,b7,b8,b9,b10,b11,b13,,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a3,a4(b2,b1,b3,b0,b6,b7,b4,b5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a5,a2(b0,b1,b2,b3,b4,b5,a2,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,a2,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,b8,b9,b6,b7,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,b10,b11,b7,b6,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b10,b5,b11,b7,b8,b9,b4,b6,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b5,b7,b4,b6,b8,b9,,,h0.1,h0.4,h0.8,h0.2,b12(b1,b2,b0,b3,b4,b5,a3,a4,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a3(b1,b2,b0,b3,b4,b5,a3,a4,b8,b13,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,b13,a0,a1,a2,a5(b0,b4,b2,b1,b3,b6,,,b11,b9,,,h0.1,h0.4,h0.8,h0.2(b1,b2,b0,b3,b4,b5,a2,a5,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b2,b3,b9,b10,a4,a5,b4,b6,b7,b8,b11,b12,b13,b14,,,a0,a1,a2,a3(b1,b0,b3,b2,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b1,b2,b0,b3,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b1,b0,b3,b2,b4,b5,b6,b7,b8,b9,b10,b11,h0.1,h0.4,h0.8,h0.2,b12,,a0,a1,a2,a3(b0,b1,b3,b4,b6,b7,,,,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,b11,b14,b12,b13,b10,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,,a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,b3,b4,b6,b7,a4,a3,,,b13,b14,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b0,b1,b2,b3,b4,b5,,,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a2,a5(b6,b7,b9,b10,b12,b13,b14,b15,b16,b17,b19,b20,h0.1,h0.4,h0.8,h0.2,b18,,a0,a1,a3,a4(b0,b1,b2,b3,b4,b5,+a2,-a2,b6,b7,b8,b9,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a4(b0,b1,,,,,,,b7,b6,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1(b0,b1,b3,b4,b6,b7,,,b10,b11,,,,,,,,,a0,a1(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a2,a5(b1,b0,b4,b3,b6,b7,b8,b9,b10,b11,b13,b14,h0.1,h0.4,h0.8,h0.2,b2,,a0,a1,a3,a4(b1,b0,b4,b3,,b6,,b7,b10,b11,,,h0.1,h0.4,h0.8,h0.2,,,a0,a1,a3,a5`.split(`(`),Qa={l00790006:0,l00790011:1,l00790016:2,l00790122:3,l00790126:4,l00791800:5,l00791803:6,l0079181a:7,l0079181b:8,l0079181c:9,l00791830:10,l00791843:11,l00791844:12,l00791845:11,l00791846:13,l007918d2:7,l007918d4:14,l0079954e:15,l046dc20a:16,l046dc211:17,l046dc216:5,l046dc218:5,l046dc219:5,l046dc21a:18,l046dc21d:14,l046dc21e:14,l046dc21f:14,l046dcad1:5,l046dcad2:5,l04b4010a:19,l04b42411:20,l04b42412:21,l054c0268:22,l054c05c4:23,l054c09cc:24,l054c0ba0:24,l054c0cda:25,l054c0ce6:24,l054c0df2:24,l054c0e5f:24,l054c1337:26,l057e0330:27,l057e0337:28,l057e1337:29,l057e2006:30,l057e2007:31,l057e2008:32,l057e2009:33,l057e2017:34,l057e201e:35,l057e2069:36,l057e2073:37,l05ac022d:38,l05ac055b:39,l05ac057a:40,l05ac061a:41,l0e6f0109:42,l0e6f011e:7,l0e6f011f:14,l0e6f0128:5,l0e6f012f:7,l0e6f0130:7,l0e6f0131:14,l0e6f0139:14,l0e6f0146:43,l0e6f0164:14,l0e6f0180:7,l0e6f0181:7,l0e6f0184:7,l0e6f0185:44,l0e6f0187:7,l0e6f0188:7,l0e6f0203:45,l0e6f0207:46,l0e6f0213:14,l0e6f0214:7,l0e6f02a7:14,l0e6f02a8:47,l0e6f02b2:48,l0e6f02b8:14,l0e6f02c8:14,l0e6f02d7:49,l0e6f02d8:14,l0e6f02da:14,l0e6f02ef:14,l0e6f02f1:14,l0e6f0301:14,l0e6f0315:14,l0e6f0401:14,l0e6f0413:14,l0e6f1112:50,l0e6f1113:51,l0e6ff501:14,l0f0d0009:7,l0f0d0010:42,l0f0d0011:7,l0f0d0016:52,l0f0d0022:42,l0f0d004d:7,l0f0d005e:53,l0f0d005f:54,l0f0d0066:24,l0f0d0067:14,l0f0d006a:8,l0f0d006b:7,l0f0d006d:55,l0f0d006e:7,l0f0d0084:8,l0f0d0085:7,l0f0d0086:47,l0f0d0087:56,l0f0d0088:57,l0f0d0092:58,l0f0d00aa:39,l0f0d00c1:7,l0f0d00ee:59,l0f0d00f6:60,l0f0d00fb:39,l0f0d0137:61,l0f0d0138:62,l0f0d0150:14,l0f0d0185:14,l0f0d0196:63,l0f0d01ab:63,l15320401:24,l15320402:7,l15320705:64,l15320900:65,l15320a03:14,l15320a14:14,l15320a29:14,l15321000:8,l15321008:66,l1532100a:59,l1532100b:24,l15321100:24,l18d19400:65,l20d60dad:67,l20d62002:68,l20d62005:14,l20d6200b:14,l20d6200f:69,l20d62065:14,l20d62802:14,l20d64001:70,l20d64002:70,l20d64005:14,l20d66271:71,l20d6792a:24,l20d689e5:71,l20d6a710:5,l20d6a711:7,l20d6a712:7,l20d6a713:7,l20d6a714:7,l20d6ca6d:7,l24c65300:14,l24c6531a:14,l24c6541a:14,l24c6543a:14,l24c6581a:14,l24c65b02:14,l24c65d04:14,l24c6891a:63,l24c6891b:63,l24c6892a:72,l24c6892b:63,l24c6fafe:14,l27f80bbf:63,l28de1102:73,l28de1105:73,l28de1106:73,l28de1142:73,l28de11fc:43,l28de11ff:14,l28de1201:73,l28de1202:73,l28de1205:74,l2dc80651:75,l2dc81003:76,l2dc81080:76,l2dc82000:14,l2dc82003:14,l2dc8200a:77,l2dc82019:14,l2dc82025:14,l2dc82101:63,l2dc82830:78,l2dc82862:79,l2dc82865:79,l2dc82869:80,l2dc8286a:81,l2dc83010:82,l2dc83011:63,l2dc83012:63,l2dc83013:63,l2dc83015:63,l2dc83016:63,l2dc83017:63,l2dc83019:83,l2dc8301b:63,l2dc8301d:63,l2dc83100:84,l2dc83101:85,l2dc83102:85,l2dc83103:85,l2dc83104:85,l2dc83106:14,l2dc8310a:14,l2dc8310b:14,l2dc83230:86,l2dc83810:79,l2dc83820:87,l2dc85006:88,l2dc85101:89,l2dc85103:86,l2dc85104:90,l2dc85107:91,l2dc85108:91,l2dc85109:90,l2dc85111:92,l2dc85112:82,l2dc86000:92,l2dc86001:93,l2dc86002:92,l2dc86006:82,l2dc86007:94,l2dc86009:82,l2dc86012:63,l2dc86100:87,l2dc86101:93,l2dc86102:92,l2dc86728:95,l2dc89000:96,l2dc89001:96,l2dc89012:93,l2dc89015:79,l2dc89018:78,l2dc89020:97,l2dc89025:98,l2dc8ab21:78,l35371004:14,l35371007:63,l3537100b:14,l35371046:63,l35371058:63,l35371094:63,l35371097:63,l358a0102:63,l358a0202:63,l358a0203:63,l358a0204:63,m00790006:99,m00790011:100,m00791800:101,m00791803:102,m0079181c:41,m00791843:103,m00791844:104,m00791846:105,m007918d2:39,m0079954e:106,m046dc216:5,m046dc218:5,m046dc219:5,m046dc21a:18,m046dc21f:107,m04b4010a:108,m04b42411:20,m04b42412:20,m054c0268:22,m054c05c4:24,m054c09cc:24,m054c0ba0:24,m054c0cda:25,m054c0ce6:24,m054c0df2:24,m054c0e5f:24,m054c1337:26,m057e2006:30,m057e2007:31,m057e2009:60,m057e2017:109,m057e2069:36,m057e2073:37,m05ac061a:41,m0e6f0109:42,m0e6f0184:110,m0e6f0187:5,m0e6f0201:107,m0e6f0203:45,m0e6f0207:46,m0e6f0401:107,m0f0d002d:54,m0f0d004d:7,m0f0d005e:111,m0f0d005f:7,m0f0d0066:24,m0f0d006e:7,m0f0d0084:8,m0f0d0085:7,m0f0d0087:112,m0f0d0088:57,m0f0d0092:58,m0f0d00aa:39,m0f0d00c1:7,m0f0d00ee:113,m0f0d00f6:3,m0f0d0138:62,m0f0d0200:7,m15320401:24,m15320402:7,m15320705:64,m15320900:65,m15320a03:107,m15321000:8,m15321100:24,m18d19400:65,m20d66271:71,m20d6792a:24,m20d6a710:7,m20d6a711:44,m20d6ca6d:7,m24c6543a:107,m24c65d04:107,m24c6891a:114,m24c6891b:63,m24c6892a:64,m24c6892b:63,m24c6fafe:107,m2dc80651:115,m2dc82820:116,m2dc82830:78,m2dc82840:78,m2dc82865:87,m2dc82869:80,m2dc8286a:81,m2dc83011:63,m2dc83012:63,m2dc83013:63,m2dc83015:117,m2dc83016:63,m2dc83017:118,m2dc83019:83,m2dc8301b:63,m2dc8301d:63,m2dc83100:9,m2dc83101:85,m2dc83102:85,m2dc83103:85,m2dc83104:85,m2dc83105:84,m2dc83230:119,m2dc83810:94,m2dc85006:120,m2dc85101:89,m2dc85103:86,m2dc85104:90,m2dc85107:121,m2dc85108:122,m2dc85109:90,m2dc85111:82,m2dc85112:82,m2dc86001:79,m2dc86002:85,m2dc86006:82,m2dc86009:123,m2dc86101:85,m2dc86102:85,m2dc86728:95,m2dc89000:96,m2dc89001:79,m2dc89012:78,m2dc89015:124,m2dc89018:78,m2dc89020:125,m2dc89025:126,m2dc89026:127,m2dc8ab12:116,m35371022:63,m35371041:63,m35371046:63,m35371104:63,m358a0102:63,m358a0201:128,m358a0202:128,m358a0203:128,m358a0204:63,w00790002:129,w00790007:129,w0079000a:129,w00790016:18,w00790122:99,w00790126:130,w00791804:131,w0079181a:7,w0079181b:113,w00791824:132,w00791830:133,w00791845:11,w00791847:12,w0079184f:134,w00791879:135,w0079188f:136,w007918ae:137,w007918d4:138,w046dc209:139,w046dc20a:16,w046dc20b:140,w046dc211:141,w046dc21d:138,w046dc21e:142,w046dc242:142,w046dca84:143,w046dca88:143,w046dcad1:5,w046dcad2:7,w04b42410:144,w04b4c681:130,w054c05c5:145,w057e0330:146,w05ac022d:144,w05ac033d:147,w05ac044d:147,w05ac055b:39,w05ac057a:148,w0e6f0003:149,w0e6f0111:7,w0e6f0114:7,w0e6f0119:7,w0e6f011a:7,w0e6f011e:7,w0e6f011f:150,w0e6f0124:42,w0e6f0128:7,w0e6f012f:7,w0e6f0130:7,w0e6f0132:7,w0e6f0146:138,w0e6f0164:151,w0e6f0180:7,w0e6f0181:7,w0e6f0185:44,w0e6f0188:7,w0e6f0189:7,w0e6f0214:7,w0e6f0301:138,w0e6f1113:51,w0e6f6302:7,w0f0d0009:7,w0f0d000a:152,w0f0d000c:153,w0f0d000d:154,w0f0d0010:155,w0f0d0011:57,w0f0d0013:155,w0f0d001b:152,w0f0d0021:155,w0f0d0022:54,w0f0d0025:42,w0f0d0026:155,w0f0d0027:42,w0f0d0032:155,w0f0d003d:156,w0f0d0040:157,w0f0d0042:155,w0f0d0049:7,w0f0d004b:155,w0f0d0051:155,w0f0d0054:7,w0f0d0055:8,w0f0d005b:113,w0f0d005c:7,w0f0d0064:155,w0f0d0067:70,w0f0d006a:8,w0f0d006b:7,w0f0d006f:158,w0f0d0070:57,w0f0d007b:155,w0f0d008a:8,w0f0d008b:7,w0f0d008c:138,w0f0d009c:8,w0f0d00a0:159,w0f0d00a5:160,w0f0d00a6:111,w0f0d00ad:161,w0f0d00ae:142,w0f0d00af:162,w0f0d00c0:138,w0f0d00c9:5,w0f0d00d8:163,w0f0d00dc:138,w0f0d0101:5,w0f0d0104:142,w0f0d0123:144,w0f0d0137:164,w0f0d0162:165,w0f0d0164:166,w0f0d0196:134,w0f0d0202:167,w0f0d1011:168,w153202a6:169,w15320300:170,w15320707:147,w15320a14:138,w15321004:145,w15321007:145,w15321009:145,w1532100a:5,w18d12c40:171,w20d60060:7,w20d60dad:142,w20d6319f:7,w20d64026:134,w20d64033:134,w20d6571d:7,w20d6576d:7,w20d65795:7,w20d657c7:7,w20d657e5:7,w20d689e5:172,w20d6a712:7,w20d6a713:7,w20d6a714:7,w20d6a720:7,w24c6531a:153,w24c65b02:138,w27f80bbf:173,w28de11fc:70,w28de11ff:174,w2dc802e0:175,w2dc81003:176,w2dc81080:176,w2dc82100:144,w2dc82810:177,w2dc82862:78,w2dc83000:78,w2dc83001:178,w2dc8301c:134,w2dc8310a:134,w2dc83820:179,w2dc85001:180,w2dc86000:79,w2dc86003:123,w2dc86012:134,w2dc86100:85,w2dc86103:123,w2dc8ab11:179,w2dc8ab20:178,w2dc8ab21:78,w35371004:138,w35371007:134,w35371094:134,w35371116:134},$a=e=>e.toLowerCase().padStart(4,`0`);function eo(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:$a(t[2]),product:$a(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:$a(n[1]),product:$a(n[2]),name:n[3].trim()}:null}function to(e){return(eo(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function no(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function ro(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Qa[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Za[n]??null}return null}function io(e){return e.mapping!==`standard`&&eo(e.id)?.vendor===`2dc8`}var ao={6003:`switch`,6006:`switch`,6103:`switch`,3010:`switch`,6001:`startx`,6002:`startx`,6101:`startx`,6102:`startx`,3011:`receiver`,3012:`receiver`,3013:`receiver`,3015:`receiver`,3016:`receiver`,3017:`receiver`,"301b":`receiver`,"301c":`receiver`,"301d":`receiver`,6012:`receiver`,5112:`none`,9020:`none`};function oo(e){let t=eo(e);return t&&ao[t.product]||`manual`}var so={1:0,2:2,4:4,8:6};function co(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function lo(e,t,n){let{n:r,hat:i}=co(t),a=Ia.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function uo(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=so[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function fo(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function po(e,t,n){let r=e.split(`,`),i=lo(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&_o(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(_o)}function yo(){try{let e=Lt(go),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>vo(e[1])))}catch{return{}}}function bo(e,t){let n=yo();return t?n[e]=t:delete n[e],It(go,JSON.stringify(n)),xo=n,n}var xo=null;function So(e){return xo??=yo(),xo[e.id]??To(xo,e.id)??ho(e)??Ua(e)}function Co(e){return xo??=yo(),xo[e.id]?`saved`:e.mapping===`standard`?`standard`:ho(e)?`known`:`guess`}function wo(e){return ho(e)??Ua(e)}function To(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(xo=bo(t,e[i]),e[i]):null}function Eo(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Do(e,t){let n=null;if(t.buttons.forEach((t,r)=>{let i=t-(e.buttons[r]??0);t>.5&&i>.5&&(!n||i>n.amount)&&(n={src:{b:r},amount:i})}),n)return n.src;for(let n=0;n1.05?La(t.axes[n]):null;if(r!==null)return{h:n,at:r}}return t.axes.forEach((t,r)=>{let i=e.axes[r]??0,a=t-i;if(!(Math.abs(a)<.6)&&(!n||Math.abs(a)>n.amount)){let e=a>0?1:-1;n={src:Math.abs(i)>.5?{a:r,d:e,rest:i}:{a:r,d:e},amount:Math.abs(a)}}}),n?n.src:null}function Oo(e,t){let n=null;if(t.axes.forEach((t,r)=>{let i=t-(e.axes[r]??0);Math.abs(i)>=.6&&(!n||Math.abs(i)>Math.abs(n.moved))&&(n={a:r,moved:i})}),!n)return null;let r=n;return r.moved>0?{a:r.a}:{a:r.a,inv:!0}}var ko=[{kind:`button`,bit:R.CROSS,name:`✕`},{kind:`button`,bit:R.CIRCLE,name:`○`},{kind:`button`,bit:R.SQUARE,name:`□`},{kind:`button`,bit:R.TRIANGLE,name:`△`},{kind:`button`,bit:R.UP,name:`↑`},{kind:`button`,bit:R.DOWN,name:`↓`},{kind:`button`,bit:R.LEFT,name:`←`},{kind:`button`,bit:R.RIGHT,name:`→`},{kind:`button`,bit:R.L1,name:`L1`},{kind:`button`,bit:R.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:R.L3,name:`L3`},{kind:`button`,bit:R.R3,name:`R3`},{kind:`button`,bit:R.OPTIONS,name:`Options`},{kind:`button`,bit:R.SHARE,name:`Create`},{kind:`button`,bit:R.PS,name:`PS`},{kind:`button`,bit:R.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}];function Ao(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function jo(e,t,n){return t.kind===`button`?{...e,buttons:[...e.buttons.filter(([e])=>e!==t.bit),[t.bit,n]]}:(t.kind,{...e,[t.which]:n})}function Mo(e,t=Va){let n=new Set(e.buttons.map(([e])=>e)),r=e=>`b`in e?`b${e.b}`:`h`in e?`h${e.h}.${e.at}`:`a${e.a}${e.d}`,i=new Set([...e.buttons.map(([,e])=>r(e)),...[e.l2,e.r2].filter(e=>!!e).map(r)]);return{buttons:[...e.buttons,...t.buttons.filter(([e,t])=>!n.has(e)&&!i.has(r(t)))],l2:e.l2??t.l2,r2:e.r2??t.r2,lx:e.lx??t.lx,ly:e.ly??t.ly,rx:e.rx??t.rx,ry:e.ry??t.ry}}var No=ko.filter(e=>e.kind!==`button`||![R.L3,R.R3,R.OPTIONS,R.SHARE,R.PS,R.TOUCHPAD].includes(e.bit));function Po(e,t){return t.buttons.every((t,n)=>Math.abs(t-(e.buttons[n]??0))<.3)&&t.axes.every((t,n)=>Math.abs(t-(e.axes[n]??0))<.3)}var Fo=class{constructor(e=ko){this.steps=e,this.step=0,this.prof=Ao(),this.rest=null,this.waiting=!0}get done(){return this.step>=this.steps.length}get current(){return this.steps[this.step]??null}feed(e){if(this.done)return!1;if(!this.rest)return this.rest=e,this.waiting=!1,!1;if(this.waiting)return Po(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Oo(this.rest,e):Do(this.rest,e);return n?(this.prof=jo(this.prof,t,n),this.go(this.step+1),!0):!1}skip(){this.go(this.step+1)}back(){this.step>0&&this.go(this.step-1)}go(e){this.waiting=!0,this.step=Math.min(e,this.steps.length)}profile(e=Va){return Mo(this.prof,e)}};function Io(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}function Lo(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Ro=e=>`ps5upload.join.token.${e??`app`}`,zo=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...ja},this.lastSent=0,this.neutral=!1,this.stopped=!1,this.attempt=0,this.deadline=0,this.raf=0,this.keepalive=null,this.pinger=null,this.retry=null,this.lastHeard=0,this.hostAway=!1,this.pings=0,this.now=e.now??(()=>Date.now()),this.storage=e.storage===void 0?Lo():e.storage,this.WS=e.WebSocketImpl??WebSocket,this.seq=this.now()>>>0;try{this.token=this.storage?.getItem(this.key)??null}catch{this.token=null}}get key(){return Ro(this.o.invite??this.o.code??null)}get current(){return this.stage}get socket(){return this.ws}get resumeToken(){return this.token}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.stopped=!1,this.setStage({kind:`connecting`}),this.connect(),this.stopped)return;let e=()=>{this.sendPad(!1),this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e)};this.raf=(this.o.raf??(e=>window.requestAnimationFrame(e)))(e),this.keepalive=setInterval(()=>this.sendPad(!1),100),this.pinger=setInterval(()=>this.ping(),1e3)}connect(){let e;try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,e.onopen=()=>{if(this.ws!==e)return;this.lastHeard=this.now();let t={name:this.o.name};this.o.invite&&(t.invite=this.o.invite),this.o.code&&(t.code=this.o.code),this.token&&(t.resume=this.token),e.send(JSON.stringify({hello:t}))},e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),typeof t.data==`string`?this.onText(t.data):t.data instanceof ArrayBuffer&&this.stage.kind===`joined`&&this.o.onFrame?.(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Ue(t);n===`mismatch`?(this.forgetToken(),this.finish({kind:`ended`,why:n})):n&&this.stage.kind!==`joined`&&this.stage.kind!==`reconnecting`?this.finish({kind:`ended`,why:n}):this.dropped()},e.onerror=()=>{}}onText(e){let t=Je(e);if(t)switch(t.kind){case`pong`:{let e=this.now()-t.t;e>=0&&e<6e4&&this.o.onRtt?.(e);return}case`asking`:this.stage.kind!==`reconnecting`&&this.setStage({kind:`asking`});return;case`waiting`:this.hostAway||(this.hostAway=!0,this.deadline=this.now()+et),this.attempt=0,this.setStage(this.reconnectingStage());return;case`joined`:this.token=t.token,this.player=t.player,this.attempt=0,this.hostAway=!1;try{this.storage?.setItem(this.key,t.token)}catch{}{let e=t.track&&this.ws?.media||null;this.o.onCodec?.(t.hevc,e,!!e&&t.audio&&!!e.audio)}this.setStage({kind:`joined`,player:t.player,hevc:t.hevc}),this.sendPad(!0);return;case`refused`:this.forgetToken(),this.hostAway&&t.why!==`seat_taken`?this.finish({kind:`ended`,why:`host_stopped`}):this.finish({kind:`refused`,why:t.why});return;case`bye`:if(t.why===`host_stopped`&&this.token){this.hostWait();return}this.forgetToken(),this.finish({kind:`ended`,why:t.why});return;case`status`:this.stage.kind===`joined`&&t.status.player>0&&t.status.player!==this.stage.player&&(this.player=t.status.player,this.setStage({...this.stage,player:t.status.player})),this.o.onStatus?.(t.status);return;case`feedback`:t.rumble&&this.o.onRumble?.(t.rumble[0],t.rumble[1]),t.light&&this.o.onLight?.(t.light);return}}hostWait(){this.hostAway=!0,this.deadline=this.now()+et,this.attempt=0;let e=this.ws;this.ws=null;try{e?.close()}catch{}this.scheduleRetry()}reconnectingStage(){return{kind:`reconnecting`,player:this.player,attempt:this.attempt,deadline:this.deadline,...this.hostAway?{hostStopped:!0}:{}}}giveUp(){this.forgetToken(),this.finish({kind:`ended`,why:this.hostAway?`host_stopped`:`gave_up`})}dropped(){if(this.stopped)return;let e=this.stage;e.kind===`joined`||e.kind===`reconnecting`&&this.token?(e.kind===`joined`&&(this.deadline=this.now()+$e),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Qe(this.attempt);this.setStage(this.reconnectingStage()),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.stopped||(this.now()>=this.deadline?this.giveUp():this.connect())},e)}forgetToken(){this.token=null;try{this.storage?.removeItem(this.key)}catch{}}ping(){if(this.hostAway&&!this.stopped&&this.now()>=this.deadline+5e3||!this.stopped&&this.stage.kind===`reconnecting`&&this.now()>=this.deadline+5e3){this.giveUp();return}let e=this.ws;if(e&&e.readyState===this.WS.OPEN){if(this.stage.kind===`joined`&&this.now()-this.lastHeard>3500){this.ws=null;try{e.close()}catch{}this.dropped()}else if(e.send(JSON.stringify({ping:this.now()})),this.stage.kind===`joined`&&this.o.readStats&&++this.pings%2==0){let t=this.o.readStats();t&&e.send(JSON.stringify({stats:t}))}}}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.sendPad(!0))}sendPad(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||this.stage.kind!==`joined`)return;let n=this.neutral?{...ja,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Io(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Ze(this.seq,n)))}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.pinger&&clearInterval(this.pinger),this.retry&&clearTimeout(this.retry),this.keepalive=this.pinger=this.retry=null}finish(e){this.stopped=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&e.send(JSON.stringify({keyframe:!0}))}leave(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&(this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),e.send(JSON.stringify({leave:1}))),this.forgetToken(),this.finish({kind:`ended`,why:`left`})}stop(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&this.stage.kind===`joined`&&(this.seq=this.seq+1>>>0,e.send(Ze(this.seq,ja))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},Bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),z=s(((e,t)=>{t.exports=Bo()}))(),Vo=`ps5upload.openIn`,Ho=`ps5upload.openIn.tab`;function Uo(){try{return sessionStorage.getItem(Ho)===`browser`}catch{return!1}}function B(){try{sessionStorage.setItem(Ho,`browser`)}catch{}}function V(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Wo({appLink:e,children:t}){let n=Ie(),[r,i]=(0,D.useState)(()=>Uo()?`browser`:V(Lt(Vo))),[a,o]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,z.jsx)(z.Fragment,{children:t});let s=()=>{a&&It(Vo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?It(Vo,`browser`):r===`opening`&&Lt(`ps5upload.openIn`)===`app`&&Rt(Vo),B(),i(`browser`)};return(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,z.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,z.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`space-y-1`,children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}var Go=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type='hidden'])`,`select:not([disabled])`,`textarea:not([disabled])`,`summary`,`[contenteditable='true']`,`[tabindex]`].map(e=>`${e}:not([tabindex='-1'])`).join(`, `),Ko=new Set,qo=[];function Jo(){for(let e of Ko)e()}function Yo(){return qo.length}function Xo(e){return qo.push(e),Jo(),()=>{let t=qo.lastIndexOf(e);t!==-1&&qo.splice(t,1),Jo()}}function Zo(e,t,n){switch(n){case`down`:return t.top-e.bottom;case`up`:return e.top-t.bottom;case`right`:return t.left-e.right;case`left`:return e.left-t.right}}function H(e,t,n){let r=(e.left+e.right)/2,i=(e.top+e.bottom)/2,a=(t.left+t.right)/2,o=(t.top+t.bottom)/2;switch(n){case`down`:return o>i&&t.top>=e.top+1;case`up`:return or&&t.left>=e.left+1;case`left`:return a0?{gap:0,overlap:c}:{gap:-c,overlap:0}}function $o(e,t,n){let r=null,i=1/0,a=!1;for(let o of t){if(!H(e,o.rect,n))continue;let t=Math.max(0,Zo(e,o.rect,n)),s=Qo(e,o.rect,n),c=s.overlap>0;if(a&&!c)continue;let l=c?t-s.overlap/1e6:Math.hypot(t,2*s.gap);(c&&!a||l`u`?void 0:window){try{return!!e?.PS5UploadTv?.isTv()}catch{return!1}}function rs(e=typeof document>`u`?void 0:document){return e?.documentElement.dataset.tv===`1`}function is(e,t){if(!e)return!1;if(e.closest(`[data-own-arrows]`))return!0;let n=e.tagName;if(n===`TEXTAREA`||e.isContentEditable)return!0;let r=t===`left`||t===`right`;if(n===`INPUT`){let t=(e.type||`text`).toLowerCase();if(t===`range`||ts.test(t))return r}return!1}var as=`[aria-modal="true"], [role="dialog"], [role="alertdialog"]`;function os(e){let t=e.activeElement?.closest(as);if(t)return t;if(Yo()>0){let t=e.querySelectorAll(as);if(t.length)return t[t.length-1]}return e}function ss(e){let t=[];return e.querySelectorAll(Go).forEach(e=>{if(e.closest(`[inert], [aria-hidden='true']`)||e.disabled)return;let n=e.getBoundingClientRect();n.width<=0||n.height<=0||t.push({el:e,rect:n})}),t}function cs(e){return(e.find(e=>e.el.getAttribute(`aria-current`)===`page`)??e[0])?.el??null}function ls(e,t=document){let n=es[e.key];if(!n||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return!1;let r=t.activeElement;if(is(r,n))return!1;let i=ss(os(t));if(!i.length)return!1;let a=i.find(e=>e.el===r),o=a?$o(a.rect,i.filter(e=>e!==a),n):cs(i);return o?(e.preventDefault(),o.focus(),typeof o.scrollIntoView==`function`&&o.scrollIntoView({block:`nearest`,inline:`nearest`}),!0):!1}var us=!1;function ds(e){us||(us=!0,e.addEventListener(`keydown`,t=>void ls(t,e.document)))}function fs(e=typeof window>`u`?void 0:window){e&&(ns(e)&&(e.document.documentElement.dataset.tv=`1`),ds(e))}function ps({id:e,className:t}){let n=Ie(),r=oo(e);if(r===`none`)return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_no_xinput`,void 0,`This 8BitDo has no X-input mode. If a button is wrong, check the controller.`)});let i=r===`switch`?n(`pad_8bitdo_how_switch`,void 0,`set the switch on the back to X, then press Start`):r===`startx`?n(`pad_8bitdo_how_startx`,void 0,`turn it off, then hold Start + X to turn it on`):r===`receiver`?n(`pad_8bitdo_how_receiver`,void 0,`use its 2.4G receiver or a USB cable`):n(`pad_8bitdo_how_manual`,void 0,`its manual says how`);return(0,z.jsx)(`span`,{className:t,"data-testid":`pad-8bitdo-hint`,"data-how":r,children:n(`pad_8bitdo_xinput`,{how:i},`For the best result, switch your 8BitDo to X-input mode: ${i}.`)})}var ms=new Set,hs={held:new Set,touch:null,touchPad:ja,mapping:!1,get paused(){return ms.size>0},motion:null},gs={s:.85,m:1,l:1.15},_s=.25;function vs(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(_s,e))}var ys={overlay:{width:844,height:390},deck:{width:390,height:480}},bs=.7,xs=1.4;function Ss(e,t,n,r){let i=gs[e]??1;if(!(t>0)||!(n>0))return i;let a=r?ys.deck:ys.overlay,o=Math.min(xs,Math.max(bs,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var Cs=34;function ws(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+Cs>t}function Ts(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var Es=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,Ds=32767,Os=12;function ks({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Ie(),s=(0,D.useRef)(new Map),c=(0,D.useRef)({...ja}),[l,u]=(0,D.useState)({...ja}),[d,f]=(0,D.useState)({l:!1,r:!1,touchpad:!1}),p=(0,D.useRef)(null),[m,h]=(0,D.useState)({width:0,height:0});(0,D.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,D.useEffect)(()=>()=>{hs.touchPad={...ja}},[]);let g=()=>{let t={...ja,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=R.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,hs.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*Ds),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*Ds)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ma((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ma((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Os&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,C=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,w=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,T={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},E=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),te=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ne={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},re=(e,t,n,r)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${te} ${n}`,style:ne,children:r}),ie=(e,t,n,r)=>(0,z.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${w} ${C(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),ae=(e,t,n,r)=>re(e,t,`h-[44px] w-[84px]`,ie(e,ee(t),n,r)),oe=(e,t,n)=>(0,z.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${te} h-[44px] w-[84px]`,style:ne,children:ie(e,l[t]>0,n,!0)}),se=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:(0,z.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...E(ee(t)),children:[(0,z.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,z.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ce=(e,t,n)=>re(e,t,`h-[52px] w-[52px]`,(0,z.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:T,children:[(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...E(ee(t))}),(0,z.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),le=(e,t)=>re(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,z.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${w} ${C(ee(t))}`,children:e})),ue=(e,t)=>re(e,t,`h-[44px] w-[44px]`,(0,z.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),de=e=>{let{dx:t,dy:n}=Ts(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,z.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,z.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${C(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},O=t===`deck`,fe=Ss(r,m.width,m.height,O),pe=e=>`${e}px * var(--k)`,k=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=O?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${pe(t)}, ${n}px))`:`calc(${e} + ${pe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=O&&ws(fe,m.height),A=O?void 0:`58%`,j=e=>O?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?k:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?k:me},xe=e=>({bottom:be?he:_e(he,O?56:0,44),[e]:be?`calc(${e===`left`?k:me} + 8px + max(${pe(80)}, 44px))`:_e(e===`left`?k:me,O?40:168)}),Se=!!a&&!O;return(0,z.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${O?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:O?i:void 0,"--k":fe},"data-testid":`rp-touch`,"data-layout":t,"data-scale":fe,onContextMenu:e=>e.preventDefault(),children:[(0,z.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:vs(n)},children:[(0,z.jsx)(`div`,{style:ye(`top left`,{top:ge,left:k}),children:(0,z.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:O?void 0:`6deg`,transformOrigin:`top left`},children:[oe(`L2`,`l2`,`l`),ae(`L1`,R.L1,`l`,!1)]})}),(0,z.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,z.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:O?void 0:`-6deg`,transformOrigin:`top right`},children:[oe(`R2`,`r2`,`r`),ae(`R1`,R.R1,`r`,!1)]})}),(0,z.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:O?{top:_e(ge,6),left:_e(k,104),right:_e(me,104),height:`max(44px, calc(${pe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${pe(250)}), 34vw)`,height:`max(44px, calc(${pe(56)}))`}}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top left`:`left center`,j(`left`)),children:[(0,z.jsx)(`span`,{}),se(`↑`,R.UP,0),(0,z.jsx)(`span`,{}),se(`←`,R.LEFT,-90),(0,z.jsx)(`span`,{}),se(`→`,R.RIGHT,90),(0,z.jsx)(`span`,{}),se(`↓`,R.DOWN,180),(0,z.jsx)(`span`,{})]}),(0,z.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(O?`top right`:`right center`,j(`right`)),children:[(0,z.jsx)(`span`,{}),ce(`△`,R.TRIANGLE,(0,z.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,z.jsx)(`span`,{}),ce(`□`,R.SQUARE,(0,z.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,z.jsx)(`span`,{}),ce(`○`,R.CIRCLE,(0,z.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,z.jsx)(`span`,{}),ce(`✕`,R.CROSS,(0,z.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,z.jsx)(`span`,{})]}),(0,z.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:de(`l`)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:de(`r`)}),(0,z.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:k}),children:le(`Create`,R.SHARE)}),(0,z.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:le(`Options`,R.OPTIONS)}),(0,z.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:Es,translate:`-50% 0`}),children:ue(`PS`,R.PS)})]}),Se&&(0,z.jsx)(`div`,{style:{...ye(`bottom center`,{bottom:he,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,vs(n))},children:(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${te} h-[44px] w-[56px]`,style:ne,"data-testid":`rp-menu-handle`,children:(0,z.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,z.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var As=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,js=null,Ms=null;function Ns(e){e.play().catch(()=>{if(Ms||js!==e)return;let t=()=>{Ps(),js===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),Ms=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Ps(){Ms?.(),Ms=null}function Fs(){if(typeof document<`u`){if(!js){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=As,document.body.appendChild(e),js=e}Ns(js)}}function Is(){Ps(),js&&=(js.pause(),js.removeAttribute(`src`),js.remove(),null)}function Ls(){return typeof navigator>`u`?null:navigator.wakeLock??null}function Rs(){return dt()||!Pn()}var zs=new Set,Bs=null,Vs=Promise.resolve(),Hs=!1;async function Us(){if(zs.size===0||Bs&&!Bs.released)return;let e=Ls();if(!e)dt()&&Fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{Bs===t&&(Bs=null)}),Bs=t}catch{}}async function Ws(){Is();let e=Bs;if(Bs=null,e&&!e.released)try{await e.release()}catch{}}function Gs(){Hs||typeof document>`u`||(Hs=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&zs.size>0&&(Vs=Vs.then(Us))}))}function Ks(e,t){if(!Rs())return;Gs();let n=zs.size>0;t?zs.add(e):zs.delete(e);let r=zs.size>0;n!==r&&(Vs=Vs.then(r?Us:Ws))}var qs=new Set;function Js(){if(typeof window<`u`)return window.PS5UploadPad}function Ys(e,t){let n=qs.size>0;t?qs.add(e):qs.delete(e);let r=qs.size>0;if(n!==r)try{Js()?.setActive(r)}catch{}}var Xs=class e{constructor(e){this.receiver=e,this.last=null,this.was={}}get frames(){return Number(this.last?.frames??0)}static report(e,t){let n=t=>e[t]??0,r=e=>n(e)-(t[e]??0),i=(e,t)=>r(t)>0?Math.round(r(e)/r(t)*1e4)/10:0;return{frames:n(`framesDecoded`),dropped:n(`framesDropped`),stalls:n(`freezeCount`),stall_ms:Math.round(n(`totalFreezesDuration`)*1e3),decode_ms:i(`totalDecodeTime`,`framesDecoded`),jitter_ms:i(`jitterBufferDelay`,`jitterBufferEmittedCount`),nacks:n(`nackCount`),plis:n(`pliCount`),decoder:`track`}}snapshot(){return this.receiver.getStats().then(t=>{t.forEach(t=>{t.type===`inbound-rtp`&&t.kind===`video`&&(this.last=e.report(t,this.was),this.was={...t})})}).catch(()=>{}),this.last}},Zs=class{constructor(e){this.inner=e,this.video=document.createElement(`video`),this.wrap=document.createElement(`div`),this.media=null,this.trackStats=null,this.audio=!1,this.soundOn=!1,this.muted=!1;let t=this.video;t.muted=t.autoplay=t.playsInline=!0,t.className=`block h-full w-full object-contain`,t.dataset.testid=`track-video`,this.wrap.className=`h-full w-full`,this.wrap.append(t,e.element),this.setTrack(null)}get element(){return this.wrap}get stats(){return this.trackStats??this.inner.stats}setTrack(e,t=!1){this.media=e,this.audio=!!e&&t,this.applySound(),this.trackStats=e?new Xs(e.receiver):null,this.video.style.display=e?``:`none`,this.inner.element.style.display=e?`none`:``,this.video.srcObject!==(e?.stream??null)&&(this.video.srcObject=e?.stream??null),e&&this.play()}play(){try{this.video.play()?.catch?.(()=>{})}catch{}}onMessage(e){let t=new Uint8Array(e)[0];this.media&&t<=1||(!this.audio||t!==3&&t!==4)&&this.inner.onMessage(e)}applySound(){this.video.muted=!(this.audio&&this.soundOn&&!this.muted)}setHevc(e){this.inner.setHevc(e)}set onSoundFail(e){this.inner.onSoundFail=e}soundReport(){return this.inner.soundReport()}startSound(){this.inner.startSound(),this.soundOn=!0,this.applySound(),this.media&&this.play()}setMuted(e){this.inner.setMuted(e),this.muted=e,this.applySound()}resumeSound(){this.inner.resumeSound(),this.media&&this.video.paused&&this.play()}stop(){this.inner.stop(),this.video.srcObject=null}},Qs=`ps5upload.join.muted`,$s=5e3,ec=Object.fromEntries(Object.entries(Na).filter(([e])=>e!==`Escape`)),tc=new Set;function nc(e){if(!(e.code in ec)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||rc(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||rc(t))}function rc(e){let t=e?.tagName;if(t===`BUTTON`||t===`A`)return!0;let n=e?.getAttribute?.(`role`);return n===`button`||n===`link`||n===`menuitem`||n===`tab`||n===`switch`}var ic=!1;function ac(e){ic=e}function oc(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function sc(){if(ic)return{...ja};let e=Ga(Xa(typeof navigator>`u`?void 0:navigator),So),t=hs.touchPad;return{...Ka(Ka(e,Fa(tc,ec)),t),touch:t.touch??null,motion:hs.motion??null}}var cc=class{constructor(e){this.opts=e,this.player=null,this.listeners=new Set,this.cleanups=[],this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.snap={stage:{kind:`connecting`},status:null,rttMs:null,light:null,problem:null,sound:!1,noSound:!1,host:e.host,muted:uc(),path:null},this.client=new zo({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:sc,onStage:e=>{this.set({stage:e}),e.kind===`joined`&&this.readPath(),(e.kind===`refused`||e.kind===`ended`)&&this.teardown()},onStatus:e=>this.set({status:e,host:e.host??this.snap.host}),onRtt:e=>this.set({rttMs:e}),onFrame:e=>this.picture().onMessage(e),readStats:()=>oc(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Zs&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Xa(typeof navigator>`u`?void 0:navigator);qa(n,e,t),n.some(e=>e?.connected)||navigator.vibrate?.(e||t?200:0)},onLight:e=>this.set({light:e})})}picture(){if(!this.player){let e=oa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Zs(e):e,this.player.onSoundFail=()=>this.set({noSound:!0}),this.player.setMuted(this.snap.muted)}return this.player}async readPath(){let e=this.client.socket,t=this.opts.path??null;if(e?.netPath)try{t=await e.netPath()??this.opts.path??null}catch{t=null}t!==this.snap.path&&this.set({path:t})}get element(){return this.picture().element}start(){let e=()=>{document.visibilityState===`hidden`?tc.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{tc.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&nc(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),tc.add(e.code))},r=e=>{tc.delete(e.code)&&nc(e)&&e.preventDefault()};window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r);let i=()=>{this.client.setNeutral(document.visibilityState===`hidden`),document.visibilityState!==`hidden`&&this.player?.resumeSound()};document.addEventListener(`visibilitychange`,e),window.addEventListener(`blur`,t),window.addEventListener(`focus`,i);let a=setInterval(()=>{this.client.current.kind===`joined`&&this.readPath()},$s);this.cleanups.push(()=>{clearInterval(a),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`blur`,t),window.removeEventListener(`focus`,i),window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),tc.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(Qs,e?`1`:`0`)}catch{}this.set({muted:e})}startSound(){this.snap.sound||(this.picture().startSound(),this.set({sound:!0}))}leave(){this.client.leave(),this.teardown()}stop(){this.client.stop(),this.teardown()}teardown(){for(let e of this.cleanups.splice(0))e();hs.touchPad={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};let e=this.player;this.player=null,e&&(e.stop(),e.element.remove())}sendPad(){this.client.sendPad(!1)}get snapshot(){return this.snap}set(e){this.snap={...this.snap,...e};for(let e of this.listeners)e()}};function lc(e){return(0,D.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function uc(){try{return typeof localStorage<`u`&&localStorage.getItem(Qs)===`1`}catch{return!1}}function dc(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Ks(`play-together`,n),Ys(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Ks(`play-together`,!1),Ys(`play-together`,!1)}}var fc=3e3,pc=class{constructor(e,t=fc){this.onChange=e,this.delay=t,this.enabled=!1,this.pinned=!1,this.sticky=!1,this.shown=!0,this.timer=null}get visible(){return!this.enabled||this.pinned||this.shown}set(e,t,n=!1){let r=this.enabled&&!this.pinned,i=this.enabled,a=this.sticky;this.enabled=e,this.pinned=t,this.sticky=n,!e||t?(this.stop(),this.show(!0)):n?(this.stop(),!i||!a?this.show(!1):r||this.show(!0)):(!r||a)&&(this.show(!0),this.arm())}poke(){this.show(!0),this.enabled&&!this.pinned&&!this.sticky&&this.arm()}toggle(){this.visible?this.hide():this.poke()}hide(){this.enabled&&!this.pinned&&(this.stop(),this.show(!1))}dispose(){this.stop()}arm(){this.stop(),this.timer=setTimeout(()=>{this.timer=null,this.show(!1)},this.delay)}stop(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}show(e){this.shown!==e&&(this.shown=e,this.onChange(e))}};function mc(e,t,n=!1){let[r,i]=(0,D.useState)(!0),a=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=new pc(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,D.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,D.useCallback)(()=>a.current?.poke(),[]),s=(0,D.useCallback)(()=>a.current?.hide(),[]),c=(0,D.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var hc=3e4,gc=class{constructor(e,t=hc){this.onChange=e,this.ms=t,this.picking=!1,this.over=!1,this.timer=null}get shown(){return this.picking&&!this.over}set(e){e!==this.picking&&(this.picking=e,this.over=!1,this.stop(),e&&(this.timer=setTimeout(()=>{this.timer=null,this.over=!0,this.onChange()},this.ms)))}stop(){this.timer&&clearTimeout(this.timer),this.timer=null}reset(){this.stop(),this.picking=!1,this.over=!1}};function _c(e){let[,t]=(0,D.useState)(0),[n]=(0,D.useState)(()=>new gc(()=>t(e=>e+1)));return(0,D.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,D.useEffect)(()=>()=>n.reset(),[n]),n.shown}var vc=()=>Xa(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function yc(e,t){if(t.kind===`axis`)return t.which===`lx`?e(`rp_pad_step_lx`,void 0,`Push the left stick right`):t.which===`ly`?e(`rp_pad_step_ly`,void 0,`Push the left stick down`):t.which===`rx`?e(`rp_pad_step_rx`,void 0,`Push the right stick right`):e(`rp_pad_step_ry`,void 0,`Push the right stick down`);if(t.kind===`button`){if(t.bit===R.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===R.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===R.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===R.TRIANGLE)return e(`join_check_top`,void 0,`Press the top face button (△)`)}return e(`rp_pad_press`,{name:t.name},`Press ${t.name}`)}function bc(e,t){let n=(0,D.useRef)(t);(0,D.useEffect)(()=>{n.current=t}),(0,D.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(vc().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var xc=[[R.CROSS,`✕`],[R.CIRCLE,`○`],[R.SQUARE,`□`],[R.TRIANGLE,`△`],[R.UP,`↑`],[R.DOWN,`↓`],[R.LEFT,`←`],[R.RIGHT,`→`],[R.L1,`L1`],[R.R1,`R1`],[R.L3,`L3`],[R.R3,`R3`],[R.SHARE,`Create`],[R.OPTIONS,`Options`],[R.PS,`PS`],[R.TOUCHPAD,`Touchpad`]];function Sc({pad:e}){let t=e=>`flex h-8 min-w-8 items-center justify-center rounded-md px-1.5 text-xs font-medium ${e?`bg-white text-black`:`bg-white/10 text-white/70`}`,n=(e,t,n)=>(0,z.jsxs)(`span`,{className:`relative flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-[10px] text-white/50`,children:[n,(0,z.jsx)(`span`,{className:`absolute h-3 w-3 rounded-full bg-white`,style:{left:`calc(50% + ${e/32767*18}px - 6px)`,top:`calc(50% + ${t/32767*18}px - 6px)`}})]});return(0,z.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[xc.map(([n,r])=>(0,z.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,z.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,z.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,z.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function Cc({onClose:e}){let t=Ie(),[n,r]=(0,D.useState)(()=>vc().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,D.useState)(()=>vc()[0]?.index??null),[o,s]=(0,D.useState)(ja),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(yo),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useRef)(null);(0,D.useEffect)(()=>(ac(!0),()=>ac(!1)),[]),(0,D.useEffect)(()=>{(v.current?.querySelector(`[data-testid="join-pad-learn-start"]`)??v.current?.querySelector(`[data-testid="join-pad-check-close"]`))?.focus({preventScroll:!0})},[]),(0,D.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||v.current?.querySelector(`button:not([disabled])`)?.focus({preventScroll:!0})},[c,u]),(0,D.useEffect)(()=>{let e=()=>{let e=vc();r(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n].id&&t.index===e[n].index)?t:e.map(e=>({index:e.index,id:e.id}))),a(t=>t!==null&&e.some(e=>e.index===t)?t:e[0]?.index??null)},t=window.setInterval(e,500);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(t),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),bc(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(Eo(e))&&y(c,e);return}let t=Ga([e],So);s(e=>e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry?e:t)});let y=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(bo(r,e.profile(n?wo(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},b=()=>{h(null),d(0),l(new Fo(No))},x=g,S=x?Co(x):null,ee=!!(x&&f[x.id]);return(0,z.jsx)(`div`,{ref:v,role:`dialog`,"aria-modal":`true`,"aria-label":t(`join_check_title`,void 0,`Check your controller`),className:`absolute inset-0 z-40 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm`,"data-testid":`join-pad-check`,onPointerDown:e=>e.stopPropagation(),children:(0,z.jsxs)(`div`,{className:`w-[min(26rem,100%)] space-y-3 rounded-2xl border border-white/10 bg-neutral-900/95 p-4 text-sm text-white shadow-2xl`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(me,{size:16,className:`text-white/70`}),(0,z.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t(`join_done`,void 0,`Done`),className:`flex h-8 w-8 items-center justify-center rounded-full bg-white/10 hover:bg-white/20`,"data-testid":`join-pad-check-close`,children:(0,z.jsx)(De,{size:15})})]}),x?(0,z.jsxs)(z.Fragment,{children:[n.length>1&&(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,z.jsx)(`button`,{type:`button`,disabled:!!c,onClick:()=>a(e.index),className:`rounded-full px-2.5 py-1 text-xs ${e.index===i?`bg-white text-black`:`bg-white/10`}`,children:to(e.id)},`${e.index}-${e.id}`))}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:to(x.id)}),(0,z.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":S??``,children:S===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):S===`guess`?t(`join_check_unknown`,void 0,`This controller isn't on our list, so its buttons may be mixed up. Setting it up takes a few seconds.`):t(`rp_pad_standard`,void 0,`Recognized`)}),io(x)&&(0,z.jsx)(ps,{id:x.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,z.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`rp_pad_progress`,{n:u+1,total:c.steps.length},`${u+1} of ${c.steps.length}`)}),(0,z.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?yc(t,c.current):``}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),y(c,x)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-learn-skip`,children:t(`rp_pad_skip`,void 0,`Skip`)}),u>0&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{c.back(),d(c.step)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,children:t(`rp_pad_back`,void 0,`Back`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>l(null),className:`rounded-full px-3 py-1.5 text-xs text-white/70 hover:bg-white/10`,children:t(`rp_pad_cancel`,void 0,`Cancel`)})]})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-xs text-white/60`,children:t(`join_check_try`,void 0,`Press buttons and move the sticks: what you press lights up.`)}),(0,z.jsx)(Sc,{pad:o}),m&&(0,z.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:b,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:ee?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),ee&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>{p(bo(x.id,null)),h(null)},className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-reset`,children:t(`rp_pad_reset`,void 0,`Reset`)}),(0,z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded-full bg-white/15 px-3 py-1.5 text-xs hover:bg-white/25`,"data-testid":`join-pad-check-done`,children:t(`join_done`,void 0,`Done`)})]})]})]}):(0,z.jsx)(`p`,{className:`text-white/70`,children:t(`rp_pads_none`,void 0,`No controller seen yet. Connect one and press any button on it.`)})]})})}function wc(e,t){let[n,r]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(!e||!t)return;let n=!0;return Be(e,Le).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function Tc({href:e}){let t=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,z.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function Ec(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var Dc=`ps5upload.join.guided`,Oc=1;function kc(e){return e.player!==Oc&&(!e.guided||e.movedOff)&&!e.reconnecting}function Ac(e,t){switch(t){case`lan`:return e(`join_path_lan`,void 0,`Home network`);case`tailscale`:return e(`join_path_tailscale`,void 0,`Tailscale`);default:return e(`join_path_internet`,void 0,`Internet`)}}function jc(e,t){return e(`join_seat_taken`,{host:t},`${t} needed their controller back and no other controller was free on the PS5, so you're out of the game. Ask ${t} to let you in again.`)}function Mc(e,t,n,r=!1){if(t.kind===`refused`)switch(t.why){case`key`:return e(`join_refused_key`,{host:n},`This invite has expired. Ask ${n} for a new link.`);case`expired`:return e(`join_refused_expired`,{host:n},`Your place in the game was lost. Ask ${n} to let you in again.`);case`full`:return e(`join_refused_full`,void 0,`The game is full: four players already.`);case`denied`:return e(`join_refused_denied`,{host:n},`${n} didn't let you in this time.`);case`no_answer`:return e(`join_refused_no_answer`,{host:n},`${n} didn't answer in time. Tell ${n}, then try again.`);case`closed`:return e(`join_refused_closed`,{host:n},`${n} isn't hosting Play Together right now.`);case`old_helper`:return e(`join_refused_old_helper`,{host:n},`${n}'s PS5 needs an updated helper for Play Together.`);case`not_playing`:return e(`join_refused_not_playing`,{host:n},`${n} isn't playing right now. Ask ${n} to start Play first.`);case`unreachable`:return e(`join_refused_unreachable`,{host:n},`${n}'s computer couldn't reach their PS5. Try again in a moment.`);case`slow_down`:return e(`join_refused_slow_down`,void 0,`Too many wrong codes. Wait a minute, then try again.`);case`address`:return e(`join_refused_address`,{host:n},`This link's address is outside your home network, so the app will not use it. Ask ${n} for a link with their computer's IP address.`);case`seat_taken`:return jc(e,n);default:return e(`join_refused_other`,{host:n},`${n} didn't let you in.`)}if(t.kind===`ended`)switch(t.why){case`kicked`:return e(`join_ended_kicked`,{host:n},`${n} took you out of the game.`);case`closed`:return e(`join_ended_closed`,{host:n},`${n} closed Play Together.`);case`host_stopped`:return e(`join_ended_host_stopped`,void 0,`The host stopped playing.`);case`replaced`:return e(`join_ended_replaced`,void 0,`This game was opened in another tab or on another device, so it stopped here.`);case`pad_lost`:return e(`join_ended_pad_lost`,{host:n},`The PS5 lost your controller, so you're out of the game. Ask ${n} to let you in again.`);case`gave_up`:return e(`join_ended_gave_up`,{host:n},`The connection to ${n} didn't come back in time.`);case`lost`:return r?e(`join_net_lost`,{host:n},`The connection to ${n} dropped. Check your internet connection, then ask again.`):e(`join_ended_lost`,{host:n},`Couldn't reach ${n}. Check that you're on the same network.`);case`left`:return e(`join_ended_left`,void 0,`You left the game.`);case`seat_taken`:return jc(e,n);case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`join_net_no_room`,{host:n},`This invite isn't open any more. Ask ${n} for a new link.`);case`net_full`:return e(`join_net_full`,{host:n},`${n}'s game has no room for another friend right now. Try again in a moment.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:return e(`join_net_offer`,{host:n},`${n}'s computer couldn't connect to this browser. Try another browser.`);case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`)}return``}function Nc(e){let[t,n]=(0,D.useState)(()=>Date.now());return(0,D.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function Pc(){let[e,t]=(0,D.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,D.useEffect)(()=>{let e=()=>{let e=Xa(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?sc():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?Co(e):null,s=!!e&&io(e);t(e=>e.ready===n&&e.pressed===i&&e.id===a&&e.kind===o&&e.weak8BitDo===s?e:{ready:n,pressed:i,id:a,kind:o,weak8BitDo:s})};e();let n=window.setInterval(e,120);return window.addEventListener(`gamepadconnected`,e),window.addEventListener(`gamepaddisconnected`,e),()=>{window.clearInterval(n),window.removeEventListener(`gamepadconnected`,e),window.removeEventListener(`gamepaddisconnected`,e)}},[]),e}function Fc(e){return!!e?.closest?.(`[data-testid="rp-touch"]`)}var Ic=14,Lc=()=>typeof window<`u`&&!rs()&&!!window.matchMedia?.(`(pointer: coarse)`).matches;function Rc(e,t,n){return!e||e===t||e.closest?.(`[data-join-game]`)?`game`:n?.contains(e)?`controls`:`page`}function zc(e){return e.checking?`close-check`:e.guide?`close-guide`:e.where===`game`?`show-controls`:e.full?`leave-full`:null}var Bc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function Vc({text:e,body:t,onCancel:n}){let r=Ie();return(0,z.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,z.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,z.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,z.jsx)(Se,{size:26})})]}),(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,z.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!0,className:`rounded-full bg-white/15 px-4 py-2 text-sm hover:bg-white/25`,"data-testid":`join-cancel`,children:r(`join_cancel`,void 0,`Cancel`)})]})}function Hc({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Ie(),c=lc(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,D.useRef)(null),p=(0,D.useRef)(null),m=(0,D.useRef)(null),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(()=>Lt(Dc)===`1`),[y,b]=(0,D.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),x=Pc(),[S,ee]=(0,D.useState)(!1),C=l.kind===`reconnecting`,w=Nc(C),T=l.kind===`joined`||C,E=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[ne,re]=(0,D.useState)(!1),ie=(0,D.useRef)(te);(0,D.useEffect)(()=>{ie.current===Oc&&te>Oc&&re(!0),te&&(ie.current=te)},[te]);let[ae,oe]=(0,D.useState)(!1),[se,ce]=(0,D.useState)(!1),le=T&&(h||!t),de=Lc(),fe=_c(E),k=mc(le,C||fe&&!de||ae||se,de),{poke:he}=k,_e=(0,D.useRef)(null),ve=()=>{_e.current&&clearTimeout(_e.current.timer),_e.current=null};(0,D.useEffect)(()=>ve,[]);let[ye,A]=(0,D.useState)(!1),xe=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(!le||!de||k.shown||!_||xe.current)return;xe.current=!0,A(!0);let e=setTimeout(()=>A(!1),6e3);return()=>clearTimeout(e)},[le,de,k.shown,_]),(0,D.useEffect)(()=>{if(!T)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[T,e]),(0,D.useEffect)(()=>{if(!T||c.sound)return;let t=()=>e.startSound(),n=[`pointerup`,`touchend`,`click`,`keydown`];for(let e of n)window.addEventListener(e,t,!0);return()=>{for(let e of n)window.removeEventListener(e,t,!0)}},[T,c.sound,e]),(0,D.useEffect)(()=>{let e=()=>b(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,D.useEffect)(()=>{if(h)return()=>void i?.(!1)},[h,i]);let Ce=(0,D.useRef)(h);(0,D.useEffect)(()=>{Ce.current=h},[h]),(0,D.useEffect)(()=>{if(!t||!T||!Lc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!Ce.current&&(g(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,T,i]),(0,D.useEffect)(()=>{t&&T&&rs()&&!Ce.current&&(g(!0),i?.(!0))},[t,T,i]),(0,D.useEffect)(()=>{if(!T)return;let e=e=>{if(e.key!==`Escape`)return;if(S)return void Le.current();if(he(),h)return g(!1);let t=Rc(document.activeElement,document.body,p.current);t===`game`?Le.current():t===`controls`&&m.current?.focus({preventScroll:!0})};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[T,h,he,S]),(0,D.useEffect)(()=>{if(!h||!Lc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,g(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[h]),(0,D.useEffect)(()=>{if(!h||typeof document>`u`)return;let e=()=>{document.fullscreenElement||Lc()||g(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[h]);let Te=rs(),Ee=T&&kc({player:te,guided:_,movedOff:ne,reconnecting:C})&&!u?.playsAs,De=async e=>{g(e),await i?.(e)},Oe=()=>m.current?.focus({preventScroll:!0}),ke=()=>{It(Dc,`1`),v(!0),re(!1)},Ae=()=>{he();let e=C?`[data-testid="join-reconnecting-leave"]`:`[data-testid="join-bar"] button`;p.current?.querySelector(e)?.focus({preventScroll:!0})},je=()=>{let e=p.current?.querySelector(`[data-testid="join-check-open"]`);e?e.focus({preventScroll:!0}):Oe(),ee(!1)},Me=()=>Rc(document.activeElement,document.body,p.current),[Ne,Pe]=(0,D.useState)(`game`);(0,D.useEffect)(()=>{if(!T)return;let e=()=>Pe(Me()),t=()=>window.setTimeout(e,0);return e(),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t)}},[T]);let Fe=()=>{switch(T?zc({checking:S,guide:Ee,where:Me(),full:h}):null){case`close-check`:return je(),!0;case`close-guide`:return ke(),Oe(),!0;case`show-controls`:return Ae(),!0;case`leave-full`:return De(!1),!0;default:return!1}},Le=(0,D.useRef)(Fe);(0,D.useEffect)(()=>{Le.current=Fe});let Re=t&&!de&&T&&zc({checking:S,guide:Ee,where:Ne,full:h})!==null;(0,D.useEffect)(()=>{if(Re)return Xo(()=>void Le.current())},[Re]);let ze=!t&&T&&!de;(0,D.useEffect)(()=>{if(!ze)return;let e=window.location.href;window.history.pushState(window.history.state,``);let t=!0,n=()=>{if(t=!1,!Le.current())return window.history.back();window.history.pushState(window.history.state,``),t=!0};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),t&&window.location.href===e&&window.history.back()}},[ze]);let Be=l.kind===`joined`;(0,D.useEffect)(()=>{if(!Be)return;let e=document.activeElement;if(e&&e!==document.body)return;let t=Te&&Ee?p.current?.querySelector(`[data-testid="join-guide-ok"]`):null;t?t.focus({preventScroll:!0}):Oe()},[Be]),(0,D.useEffect)(()=>{x.pressed&&T&&!S&&Me()===`controls`&&Oe()},[x.pressed]);let Ve=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,z.jsxs)(`div`,{className:t?`rounded-[var(--radius-card)] bg-neutral-900 text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black text-white`,"data-join-ui":``,children:[l.kind===`connecting`&&o&&a&&(0,z.jsx)(Tc,{href:a}),(0,z.jsx)(Vc,{text:l.kind===`connecting`?s(`join_connecting`,{host:d},`Connecting to ${d}…`):s(`join_waiting`,{host:d},`Waiting for ${d} to let you in`),body:l.kind===`asking`?s(`join_waiting_body`,{host:d},`${d} sees your name on their screen and taps Allow.`):void 0,onCancel:Ve})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,z.jsxs)(`div`,{className:t?`flex flex-col items-center gap-4 rounded-[var(--radius-card)] bg-neutral-900 px-6 py-10 text-center text-white`:`flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-black px-6 text-center text-white`,"data-testid":`join-ended`,"data-why":l.why,"data-join-ui":``,children:[(0,z.jsx)(Se,{size:28,className:`text-white/60`}),(0,z.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:Mc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,z.jsx)(Tc,{href:a}),(0,z.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,z.jsx)(`button`,{type:`button`,onClick:r,autoFocus:!0,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`join-again`,children:l.kind===`refused`&&l.why===`not_playing`?s(`join_retry`,void 0,`Try again`):s(`join_again`,void 0,`Ask to join again`)}),(0,z.jsx)(`button`,{type:`button`,onClick:n,autoFocus:!i,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let He=l.player,Ue=c.light??at(He),We=c.rttMs??u?.rttMs??null,Ge=it(We),Ke=Lc(),qe=T&&!C&&!x.ready&&Ke&&(!t||h),Je=kc({player:He,guided:_,movedOff:ne,reconnecting:C}),Ye=He===Oc,Xe=u?.playsAs??null,Ze=C?(l.deadline-w)/1e3:0,Qe=()=>De(!h),$e=t&&!h&&Ke&&T,et=(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`span`,{className:`flex items-center gap-1.5 rounded-full bg-black/60 px-2.5 py-1 font-medium`,"data-testid":`join-player`,children:[(0,z.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`}}),t&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:He},`You are Player ${He}`)]}),We!=null&&(0,z.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:Bc[Ge]},"data-testid":`join-delay`,"data-tone":Ge,"data-path":c.path??void 0,children:[c.path&&(0,z.jsxs)(`span`,{className:`text-white/80`,children:[Ac(s,c.path),` · `]}),Math.round(We),` ms`]}),Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-stream`,children:s(`join_seat_stream`,{host:d},`You're playing as ${d}'s PS5 user. No need to pick one.`)}),Xe&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-plays-as`,children:s(`join_plays_as`,{profile:Xe},`You're playing as ${Xe}. No need to pick one.`)}),E&&!Ye&&u?.seatNote&&(0,z.jsx)(`span`,{className:`rounded-full bg-black/60 px-2.5 py-1 text-white/85`,"data-testid":`join-seat-note`,children:s(`join_seat_tv_asks`,{host:d},`${d} chose a profile for you, but it couldn't be used. The TV will ask who you are.`)}),E&&!Ye&&(0,z.jsx)(`span`,{className:`rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-picking`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)})]}),tt=(0,z.jsxs)(z.Fragment,{children:[le&&de&&k.shown&&!C&&(0,z.jsxs)(`button`,{type:`button`,onClick:k.hide,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 font-medium`,"data-testid":`join-hide-controls`,children:[(0,z.jsx)(pe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex items-center gap-1 rounded-full bg-white/90 px-2.5 py-1 font-medium text-black`,"data-testid":`join-sound`,children:[(0,z.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-mute`,children:[c.muted?(0,z.jsx)(M,{size:13}):(0,z.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,z.jsxs)(`span`,{className:`flex items-center gap-1 rounded-full bg-black/60 px-2.5 py-1 text-white/80`,"data-testid":`join-no-sound`,children:[(0,z.jsx)(M,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,z.jsx)(`button`,{type:`button`,onClick:()=>void Qe(),"aria-label":h?s(`join_exit_fullscreen`,void 0,`Leave full screen`):s(`pad_fill`,void 0,`Full screen`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-full`,children:h?(0,z.jsx)(be,{size:13}):(0,z.jsx)(O,{size:13})}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),"aria-label":s(`join_check_title`,void 0,`Check your controller`),title:s(`join_check_title`,void 0,`Check your controller`),className:`flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 hover:bg-white/25`,"data-testid":`join-check-open`,children:(0,z.jsx)(me,{size:13})}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex items-center gap-1 rounded-full bg-[var(--color-danger,#dc2626)] px-3 py-1 font-medium`,"data-testid":`join-leave`,children:[(0,z.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),nt=k.shown?`opacity-100`:`pointer-events-none opacity-0`,rt={"data-testid":`join-bar`,"data-shown":k.shown?`1`:`0`,onFocus:e=>{(Te||e.target.matches?.(`:focus-visible`))&&ce(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||ce(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&oe(!0)},onPointerLeave:()=>oe(!1)},ot=h||!t?`fixed inset-0 z-[200] bg-black`:`relative mx-auto aspect-video w-full max-w-[max(20rem,calc((100dvh_-_22rem)*16/9))] overflow-hidden rounded-[var(--radius-card)] bg-black shadow-[var(--shadow-2)]`,st=t&&h;return(0,z.jsxs)(`div`,{className:`space-y-2`,ref:p,"data-join-ui":``,children:[(0,z.jsxs)(`div`,{className:`${ot} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},role:st?`dialog`:void 0,"aria-modal":st?!0:void 0,"aria-label":st?s(`pad_fill`,void 0,`Full screen`):void 0,onPointerMove:e=>{if(e.pointerType===`mouse`)return he();let t=_e.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>Ic&&ve()},onPointerDown:e=>{if(Fc(e.target))return;if(e.pointerType===`mouse`||!de)return he();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;ve();let{pointerId:t,clientX:n,clientY:r}=e;_e.current={id:t,x:n,y:r,timer:setTimeout(()=>{_e.current=null,navigator.vibrate?.(15),k.toggle()},450)}},onPointerUp:ve,onPointerCancel:ve,onPointerLeave:ve,"data-testid":`join-stage-view`,children:[(0,z.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),le&&!k.shown&&!C&&We!=null&&(0,z.jsxs)(`span`,{className:`pointer-events-none absolute z-10 rounded-full bg-black/40 px-1.5 py-0.5 text-[10px] leading-none tabular-nums`,style:{color:Bc[Ge],top:`max(0.5rem, env(safe-area-inset-top))`,right:`max(0.5rem, env(safe-area-inset-right))`},"data-testid":`join-delay-corner`,children:[Math.round(We),` ms`]}),qe?(0,z.jsxs)(`div`,{className:`absolute left-1/2 top-1/2 z-20 flex w-max max-w-[min(24rem,calc(100%-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-2 rounded-2xl bg-black/70 p-3 text-xs backdrop-blur-sm transition-opacity duration-300 ${nt}`,...rt,children:[(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:et}),(0,z.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:tt})]}):$e?null:(0,z.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex flex-wrap items-center gap-2 bg-gradient-to-b from-black/70 to-transparent px-3 pb-5 pt-[max(8px,env(safe-area-inset-top))] text-xs transition-opacity duration-300 ${nt}`,...rt,children:[et,(0,z.jsx)(`span`,{className:`flex-1`}),tt]}),!k.shown&&!qe&&(0,z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},"aria-label":s(`join_show_controls`,void 0,`Show controls`),className:`absolute left-1/2 top-[max(6px,env(safe-area-inset-top))] z-20 flex h-7 w-11 -translate-x-1/2 items-center justify-center rounded-full bg-black/40 text-white/70 opacity-60 hover:opacity-100 focus-visible:opacity-100`,"data-testid":`join-show-controls`,children:(0,z.jsx)(ue,{size:16,"aria-hidden":!0})}),ye&&!k.shown&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-[max(10px,env(safe-area-inset-top))] z-20 -translate-x-1/2 rounded-full bg-black/60 px-3 py-1 text-xs text-white/85`,"data-testid":`join-hold-hint`,children:s(`join_hold_hint`,void 0,`Press and hold the picture to show the buttons`)}),c.problem&&(0,z.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`join-problem`,children:c.problem===`no_hevc`?s(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):s(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),S&&(0,z.jsx)(Cc,{onClose:je}),qe&&(0,z.jsx)(ks,{stream:e,layout:`overlay`,onMenu:()=>k.shown?k.hide():he()}),!qe&&!C&&(0,z.jsxs)(`div`,{className:`absolute bottom-3 left-3 z-20 flex items-center gap-2 rounded-2xl bg-black/70 px-3 py-1.5 text-xs transition-opacity duration-300 ${nt}`,"data-testid":`join-pad`,children:[(0,z.jsx)(me,{size:14,style:{color:x.pressed?`rgb(${Ue[0]},${Ue[1]},${Ue[2]})`:void 0}}),x.ready?(0,z.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),x.weak8BitDo&&x.id&&(0,z.jsx)(ps,{id:x.id,className:`text-amber-200/90`}),x.kind===`guess`&&no()&&(0,z.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2 text-white/75`,"data-testid":`join-pad-unknown`,children:[s(`join_check_unknown_short`,void 0,`Not on our list: buttons may be mixed up.`),(0,z.jsx)(`button`,{type:`button`,onClick:()=>ee(!0),className:`rounded-full bg-white px-2.5 py-0.5 font-medium text-black`,"data-testid":`join-pad-unknown-check`,children:s(`join_check_title`,void 0,`Check your controller`)})]})]}):Ke&&t&&!h?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,z.jsxs)(`span`,{className:`flex flex-col`,children:[(0,z.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,z.jsx)(`span`,{className:`text-white/60`,"data-testid":`join-pad-keys`,children:s(`join_pad_keys`,void 0,`Or use the keyboard: WASD move, arrows D-pad, Enter ✕, Backspace ○, Q □, E △, Tab Options.`)})]}),Te&&(0,z.jsx)(`span`,{className:`max-w-[14rem] border-l border-white/20 pl-2 text-white/70`,"data-testid":`join-tv-back`,children:s(`join_tv_back_hint`,void 0,`Press Back on the remote for the buttons.`)})]}),u?.blockSystem&&u.state===`playing`&&!qe&&(0,z.jsx)(`p`,{className:`absolute bottom-3 right-3 z-20 rounded-full bg-black/60 px-3 py-1 text-[11px] text-white/70 transition-opacity duration-300 ${nt}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),fe&&!Ye&&de&&!k.shown&&!C&&(0,z.jsx)(`p`,{className:`pointer-events-none absolute left-1/2 top-2 z-20 -translate-x-1/2 whitespace-nowrap rounded-full bg-white/90 px-2.5 py-1 text-xs font-medium text-black`,"data-testid":`join-picking-note`,children:s(`join_picking`,void 0,`Press PS, then pick Quick Play on the TV`)}),Je&&!Xe&&(0,z.jsxs)(`div`,{className:`absolute bottom-14 left-1/2 z-30 w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-2xl border border-white/10 bg-neutral-900/90 p-4 text-sm shadow-2xl backdrop-blur-md`,"data-testid":`join-guide`,children:[(0,z.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/75`,children:s(`join_guide_body`,void 0,`On your controller, press PS once. The TV asks "Who's using this controller?". Pick Quick Play or your own user. The host doesn't need to do anything.`)}),(0,z.jsx)(`p`,{className:`mt-1 text-white/60`,children:s(`join_guide_menus`,void 0,`On the PS5's home screen only the host controls the menus; your controller plays inside games.`)}),(0,z.jsx)(`button`,{type:`button`,onClick:()=>{ke(),Oe()},className:`mt-3 rounded-full bg-white px-3 py-1 text-xs font-medium text-black`,"data-testid":`join-guide-ok`,children:s(`join_guide_ok`,void 0,`Got it`)})]}),C&&(0,z.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-black/70 px-6 text-center`,"data-testid":`join-reconnecting`,children:[(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`absolute right-3 top-[max(10px,env(safe-area-inset-top))] flex items-center gap-1 rounded-full bg-white/15 px-3 py-1.5 text-sm font-medium hover:bg-white/25`,"data-testid":`join-reconnecting-leave`,children:[(0,z.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,z.jsx)(`span`,{className:`h-7 w-7 animate-spin rounded-full border-2 border-white/30 border-t-white`,"aria-hidden":!0}),l.hostStopped?(0,z.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:Ec(Ze)},`The host stopped playing — waiting for them to start again (${Ec(Ze)})`)}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:Ec(Ze)},`Your place is kept for ${Ec(Ze)}.`)})]})]}),!t&&T&&y&&Ke&&(0,z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,z.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,z.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})}),(0,z.jsx)(`div`,{ref:m,tabIndex:0,"data-own-arrows":``,"data-join-game":``,"aria-label":s(`join_game_label`,{host:d},`${d}'s game`),className:`pointer-events-none absolute inset-0 outline-none`,"data-testid":`join-game`})]}),$e&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-[var(--radius-card)] bg-neutral-900 px-3 py-2 text-xs text-white`,"data-testid":`join-bar`,"data-shown":`1`,"data-below":`1`,children:[(0,z.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:et}),(0,z.jsxs)(`button`,{type:`button`,onClick:()=>void Qe(),className:`flex h-11 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full bg-white/15 px-3 text-sm font-medium hover:bg-white/25`,"data-testid":`join-fullscreen-below`,children:[(0,z.jsx)(O,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,z.jsx)(`button`,{type:`button`,onClick:()=>e.setMuted(!c.muted),"aria-pressed":c.muted,"aria-label":c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`),className:`flex h-11 w-11 items-center justify-center rounded-full bg-white/15 hover:bg-white/25`,children:c.muted?(0,z.jsx)(M,{size:16}):(0,z.jsx)(we,{size:16})}):c.sound?null:(0,z.jsxs)(`button`,{type:`button`,onClick:()=>e.startSound(),className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-white px-3 text-sm font-medium text-black`,children:[(0,z.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,z.jsxs)(`button`,{type:`button`,onClick:Ve,className:`flex h-11 items-center justify-center gap-1.5 rounded-full bg-[var(--color-danger,#dc2626)] px-4 text-sm font-medium`,"data-testid":`join-leave-below`,children:[(0,z.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var Uc=`ps5upload.join.name`;function Wc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function Gc(e){return e.trim().slice(0,32)}function Kc(e=``){return Gc(Lt(`ps5upload.join.name`)??``)||e}function qc(e){let t=Gc(e);return t&&It(Uc,t),t}function Jc(e){try{return!!sessionStorage.getItem(Ro(e))}catch{return!1}}async function Yc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Xc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Ie(),c=wc(r&&o!==!1?e:null,i),[l,u]=(0,D.useState)(()=>Kc(Wc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(0),h=(0,D.useCallback)(e=>{if(!e)return;let t=typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,n=e.querySelector(`[data-testid="join-name"]`)?.value.trim()?`join-go`:t?null:`join-name`;n&&e.querySelector(`[data-testid="${n}"]`)?.focus({preventScroll:!0})},[]),g=i=>{let s=qc(i);if(!s)return;let c=new cc({url:e,invite:t,name:s,host:n,transport:r,path:a,...o===void 0?{}:{internet:o}});f(c),m(e=>e+1),c.start()};if((0,D.useEffect)(()=>{!d&&Jc(t)&&l.trim()&&g(l)},[]),(0,D.useEffect)(()=>d?dc(d):void 0,[d]),(0,D.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,z.jsx)(Hc,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),g(l)},onFullscreen:Yc},p);let _=n??s(`join_host_fallback`,void 0,`your friend`),v=(0,z.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,"data-join-ui":``,children:(0,z.jsxs)(`form`,{ref:h,className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),g(l)},children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,z.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,z.jsx)(Se,{size:20})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,z.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:_},`Play on ${_}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,z.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,z.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,z.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),maxLength:32,autoComplete:`nickname`,className:`block w-full rounded-lg border border-white/15 bg-black px-3 py-2 text-base outline-none focus:border-white/50`,"data-testid":`join-name`}),(0,z.jsx)(`span`,{className:`block text-xs text-white/50`,children:s(`join_name_hint`,void 0,`Your friend sees this when you ask to join.`)})]}),(0,z.jsx)(`button`,{type:`submit`,disabled:!l.trim(),className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black disabled:opacity-40`,"data-testid":`join-go`,children:s(`join_button`,void 0,`Join`)}),c&&i&&(0,z.jsx)(Tc,{href:i})]})});return t?(0,z.jsx)(Wo,{appLink:rt(location.href),children:v}):v}function Zc(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Qc(e,t){let n=Zc(e),r=Zc(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function $c(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Zc(t);return n===0?`lan`:n===1?`tailscale`:null}function el(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Qc(a(i.localCandidateId),a(i.remoteCandidateId))}function tl(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function nl(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function rl(e,t){let n=nl(e);return n!==null&&n===t.toUpperCase()}var il=16777216;function al(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function sl(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var cl=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],ll=1500,ul=2e4;function dl(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var fl=null;function pl(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function ml(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||fl)return;let r=tl(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};fl=a;let o=()=>{fl===a&&(fl=null,a.timer&&clearTimeout(a.timer),pl(i))};i.onopen=()=>i.send(JSON.stringify({v:1,t:`join`,room:e.room})),i.onmessage=e=>{if(typeof e.data==`string`)try{a.msgs.push(JSON.parse(e.data))}catch{}},i.onclose=o,i.onerror=()=>{},a.timer=setTimeout(o,t.keepMs??6e4)}function hl(e,t){let n=fl;return n?(fl=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(pl(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function gl(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new ol,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??tl(e.hub),a=t.signalUrl||t.lan?null:hl(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:cl}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=dl(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!rl(t.sdp,e.fp):nl(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(sl(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return el(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of al(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+ul,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},ll),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(He,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}var _l=3e3;function vl(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var U=e=>vl(e,`api/join/signal`);function yl(e){let t=[];if(e.rtc){let n=e.net??{room:``,key:``,fp:e.fp??``,hub:``};for(let[r,i]of[[`lan`,e.lan],[`tailscale`,e.ts]]){let a=i?U(i):null;if(!a)continue;let o=e.rtcMake(n,{signalUrl:e.reach(a),...e.net?{}:{lan:!0}});t.push({via:r,make:()=>new o(``),pinned:!!n.fp})}if(e.net){let n=e.rtcMake(e.net,{});t.push({via:`hub`,make:()=>new n(``),pinned:!0})}}let n=e.lan?vl(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var bl=new Map;function xl(e,t,n=300,r=_l){let i=e.some(e=>e===`lan`||e===`tailscale`),a=e.some(e=>e!==`socket`);return e.map(e=>e===t?0:e===`hub`&&i?n:e===`socket`&&a?r:0)}function Sl(e){let t=e.find(e=>e.via===`hub`),n=e.find(e=>(e.via===`lan`||e.via===`tailscale`)&&[`no_direct`,`net_full`,`offer`].includes(Ue(e.e)??``));return t&&(Ue(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function Cl(e,t){var n;let r=t.log??(()=>{}),i=t.headStartMs??300,a=t.socketAfterMs??3e3;class o{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.live=[],this.waiting=[],this.pinned=new Set,this.t0=0,this.closes=[],this.winner=null,setTimeout(()=>this.begin(),0)}get via(){return this.winner?.via??null}get media(){return this.winner?.s?.media??null}async netPath(){let e=this.winner?.s;return e?.netPath?e.netPath():null}begin(){if(this.readyState!==0)return;let n=e();if(!n.length){this.end({type:`close`,code:1006,reason:``,wasClean:!1});return}this.t0=Date.now();for(let e of n)e.pinned&&this.pinned.add(e.via);let r=xl(n.map(e=>e.via),bl.get(t.room)??null,i,a);n.forEach((e,t)=>{r[t]===0?this.launch(e.via,e.make):this.waiting.push({via:e.via,make:e.make,timer:setTimeout(()=>this.startWaiting(e.via),r[t])})})}startWaiting(e){let t=this.waiting.findIndex(t=>t.via===e);if(t<0)return;let[n]=this.waiting.splice(t,1);clearTimeout(n.timer),this.launch(n.via,n.make)}launch(e,t){if(this.readyState!==0)return;let n;try{n=t()}catch{this.tryClosed(e,{type:`close`,code:1006,reason:``,wasClean:!1});return}r(`path: trying ${e}`);let i={via:e,s:n};this.live.push(i),n.binaryType=this.binaryType,n.onopen=e=>this.won(i,e),n.onclose=t=>{this.live=this.live.filter(e=>e!==i),this.tryClosed(e,t)},n.onerror=()=>{},n.onmessage=null}tryClosed(e,t){if(this.readyState===0){if(r(`path: ${e} failed after ${Date.now()-this.t0} ms${t?.reason?` (${t.reason})`:``}`),this.closes.push({via:e,e:t}),this.pinned.has(e)&&Ue(t)===`mismatch`){for(let e of this.waiting.filter(e=>e.via===`socket`))clearTimeout(e.timer);this.waiting=this.waiting.filter(e=>e.via!==`socket`)}!this.live.length&&this.waiting.length?this.startWaiting(this.waiting[0].via):!this.live.length&&!this.waiting.length&&this.end(Sl(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,bl.set(t.room,e.via),r(`path: playing by ${e.via} after ${Date.now()-this.t0} ms`);for(let e of this.waiting.splice(0))clearTimeout(e.timer);for(let t of this.live.splice(0))if(t!==e){t.s.onopen=t.s.onclose=t.s.onmessage=t.s.onerror=null;try{t.s.close()}catch{}}let i=e.s;i.onmessage=e=>this.onmessage?.(e),i.onerror=e=>this.onerror?.(e),i.onclose=e=>{this.readyState!==3&&(this.readyState=3,this.onclose?.(e))},this.readyState=1,t.onWin?.(e.via),this.onopen?.(n)}send(e){if(this.readyState!==1||!this.winner)throw Error(`not open`);this.winner.s.send(e)}close(e,t){if(this.readyState===3)return;let n=this.readyState===1;this.readyState=3;for(let e of this.waiting.splice(0))clearTimeout(e.timer);let r=this.winner?[this.winner,...this.live]:this.live.splice(0);for(let n of r){n.s.onopen=n.s.onclose=n.s.onmessage=n.s.onerror=null;try{n.s.close(e,t)}catch{}}let i=this.onclose;if(i){let r={type:`close`,code:e??1e3,reason:t??``,wasClean:n};setTimeout(()=>i(r),0)}}end(e){if(this.readyState===3)return;this.readyState=3;let t=this.onclose,n=e??{type:`close`,code:1006,reason:``,wasClean:!1};t&&setTimeout(()=>t(n),0)}}return n=o,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,o}fs();var wl=new URLSearchParams(location.hash.slice(1)),Tl=wl.get(`n`)?.trim()||null,El=nt(location.hash);El&&ml(El);var Dl=(0,x.createRoot)(document.getElementById(`root`));if(El){let e=gl(El,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Re(location.hash,`join`);Dl.render((0,z.jsx)(Xc,{url:tl(El.hub),invite:El.key,host:Tl,transport:e,lanUrl:t?ze(t,{key:El.key}):null}))}else{let e=wl.get(`i`)||null,t=location.pathname.replace(/\/join\/?$/,``),n=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${t}/api/join/ws`,r=e=>console.info(`[join] ${e}`),i=`${location.origin}${t}/join`,a=typeof RTCPeerConnection>`u`?void 0:Cl(()=>yl({net:null,lan:i,ts:null,fp:tt(wl.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>gl(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});Dl.render((0,z.jsx)(Xc,{url:n,invite:e,host:Tl,path:$c(location.hostname),transport:a,internet:!1}))} diff --git a/site/pad/index.html b/site/pad/index.html index a59852b02..78a6de820 100644 --- a/site/pad/index.html +++ b/site/pad/index.html @@ -270,7 +270,7 @@ z AÍp\Ž0N˜HJê´ªØ^U I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var w={a:v};this.setModule=t=>{e.setModule(fi,t)},this.getModule=()=>e.getModule(fi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,w)).then(e=>{let t=e.exports;y(t),a=t.g,o(),ne(t),n()}),this.ready=new Promise(e=>{n=e}).then(()=>{this.HEAP=a.buffer,this.malloc=x,this.free=te,this.opus_frame_decoder_create=b,this.opus_frame_decode_float_deinterleaved=S,this.opus_frame_decoder_destroy=ee}),this)}var pi=o((()=>{}));function mi(e={}){mi.errors||Object.defineProperties(mi,{errors:{value:new Map([[-1,`OPUS_BAD_ARG: One or more invalid/out of range arguments`],[-2,`OPUS_BUFFER_TOO_SMALL: Not enough bytes allocated in the buffer`],[-3,`OPUS_INTERNAL_ERROR: An internal error was detected`],[-4,`OPUS_INVALID_PACKET: The compressed data passed is corrupted`],[-5,`OPUS_UNIMPLEMENTED: Invalid/unsupported request number`],[-6,`OPUS_INVALID_STATE: An encoder or decoder structure is invalid or already freed`],[-7,`OPUS_ALLOC_FAIL: Memory allocation has failed`]])}}),this._init=()=>new this._WASMAudioDecoderCommon(this).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputChannels*this._outputChannelSize,Float32Array);let t=this._common.allocateTypedArray(this._channels,Uint8Array);t.buf.set(this._channelMappingTable),this._decoder=this._common.wasm.opus_frame_decoder_create(this._sampleRate,this._channels,this._streamCount,this._coupledStreamCount,t.ptr,this._preSkip,this._forceStereo)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.free(),this._common.wasm.opus_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder)},this._decode=e=>{if(!(e instanceof Uint8Array))throw Error(`Data to decode must be Uint8Array. Instead got `+typeof e);this._input.buf.set(e);let t=this._common.wasm.opus_frame_decode_float_deinterleaved(this._decoder,this._input.ptr,e.length,this._output.ptr),n;return t<0&&(n=`libopus `+t+` `+(mi.errors.get(t)||`Unknown Error`),console.error(n),t=0),{outputBuffer:this._common.getOutputChannels(this._output.buf,this._outputChannels,t),samplesDecoded:t,error:n}},this.decodeFrame=e=>{let t=[],n=this._decode(e);return n.error&&this._common.addError(t,n.error,e.length,this._frameNumber,this._inputBytes,this._outputSamples),this._frameNumber++,this._inputBytes+=e.length,this._outputSamples+=n.samplesDecoded,this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(t,[n.outputBuffer],this._outputChannels,n.samplesDecoded,this._sampleRate)},this.decodeFrames=e=>{let t=[],n=[],r=0,i=0;for(;itypeof e==`number`,n=e.sampleRate,r=e.channels,i=e.streamCount,a=e.coupledStreamCount,o=e.channelMappingTable,s=e.preSkip,c=+!!e.forceStereo;if(r>2&&(!t(i)||!t(a)||!Array.isArray(o)))throw Error(`Invalid Opus Decoder Options for multichannel decoding.`);return this._sampleRate=[8e3,12e3,16e3,24e3,48e3].includes(n)?n:48e3,this._channels=t(r)?r:2,this._streamCount=t(i)?i:1,this._coupledStreamCount=t(a)?a:this._channels-1,this._channelMappingTable=o||(this._channels===2?[0,1]:[0]),this._preSkip=s||0,this._forceStereo=r<=8&&r!=2?c:0,this._inputSize=3840*this._channels,this._outputChannelSize=5760,this._outputChannels=this._forceStereo?2:this._channels,this._ready=this._init(),this}var hi=o((()=>{di(),pi()})),gi,_i=o((()=>{di(),pi(),hi(),gi=class extends si{constructor(e){super(e,`opus-decoder`,mi,fi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),vi=c({OpusDecoder:()=>mi,OpusDecoderWebWorker:()=>gi}),yi=o((()=>{hi(),_i(),di(),li(mi,`OpusDecoder`),li(gi,`OpusDecoderWebWorker`)})),bi=[8e3,12e3,16e3,24e3,48e3],xi=null;function Si(){return xi??=Vn(()=>Promise.resolve().then(()=>(yi(),vi)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw xi=null,e}),xi}function Ci(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function wi(e,t,n,r){return{numberOfFrames:t,numberOfChannels:e.length,sampleRate:n,timestamp:r,format:`f32-planar`,duration:Math.round(t/n*1e6),copyTo(n,r){n.set(e[r.planeIndex].subarray(0,t))},close(){}}}var Ti=class{constructor(e,t=Si){this.init=e,this.load=t,this.state=`unconfigured`,this.dec=null,this.pending=[]}configure(e){if(this.state===`closed`)throw Error(`the decoder is closed`);if(!Ci())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!bi.includes(t))throw Error(`Opus does not decode at ${t} Hz`);let n=e.numberOfChannels;if(n<1||n>2)throw Error(`${n} channels: only mono and stereo are decoded`);this.state=`configured`,this.load().then(async e=>{if(this.state===`closed`)return;let r=new e.OpusDecoder({channels:n,sampleRate:t});if(await r.ready,this.state!==`configured`){r.free();return}this.dec=r;let i=this.pending;this.pending=[];for(let e of i)this.state===`configured`&&this.run(e)}).catch(e=>this.fail(e))}decode(e){if(this.state!==`configured`)return;let t=e;if(this.dec)return this.run(t);this.pending.push({timestamp:t.timestamp,data:t.data.slice()}),this.pending.length>50&&this.pending.shift()}run(e){let t=this.dec;if(!t)return;let n;try{n=t.decodeFrame(e.data)}catch(e){return this.fail(e)}n.samplesDecoded&&n.channelData.length&&this.init.output(wi(n.channelData,n.samplesDecoded,n.sampleRate,e.timestamp))}fail(e){if(this.state===`closed`)return;this.close();let t=e instanceof Error?e:Error(String(e));queueMicrotask(()=>this.init.error(t))}close(){this.state=`closed`,this.pending=[];let e=this.dec;this.dec=null;try{e?.free()}catch{}}},Ei={makeDecoder:e=>new Ti(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Di(e,t){for(let n=0;n+3>1&63;if(t>=16&&t<=21)return!0;if(t<16)return!1}else{let t=e[n+3]&31;if(t===5)return!0;if(t===1)return!1}}return!1}function Oi(e){for(let t=0;t+6e.toString(16).padStart(2,`0`);return`avc1.${n(e[t+4])}${n(e[t+5])}${n(e[t+6])}`}return`avc1.4d4028`}var ki=[`hev1.1.6.L153.B0`,`hvc1.1.6.L153.B0`,`hev1.2.4.L153.B0`,`hvc1.2.4.L153.B0`,`hev1.1.6.L150.90`];async function Ai(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of ki)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function ji(e){let t=[];for(let n=0;n+2{let i=r+1n&&e[i-1]===0;)i--;return e.subarray(n,i)}).filter(e=>e.length>0)}var Mi=(e,t)=>t?e[0]>>1&63:e[0]&31;function j(e,...t){let n=8+t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);new DataView(r.buffer).setUint32(0,n);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);let i=8;for(let e of t)r.set(e,i),i+=e.length;return r}function M(...e){let t=new Uint8Array(e.reduce((e,[,t])=>e+t,0)),n=0;for(let[r,i]of e){for(let e=i-1;e>=0;e--)t[n+i-1-e]=Math.floor(r/2**(8*e))&255;n+=i}return t}var Ni=(e,t,n,...r)=>j(e,M([t,1],[n,3]),...r),Pi=M([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Fi(e){let t=e.handler===`vide`,n=j(`ftyp`,new TextEncoder().encode(`isom`),M([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=j(`moov`,Ni(`mvhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Pi,new Uint8Array(24),M([2,4])),j(`trak`,Ni(`tkhd`,0,3,M([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Pi,M([(e.width??0)*65536,4],[(e.height??0)*65536,4])),j(`mdia`,Ni(`mdhd`,0,0,M([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Ni(`hdlr`,0,0,M([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),M([0,1])),j(`minf`,t?Ni(`vmhd`,0,1,new Uint8Array(8)):Ni(`smhd`,0,0,M([0,4])),j(`dinf`,Ni(`dref`,0,0,M([1,4]),Ni(`url `,0,1))),j(`stbl`,Ni(`stsd`,0,0,M([1,4]),e.sampleEntry),Ni(`stts`,0,0,M([0,4])),Ni(`stsc`,0,0,M([0,4])),Ni(`stsz`,0,0,M([0,4],[0,4])),Ni(`stco`,0,0,M([0,4])))))),j(`mvex`,Ni(`trex`,0,0,M([1,4],[1,4],[0,4],[0,4],[0,4])))),i=new Uint8Array(n.length+r.length);return i.set(n,0),i.set(r,n.length),i}function Ii(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Ni(`trun`,0,1793,M([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>j(`traf`,Ni(`tfhd`,0,131072,M([1,4])),Ni(`tfdt`,1,0,M([t,8])),o(e)),c=Ni(`mfhd`,0,0,M([e,4])),l=j(`moof`,c,s(0)).length,u=j(`moof`,c,s(l+8)),d=j(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Li(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=ji(e).filter(e=>!r.includes(Mi(e,t))),a=new Uint8Array(i.reduce((e,t)=>e+4+t.length,0)),o=new DataView(a.buffer),s=0;for(let e of i)o.setUint32(s,e.length),a.set(e,s+4),s+=4+e.length;return a}var Ri=e=>e.toString(16).padStart(2,`0`),zi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Bi=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t};function Vi(e){let t=ji(e),n=t.filter(e=>Mi(e,!1)===7),r=t.filter(e=>Mi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Bi([M([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(zi),M([r.length,1]),...r.map(zi)])}function Hi(e,t,n){let r=ji(e),i=e=>r.filter(n=>Mi(n,t)===e),a=(e,t)=>j(e,new Uint8Array(6),M([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),M([24,2],[65535,2]),t);if(!t){let t=i(7),r=Vi(e);return r?{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,j(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ri(t[0][1])}${Ri(t[0][2])}${Ri(t[0][3])}"`}:null}let o=i(32),s=i(33),c=i(34);if(!o.length||!s.length||!c.length)return null;let l=Vr(s[0]);if(l.length<15)return null;let u=l.subarray(3,15),d=u[0]&31,f=d===2?2:0,p=(e,t)=>Bi([M([128|e,1],[t.length,2]),...t.map(zi)]),m=j(`hvcC`,M([1,1]),u,M([61440,2],[252,1],[253,1],[248|f,1],[248|f,1],[0,2],[15,1],[3,1]),p(32,o),p(33,s),p(34,c)),h=[``,`A`,`B`,`C`][u[0]>>6],g=0,_=(u[1]<<24|u[2]<<16|u[3]<<8|u[4])>>>0;for(let e=0;e<32;e++)_&1<>>0).toString(16),`${u[0]&32?`H`:`L`}${u[11]}`,...v.map(e=>e.toString(16))].join(`.`);return{init:Fi({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Ui(e,t,n,r,i,a){return Ii(e,t,n,Li(r,i),a)}function Wi(e,t){let n=j(`dOps`,M([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Fi({handler:`soun`,timescale:48e3,sampleEntry:j(`Opus`,new Uint8Array(6),M([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function Gi(e){if(!e.length)return 960;let t=e[0]>>3,n=t<12?[480,960,1920,2880][t%4]:t<16?[480,960][t%2]:[120,240,480,960][t%4],r=e[0]&3,i=r===0?1:r===3?(e[1]??1)&63:2;return n*Math.max(1,i)}function Ki(e,t,n){return Ii(e,t,Gi(n),n,!0)}var qi={watch:30,player:4},Ji={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},Yi={seek:.8,speed:.25,target:.12};function Xi(e,t,n){let r=typeof n==`string`?Ji[n]:n;return e>r.seek?{seekTo:t-r.target,rate:1}:e>r.speed?{seekTo:null,rate:1.1}:{seekTo:null,rate:1}}function Zi(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ca(e,t,n):new ba(e,t,n)}var Qi=class{constructor(e,t=()=>performance.now()){this.ask=e,this.now=t,this.last=-1/0}waiting(){if(!this.ask)return;let e=this.now();e-this.last<1e3||(this.last=e,this.ask())}};function $i(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var ea=class{constructor(){this.last=-1}take(e){if(this.last>=0){let t=e-this.last&65535;if(t===0||t>=32768)return!1}return this.last=e,!0}reset(){this.last=-1}};function ta(e){if(e.length>=10)return e;let t=new Uint8Array(10);t.set(e.subarray(0,6));let n=new DataView(t.buffer);return n.setUint32(6,Math.round(n.getUint32(2)/100)||480),t}function na(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var ra=class{constructor(e,t=.2){this.min=e,this.max=t,this.next=0,this.calmSince=0,this.minLead=1/0,this.windowAt=0,this.underruns=0,this.dropped=0,this.cushion=e}at(e,t){this.next0&&(this.underruns++,this.cushion=Math.min(this.max,this.cushion+.02)),this.calmSince=e,this.next=e+this.cushion,this.minLead=1/0,this.windowAt=e):e-this.calmSince>10&&this.cushion>this.min&&(this.cushion=Math.max(this.min,this.cushion-.01),this.calmSince=e);let n=this.next-e;if(n>this.cushion+.15)return this.dropped++,null;if(this.minLead=Math.min(this.minLead,n),e-this.windowAt>=.25){let t=this.minLead>this.cushion+ia;if(this.minLead=1/0,this.windowAt=e,t)return this.dropped++,null}let r=this.next;return this.next+=t,r}reset(){this.next=0}},ia=.02;async function aa(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var oa=class{constructor(e,t=()=>performance.now()){this.decoder=e,this.now=t,this.n={frames:0,dropped:0,late:0,stalls:0,stall_ms:0,worst_stall_ms:0,key_waits:0},this.a=0,this.d=0,this.w=!1,this.q=[],this.sum=0,this.cnt=0,this.codec=``}get frames(){return this.n.frames}arrived(){let e=this.now();this.a&&e-this.a>50&&this.n.late++,this.a=e}drop(){this.n.dropped++,this.w||this.n.key_waits++,this.w=!0}decoding(){this.w=!1,this.q.push(this.now())>64&&this.q.shift()}drawn(e=!1){let t=this.now(),n=e?this.q.shift():void 0;n!==void 0&&(this.sum+=t-n,this.cnt++);let r=this.d?t-this.d:0;r>100&&this.stall(r),this.d=t,this.n.frames++}stall(e){this.n.stalls++,this.n.stall_ms+=e,this.n.worst_stall_ms=Math.max(this.n.worst_stall_ms,e)}snapshot(){let e=this.d?this.now()-this.d:0,t={...this.n,decoder:this.decoder};this.codec&&(t.codec=this.codec),e>100&&(t.stalls=this.n.stalls+1,t.stall_ms=this.n.stall_ms+e,t.worst_stall_ms=Math.max(this.n.worst_stall_ms,e));for(let e of[`stall_ms`,`worst_stall_ms`])t[e]=Math.round(t[e]);return t.decode_ms=this.cnt?Math.round(this.sum/this.cnt*10)/10:0,this.sum=this.cnt=0,t}},sa=[`pointerup`,`touchend`,`click`,`keydown`],ca=class{get element(){if(!this.wrap){let e=document.createElement(`div`);e.className=`h-full w-full`,e.append(this.canvas),this.mse&&e.append(this.mse.element),this.wrap=e}return this.wrap}get stats(){return this.mse?.stats??this.ownStats}soundReport(){return this.soundOn?this.mseSound?this.mseSound.report():na(this.soundWasm?`wasm`:`webcodecs`,this.soundStats):null}constructor(e,t=`watch`,n){this.onProblem=e,this.latency=t,this.onNeedKey=n,this.canvas=document.createElement(`canvas`),this.wrap=null,this.mse=null,this.failsNoPicture=0,this.ctx=this.canvas.getContext(`2d`,{alpha:!1}),this.hevc=!1,this.header=null,this.spsRect=null,this.software=!1,this.video=null,this.opening=!1,this.stopped=!1,this.sawKey=!1,this.ownStats=new oa(`webcodecs`),this.problemShown=!1,this.ts=0,this.pipe=null,this.audioGen=0,this.actx=null,this.soundOn=!1,this.unarm=null,this.mseSound=null,this.audioHeader=null,this.soundWasm=!1,this.onSoundFail=null,this.muted=!1,this.keyAsk=new Qi(n),this.clock=new ra(t===`player`?.05:.08),typeof AudioDecoder>`u`&&N()&&(this.mseSound=new P(t,()=>this.mseSoundFailed())),this.canvas.className=`block h-full w-full object-contain`,this.canvas.dataset.testid=`watch-canvas`}setHevc(e){this.hevc=e,this.header&&(this.spsRect=qr(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!fa())return!1;let e=new ba(this.onProblem,this.latency,this.onNeedKey);e.setHevc(this.hevc),e.markProblemShown(),this.mse=e;let t=this.video;this.video=null;try{t?.close()}catch{}return this.canvas.style&&(this.canvas.style.display=`none`),this.wrap?.append(e.element),this.header&&e.onMessage(new Uint8Array([0,...this.header]).buffer),this.onNeedKey?.(),!0}startSound(){this.soundOn=!0,la(),this.mseSound?this.mseSound.start():this.openContext()}openContext(){try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{})}catch{this.onSoundFail?.()}}get sound(){return this.soundOn}setMuted(e){this.muted=e,this.mseSound?.setMuted(e)}resumeSound(){if(!this.soundOn)return;if(this.mseSound)return this.mseSound.resume();let e=this.actx;e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}get soundStats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped,cushionMs:Math.round(this.clock.cushion*1e3)}}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1||this.stopped)return;let n=t[0],r=t.subarray(1);if(this.mse&&(n===0||n===1))return n===0&&(this.header=r.slice()),this.mse.onMessage(e);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?this.openAudio(r.slice()):n===4&&this.onAudio(r)}async openVideo(e){if(this.header=e,this.spsRect=qr(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await xa(e):Oi(e);if(this.mse||this.stopped)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Vi(e)??void 0;try{this.video?.close()}catch{}let r=new VideoDecoder({output:e=>{let t=this.realVisible(e),n=this.canvas;(n.width!==t.displayWidth||n.height!==t.displayHeight)&&(n.width=t.displayWidth,n.height=t.displayHeight),this.ctx?.drawImage(t,0,0,n.width,n.height),this.ownStats.drawn(!0),t.close(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))},error:()=>{this.video===r&&(this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()||this.rebuild())}}),i={codec:t,optimizeForLatency:!0};n&&(i.description=n),this.software&&(i.hardwareAcceleration=`prefer-software`),r.configure(i),this.video=r,this.sawKey=!1}catch{this.problemShown=!0,this.onProblem(`decode`),this.decodeFailed()}finally{this.opening=!1}}}realVisible(e){let t=this.spsRect,n=Jr(e,t);if(n)try{let t=new VideoFrame(e,{visibleRect:{x:n.x,y:n.y,width:n.w,height:n.h},displayWidth:n.w,displayHeight:n.h});return e.close(),t}catch{return e}let r=e.visibleRect;if(t&&r&&!this.software&&(r.width{if(this.video===e){try{e?.close()}catch{}this.rebuild(),this.onNeedKey?.()}})}return e}rebuild(){this.mse||this.stopped||(this.video=null,this.sawKey=!1,this.header&&this.openVideo(this.header).then(()=>this.keyAsk.waiting()))}onVideo(e){let t=this.video;if(t?.state===`closed`){this.opening||this.rebuild();return}if(!t||t.state!==`configured`)return;let n=Di(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>qi[this.latency])return this.sawKey=!1,this.ownStats.drop(),this.keyAsk.waiting();this.sawKey=!0;let r=e;this.hevc?n&&this.header&&(r=new Uint8Array(this.header.length+e.length),r.set(this.header,0),r.set(e,this.header.length)):r=Li(e,!1,!0),this.ts+=16667,this.ownStats.decoding(),t.decode(new EncodedVideoChunk({type:n?`key`:`delta`,timestamp:this.ts,data:r}))}openAudio(e){if(e.length<6)return;let t=++this.audioGen;if(this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.audioHeader=e,this.mseSound)return this.mseSound.setHeader(e);let n=e[0];aa(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return N()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new Qr((e,t)=>this.play(e,t,r.sampleRate));try{r.header(ta(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new P(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),Ei,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(ta(e))}mseSoundFailed(){let e=this.mseSound;e&&(this.mseSound=null,e.stop(),this.soundOn&&(this.openContext(),this.actx&&this.actx.state!==`running`&&this.armResume()),this.audioHeader&&this.soundThroughWasm(this.audioHeader))}onAudio(e){if(this.mseSound)return this.mseSound.frame(e);this.soundOn&&this.pipe&&this.pipe.packet(e)}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a)}stop(){this.stopped=!0;try{this.video?.close()}catch{}this.mse?.stop(),this.audioGen++,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.mseSound?.stop()}};function la(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ua(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function N(){let e=typeof window>`u`?null:fa();return!!e&&(ua(e,`audio/mp4; codecs="Opus"`)||ua(e,`audio/mp4; codecs="opus"`))}var P=class{constructor(e,t,n=document.createElement(`audio`)){this.onFail=t,this.header=null,this.time=0,this.on=!1,this.failed=!1,this.order=new ea,this.el=n,this.track=new ga(n,()=>this.fail(),e===`player`?Yi:e)}get playing(){return this.on&&!this.failed}report(){return{snd:`mse`,snd_jumps:this.track.seeks}}setHeader(e){this.header=e,this.on&&this.open()}start(){if(!this.on&&(this.on=!0,this.header&&this.open(),!this.failed))try{this.el.play()?.catch?.(()=>{})}catch{}}frame(e){if(!this.on||this.failed||!this.track.ready&&!this.track.backlog)return;let t=$i(e);if(!t||!this.order.take(t.index))return;let n=Ki(this.track.nextSeq(),this.time,t.packet);this.time+=Gi(t.packet),this.track.push(n)}setMuted(e){this.el.muted=e}resume(){if(this.playing&&this.el.paused)try{this.el.play()?.catch?.(()=>{})}catch{}}stop(){this.on=!1,this.track.close()}open(){let e=this.header;if(!e||e.length<6||this.failed)return;let t=e[0],n=Wi(t,new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2));this.track.open(`audio/mp4; codecs="Opus"`,n)||this.track.open(`audio/mp4; codecs="opus"`,n)?(this.time=0,this.order.reset()):this.fail()}fail(){this.failed||(this.failed=!0,this.onFail())}},da=class{constructor(e,t,n=Ei){this.onFail=t,this.codecs=n,this.actx=null,this.pipe=null,this.header=null,this.on=!1,this.failed=!1,this.muted=!1,this.unarm=null,this.played=!1,this.clock=new ra(e===`player`?.05:.08)}get playing(){return this.on&&!this.failed}get stats(){return{decoded:this.pipe?.decoded??0,concealed:this.pipe?.concealed??0,underruns:this.clock.underruns,dropped:this.clock.dropped}}start(){if(!this.failed){this.on=!0,la();try{if(!this.actx){let e=new AudioContext({latencyHint:`interactive`});this.actx=e,e.onstatechange=()=>{this.actx===e&&e.state!==`running`&&e.state!==`closed`&&this.armResume()}}this.actx.resume().catch(()=>{}),this.actx.state!==`running`&&this.armResume()}catch{return this.fail()}this.header&&!this.pipe&&this.open()}}setHeader(e){e.length<6||(this.header=e,this.pipe?.reset(),this.pipe=null,this.clock.reset(),this.on&&this.open())}frame(e){this.on&&!this.failed&&this.pipe?.packet(e)}setMuted(e){this.muted=e}resume(){let e=this.actx;this.playing&&e&&e.state!==`running`&&e.state!==`closed`&&(this.clock.reset(),e.resume().catch(()=>{}),this.armResume())}stop(){this.on=!1,this.pipe?.reset(),this.pipe=null,this.unarm?.(),this.actx?.close().catch(()=>{}),this.actx=null}open(){let e=this.header;if(!e||this.failed)return;let t=new Qr((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(ta(e))}play(e,t,n){let r=this.actx;if(!r||r.state!==`running`||!e.length)return;let i=e[0].length,a=this.clock.at(r.currentTime,i/n);if(a===null)return;let o=r.createBuffer(e.length,i,n),s=this.muted?0:t;e.forEach((e,t)=>o.copyToChannel(s===1?e:e.map(e=>e*s),t));let c=r.createBufferSource();c.buffer=o,c.connect(r.destination),c.start(a),this.played=!0}armResume(){if(this.unarm||typeof window>`u`||!window.addEventListener)return;let e=()=>{let e=this.actx;if(!e||e.state===`closed`)return this.unarm?.();this.clock.reset(),e.resume().then(()=>{e.state===`running`&&this.unarm?.()}).catch(()=>{})};for(let t of sa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of sa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function fa(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var pa=10,ma=3;function ha(e,t,n,r=ma){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var ga=class{constructor(e,t,n=`watch`,r,i=()=>performance.now()){this.el=e,this.onError=t,this.latency=n,this.onNeedKey=r,this.now=i,this.ms=null,this.sb=null,this.queue=[],this.mime=``,this.seq=1,this.ready=!1,this.dropped=!1,this.keys=null,this.seeks=0,this.maxLagS=0,this.fromZero=0,this.trims=0,this.lastJump=null,this.trimAt=-1,this.trimFrom=-1,this.keyAt=-1,this.attached=null,r&&(this.keys=[])}setEdge(e){this.latency=e}markKey(e){this.keys?.push(e),this.keyAt=this.now()}open(e,t){let n=fa();if(!n||!ua(n,e))return!1;this.close();let r=new n;return this.ms=r,this.mime=e,this.queue=[t],this.seq=1,this.ready=!1,this.keys&&=[],r.addEventListener(`sourceopen`,()=>{if(this.ms===r)try{let e=r.addSourceBuffer(this.mime);e.mode=`segments`,e.addEventListener(`updateend`,()=>this.pump()),e.addEventListener(`error`,()=>this.onError()),this.sb=e,this.ready=!0,this.pump()}catch{this.onError()}}),`ManagedMediaSource`in window&&n===window.ManagedMediaSource&&(this.el.disableRemotePlayback=!0),this.attached=_a(this.el,r),!0}nextSeq(){return this.seq++}get backlog(){return this.queue.length}push(e){this.queue.push(e),this.pump()}pump(){let e=this.sb;if(!e||e.updating||!this.ready)return;let t=this.el;if(e.buffered.length){let n=e.buffered.end(e.buffered.length-1),r=e.buffered.start(0),i=n-t.currentTime,a=Xi(i,n,this.latency);if(a.seekTo!==null){this.seeks++,this.maxLagS=Math.max(this.maxLagS,i);let o=this.now(),s=e=>e<0?-1:Math.round(o-e);t.currentTime<.05&&r>1&&this.fromZero++,this.lastJump={at:t.currentTime,start:r,end:n,ranges:e.buffered.length,readyState:t.readyState,paused:t.paused,seeking:t.seeking,sinceTrimMs:s(this.trimAt),trimFrom:this.trimFrom,sinceKeyMs:s(this.keyAt)},t.currentTime=Math.max(r,a.seekTo)}if(t.playbackRate!==a.rate&&(t.playbackRate=a.rate),t.currentTime-r>pa&&this.trim(e,r))return}let n=this.queue.shift();if(n){try{e.appendBuffer(n)}catch{this.dropped=!0}t.paused&&t.play().catch(()=>{})}}trim(e,t){let n=this.el.currentTime,r=n-ma;if(this.keys){if(r=ha(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-ma&&this.onNeedKey?.(),!1;let e=r;this.keys=this.keys.filter(t=>t>=e),r-=.001}try{return e.remove(t,r),this.trims++,this.trimAt=this.now(),this.trimFrom=n,!0}catch{return!1}}close(){this.ready=!1,this.sb=null,this.queue=[];let e=this.ms;if(this.ms=null,e&&e.readyState===`open`)try{e.endOfStream()}catch{}if(this.attached===`object`)try{this.el.srcObject=null}catch{}this.attached=null,this.el.src?.startsWith(`blob:`)&&URL.revokeObjectURL(this.el.src),this.el.removeAttribute(`src`)}};function _a(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var va=1e4,ya=class{constructor(e=3,t=va,n=()=>performance.now()){this.max=e,this.windowMs=t,this.now=n,this.at=[]}fail(){let e=this.now();return this.at=this.at.filter(t=>e-t=this.max}clear(){this.at=[]}},ba=class{constructor(e,t=`watch`,n,r){this.onProblem=e,this.latency=t,this.wasm=null,this.audioHeader=null,this.muted=!1,this.gaveUp=!1,this.reopening=!1,this.failedWhileOpening=!1,this.wrap=document.createElement(`div`),this.hevc=!1,this.header=null,this.sawKey=!1,this.stats=new oa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new Qi(n),this.fails=new ya(3,va,r);let i=document.createElement(`video`);i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.className=`block h-full w-full object-contain`,i.dataset.testid=`watch-video`,this.audio=new P(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new ga(i,()=>this.showProblem(),t,()=>this.keyAsk.waiting()),i.addEventListener(`error`,()=>this.restartVideo()),i.addEventListener(`playing`,()=>{this.fails.clear(),this.problemShown&&(this.problemShown=!1,this.onProblem(null))})}markProblemShown(){this.problemShown=!0}showProblem(){this.problemShown||(this.problemShown=!0,this.onProblem(`decode`))}restartVideo(){if(this.gaveUp)return;if(this.reopening){this.failedWhileOpening=!0;return}if(this.showProblem(),this.fails.fail()){this.gaveUp=!0,this.video.close(),this.onGiveUp?.();return}let e=this.header;if(e){this.header=null,this.reopening=!0,this.failedWhileOpening=!1;try{this.openVideo(e)}finally{this.reopening=!1}this.sawKey=!1,this.keyAsk.waiting(),this.failedWhileOpening&&(this.failedWhileOpening=!1,this.restartVideo())}}get failed(){return this.gaveUp}setVideoEdge(e){this.video.setEdge(e)}get videoSeeks(){return{seeks:this.video.seeks,maxLagMs:Math.round(this.video.maxLagS*1e3),fromZero:this.video.fromZero,trims:this.video.trims,lastJump:this.video.lastJump}}get element(){return this.wrap}resume(){let e=this.video.el;e.paused&&e.play()?.catch?.(()=>{})}setHevc(e){this.hevc=e}startSound(){if(this.soundOn=!0,this.wasm)return this.wasm.start();if(!N())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new da(this.latency,()=>this.onSoundFail?.());this.wasm=e,e.setMuted(this.muted),this.audioHeader&&e.setHeader(this.audioHeader),this.soundOn&&e.start()}resumeSound(){this.soundOn&&(this.wasm?this.wasm.resume():this.audio.resume())}setMuted(e){this.muted=e,this.audio.setMuted(e),this.wasm?.setMuted(e)}soundReport(){return this.soundOn?this.wasm?na(`wasm`,this.wasm.stats):this.audio.report():null}get soundPlaying(){return this.wasm?this.wasm.played:this.audio.playing}get sound(){return this.soundOn}onMessage(e){let t=new Uint8Array(e);if(t.length<1)return;let n=t[0],r=t.subarray(1);n===0?this.openVideo(r.slice()):n===1?this.onVideo(r):n===3?(this.audioHeader=r.slice(),(this.wasm??this.audio).setHeader(this.audioHeader)):n===4&&(this.wasm??this.audio).frame(r)}openVideo(e){let t=!!this.header&&this.header.length===e.length&&this.header.every((t,n)=>t===e[n]);if(t&&this.video.ready)return;if(this.gaveUp){if(t)return;this.gaveUp=!1,this.fails.clear()}this.header=e;let n=qr(e,this.hevc)??{w:1920,h:1080},r=Hi(e,this.hevc,n);r&&(this.stats.codec=/codecs="([^"]+)"/.exec(r.mime)?.[1]??``,this.video.open(r.mime,r.init)?(this.sawKey=!1,this.vTime=0,this.vLast=0):(this.problemShown=!0,this.onProblem(this.hevc?`no_hevc`:`decode`)))}onVideo(e){if(!this.video.ready&&!this.video.backlog)return;let t=Di(e,this.hevc);if(this.video.dropped&&(this.video.dropped=!1,this.sawKey=!1),this.stats.arrived(),!this.sawKey&&!t)return this.stats.drop(),this.keyAsk.waiting();if(!t&&this.video.backlog>qi[this.latency])return this.sawKey=!1,this.stats.drop(),this.keyAsk.waiting();this.sawKey=!0,this.stats.drawn();let n=performance.now(),r=this.vLast?Math.min(9e3,Math.max(750,Math.round((n-this.vLast)*90))):1500;this.vLast=n,t&&this.video.markKey(this.vTime/9e4),this.video.push(Ui(this.video.nextSeq(),this.vTime,r,e,this.hevc,t)),this.vTime+=r}stop(){this.video.close(),this.audio.stop(),this.wasm?.stop()}};async function xa(e){let t=Yr(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Ai(1920,1080)}var F={CROSS:1,CIRCLE:2,SQUARE:4,TRIANGLE:8,LEFT:16,RIGHT:32,UP:64,DOWN:128,L1:256,R1:512,L3:1024,R3:2048,OPTIONS:4096,SHARE:8192,TOUCHPAD:16384,PS:32768},Sa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function Ca(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CROSS,F.CIRCLE,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD;var wa=e=>Math.max(-32768,Math.min(32767,Math.round(e))),Ta=[F.CROSS,F.CIRCLE,F.SQUARE,F.TRIANGLE,F.L1,F.R1,0,0,F.SHARE,F.OPTIONS,F.L3,F.R3,F.UP,F.DOWN,F.LEFT,F.RIGHT,F.PS,F.TOUCHPAD];function Ea(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var Da=[0,1,1,1,0,-1,-1,-1],Oa=[-1,-1,0,1,1,1,0,-1];function ka(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ea(n);return e===null?0:(t.hat===`x`?Da:Oa)[e]}return t.inv?-n:n}var Aa={buttons:Ta.flatMap((e,t)=>e?[[e,{b:t}]]:[]),l2:{b:6},r2:{b:7},lx:{a:0},ly:{a:1},rx:{a:2},ry:{a:3}};function ja(e,t,n=!1){if(`b`in t){let r=e.buttons[t.b];return r?n&&r.value>0?Math.min(1,r.value):Math.max(+!!r.pressed,r.value):0}if(`h`in t){let n=Ea(e.axes[t.h]??9);if(n===null)return 0;let r=(n-t.at+8)%8;return+(r===0||r===1||r===7)}let r=e.axes[t.a];if(r===void 0)return 0;let i=t.rest??0;return Math.min(1,Math.max(0,(r-i)/(t.d-i)))}function Ma(e){if(e.mapping===`standard`)return Aa;let t=Na.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Aa;let r={...Aa,buttons:[...Aa.buttons,[F.UP,{h:n,at:0}],[F.RIGHT,{h:n,at:2}],[F.DOWN,{h:n,at:4}],[F.LEFT,{h:n,at:6}]]};return Na.set(e.id,r),r}var Na=new Map;function Pa(e,t=Ma){let n={...Sa},r=e=>Math.abs(e)<.08?0:wa(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(ka(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)ja(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(ja(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(ja(r,e.r2,!0)*255))),n.lx=i(n.lx,a(r,e.lx)),n.ly=i(n.ly,a(r,e.ly)),n.rx=i(n.rx,a(r,e.rx)),n.ry=i(n.ry,a(r,e.ry))}return n}function Fa(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:wa(e.lx+t.lx),ly:wa(e.ly+t.ly),rx:wa(e.rx+t.rx),ry:wa(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}var I=e=>e.toLowerCase().padStart(4,`0`);function Ia(e){let t=/^(.*?)\s*\((?:[^()]*?\s)?Vendor:\s*([0-9a-f]{1,4})\s+Product:\s*([0-9a-f]{1,4})\s*\)\s*$/i.exec(e);if(t)return{vendor:I(t[2]),product:I(t[3]),name:t[1].trim()};let n=/^([0-9a-f]{1,4})-([0-9a-f]{1,4})-(.*)$/i.exec(e.trim());return n?{vendor:I(n[1]),product:I(n[2]),name:n[3].trim()}:null}function La(e=globalThis.navigator){let t=e?.userAgent??``;return/Android|iPhone|iPad|iPod/i.test(t)?null:/Macintosh|Mac OS X/i.test(t)?(e?.maxTouchPoints??0)>1?null:`m`:/Windows/i.test(t)?`w`:/Linux|CrOS|X11/i.test(t)?`l`:null}function Ra(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Ge[`${t}${e.vendor}${e.product}`];if(n!==void 0)return We[n]??null}return null}var za={1:0,2:2,4:4,8:6};function Ba(e){let t=0,n=!1;for(let r of e){let e=/a(\d+)/.exec(r);e&&(t=Math.max(t,Number(e[1])+1)),r.startsWith(`h`)&&(n=!0)}return{n:t,hat:n}}function Va(e,t,n){let{n:r,hat:i}=Ba(t),a=Ta.length,o=e.axes.findIndex(e=>Math.abs(e)>1.05),s=e=>e;if(i&&o<0)return n===`l`&&e.axes.length>=r+2?{hat:-1,hatXY:r,axis:s}:null;if(!(i?o>r:n!==`l`&&e.axes.length>=r+2))return{hat:o,hatXY:-1,axis:s};if(r<=4)return{hat:o,hatXY:-1,axis:e=>[0,1,2,5][e]??e};let c=t[a+2]?.replace(`~`,``)===`a2`&&t[a+3]?.replace(`~`,``)===`a3`,l=[t[6],t[7]].every(e=>/^a[45]~?$/.test(e??``));return r===6&&c&&l?{hat:o,hatXY:-1,axis:e=>[0,1,2,5,3,4][e]??e}:{hat:o,hatXY:-1,axis:s}}function Ha(e,t){let n=/^b(\d+)$/.exec(e);if(n)return{b:Number(n[1])};if(n=/^([+-]?)a(\d+)(~?)$/.exec(e),n){let e=t.axis(Number(n[2]));return n[1]===`+`?{a:e,d:1}:n[1]===`-`?{a:e,d:-1}:n[3]?{a:e,d:-1,rest:1}:{a:e,d:1,rest:-1}}if(n=/^h0\.(\d)$/.exec(e),n){let e=za[n[1]];if(e===void 0)return null;if(t.hat>=0)return{h:t.hat,at:e};if(t.hatXY>=0)return e===0?{a:t.hatXY+1,d:-1}:e===4?{a:t.hatXY+1,d:1}:e===6?{a:t.hatXY,d:-1}:{a:t.hatXY,d:1}}return null}function Ua(e,t){let n=/^a(\d+)(~?)$/.exec(e);if(n)return n[2]?{a:t.axis(Number(n[1])),inv:!0}:{a:t.axis(Number(n[1]))};if(e===`hx`||e===`hy`){if(t.hat>=0)return{a:t.hat,hat:e===`hx`?`x`:`y`};if(t.hatXY>=0)return{a:t.hatXY+ +(e===`hy`)}}return null}function Wa(e,t,n){let r=e.split(`,`),i=Va(t,r,n);if(!i)return null;let a={buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null};for(let e=0;eArray.isArray(e)&&e.length===2&&typeof e[0]==`number`&&Ja(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(Ja)}function Xa(){try{let e=yt(qa),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Ya(e[1])))}catch{return{}}}function Za(e,t){let n=Xa();return t?n[e]=t:delete n[e],vt(qa,JSON.stringify(n)),Qa=n,n}var Qa=null;function $a(e){return Qa??=Xa(),Qa[e.id]??eo(Qa,e.id)??Ka(e)??Ma(e)}function eo(e,t){if(!t.endsWith(` (app)`))return null;let n=t.slice(0,-6).trim().toLowerCase();if(!n)return null;let r=Object.keys(e).filter(e=>{let t=e.trim().toLowerCase();return t===n||t.includes(n)}),i=r.find(e=>e.trim().toLowerCase()===n)??(r.length===1?r[0]:null);return i?(Qa=Za(t,e[i]),e[i]):null}[{kind:`button`,bit:F.CROSS,name:`✕`},{kind:`button`,bit:F.CIRCLE,name:`○`},{kind:`button`,bit:F.SQUARE,name:`□`},{kind:`button`,bit:F.TRIANGLE,name:`△`},{kind:`button`,bit:F.UP,name:`↑`},{kind:`button`,bit:F.DOWN,name:`↓`},{kind:`button`,bit:F.LEFT,name:`←`},{kind:`button`,bit:F.RIGHT,name:`→`},{kind:`button`,bit:F.L1,name:`L1`},{kind:`button`,bit:F.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:F.L3,name:`L3`},{kind:`button`,bit:F.R3,name:`R3`},{kind:`button`,bit:F.OPTIONS,name:`Options`},{kind:`button`,bit:F.SHARE,name:`Create`},{kind:`button`,bit:F.PS,name:`PS`},{kind:`button`,bit:F.TOUCHPAD,name:`Touchpad`},{kind:`axis`,which:`lx`,name:`L →`},{kind:`axis`,which:`ly`,name:`L ↓`},{kind:`axis`,which:`rx`,name:`R →`},{kind:`axis`,which:`ry`,name:`R ↓`}].filter(e=>e.kind!==`button`||![F.L3,F.R3,F.OPTIONS,F.SHARE,F.PS,F.TOUCHPAD].includes(e.bit));var to=12e4;function no(e){let t;try{t=JSON.parse(e)}catch{return null}return Array.isArray(t.rumble)?{rumble:[Number(t.rumble[0])||0,Number(t.rumble[1])||0]}:Array.isArray(t.light)?{light:t.light}:t.stage===`asking`?{kind:`asking`}:t.stage===`refused`?{kind:`refused`,why:String(t.why??``)}:t.stage===`joined`?{kind:`joined`,host:t.session?.host??null,playing:!!t.session?.playing,passcode:!!t.session?.passcode}:null}function ro(e,t){return e.buttons===t.buttons&&e.l2===t.l2&&e.r2===t.r2&&e.lx===t.lx&&e.ly===t.ly&&e.rx===t.rx&&e.ry===t.ry&&(e.touch?.[0]??-1)===(t.touch?.[0]??-1)&&(e.touch?.[1]??-1)===(t.touch?.[1]??-1)&&(e.motion?.t??-1)===(t.motion?.t??-1)}var io=class{constructor(e){this.o=e,this.ws=null,this.last={...Sa},this.lastSent=0,this.raf=0,this.keepalive=null,this.watchdog=null,this.retry=null,this.done=!1,this.stage={kind:`connecting`},this.wasIn=!1,this.attempt=0,this.deadline=0,this.lastHeard=0,this.control=!1,this.neutral=!1,this.now=e.now??(()=>Date.now()),this.WS=e.WebSocketImpl??WebSocket}get currentStage(){return this.stage}setStage(e){this.stage=e,this.o.onStage(e)}start(){if(this.done=!1,this.setStage({kind:`connecting`}),this.connect(),this.done)return;let e=this.o.raf??(e=>window.requestAnimationFrame(e)),t=()=>{this.send(!1),this.raf=e(t)};this.raf=e(t),this.keepalive=setInterval(()=>this.send(!1),250),this.watchdog=setInterval(()=>this.checkSilence(),1e3)}connect(){let e;this.lastHeard=this.now();try{e=new this.WS(this.o.url)}catch{this.dropped();return}this.ws=e,e.binaryType=`arraybuffer`,this.control=!this.o.watch,this.o.watch&&this.o.watch.onControl(!1),e.onmessage=t=>{this.ws===e&&(this.lastHeard=this.now(),this.onMessage(t.data))},e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=Le(t);n&&!this.wasIn?this.finish({kind:`refused`,why:`net:${n}`}):this.dropped()},e.onopen=()=>{this.ws===e&&(this.lastHeard=this.now(),this.o.hello&&e.send(JSON.stringify({hello:this.o.hello})),this.send(!0))}}onMessage(e){if(typeof e!=`string`){e instanceof ArrayBuffer&&this.o.watch?.onFrame(e);return}if(this.o.hello&&e.startsWith(`{"rt":`))try{let t=JSON.parse(e);if(typeof t.rt==`string`&&/^[0-9a-f]{32}$/.test(t.rt)){this.o.hello.rt=t.rt,this.o.onReconnectToken?.(t.rt);return}}catch{}if(e.includes(`"kbm_caps"`))try{let t=JSON.parse(e);if(t.kbm_caps){let e=t.kbm_caps;this.o.onKbmCaps?.({mouse:e.mouse===!0,keyboard:e.keyboard===!0,reason:typeof e.reason==`string`?e.reason:null});return}}catch{}if(this.o.watch)try{let t=JSON.parse(e);if(t.watch&&this.o.watch.onCodec(!!t.watch.hevc),typeof t.control==`boolean`){this.control=t.control,this.o.watch.onControl(t.control),t.control&&this.send(!0);return}}catch{}let t=no(e);if(t){if(`rumble`in t){let[e,n]=t.rumble;navigator.vibrate?.(e||n?250:0)}else if(`light`in t)this.o.onLight?.(t.light);else if(t.kind===`refused`)this.finish(t);else{if(t.kind===`joined`){let e=this.stage.kind!==`joined`;this.wasIn=!0,this.attempt=0,this.setStage(t),e&&this.send(!0);return}this.setStage(t)}}}dropped(){if(this.done)return;if(!this.wasIn||(this.stage.kind!==`reconnecting`&&(this.deadline=this.now()+to),this.now()>=this.deadline)){this.finish({kind:`lost`});return}let e=Re(this.attempt);this.setStage({kind:`reconnecting`,attempt:this.attempt}),this.attempt+=1,this.retry&&clearTimeout(this.retry),this.retry=setTimeout(()=>{this.retry=null,this.done||this.connect()},e)}checkSilence(){let e=this.ws;if(e&&!this.done&&(this.stage.kind===`joined`||this.stage.kind===`reconnecting`)&&!(this.now()-this.lastHeard<=3500)){this.ws=null;try{e.close()}catch{}this.dropped()}}wake(){this.stage.kind===`lost`&&this.wasIn?(this.attempt=0,this.start()):this.stage.kind===`reconnecting`&&(this.deadline=this.now()+to,this.attempt=0,this.retry&&(clearTimeout(this.retry),this.retry=null,this.connect()))}setNeutral(e){this.neutral!==e&&(this.neutral=e,this.send(!0))}current(){let e=Pa(Ue(typeof navigator>`u`?void 0:navigator),$a),t=this.o.touchPad();return{...Fa(e,t),touch:t.touch??null,motion:this.o.motion?.()??null}}send(e){let t=this.ws;if(!t||t.readyState!==this.WS.OPEN||!this.control)return;let n=this.neutral?{...Sa,touch:null,motion:null}:this.current(),r=this.now();!e&&ro(n,this.last)&&r-this.lastSent<250||(this.last=n,this.lastSent=r,t.send(JSON.stringify({pad:{...n,touch:n.touch??null,motion:n.motion??null},ka:1})))}askKeyframe(){let e=this.ws;e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({keyframe:!0}))}sendKbm(e){let t=this.ws;return!t||t.readyState!==this.WS.OPEN||!this.control?!1:(t.send(e instanceof Uint8Array?e:JSON.stringify(e)),!0)}sendPad(){this.send(!1)}clearTimers(){(this.o.cancelRaf??(e=>window.cancelAnimationFrame(e)))(this.raf),this.keepalive&&clearInterval(this.keepalive),this.watchdog&&clearInterval(this.watchdog),this.retry&&clearTimeout(this.retry),this.keepalive=this.watchdog=this.retry=null}finish(e){this.done=!0,this.clearTimers();let t=this.ws;this.ws=null;try{t?.close()}catch{}this.setStage(e)}stop(){this.done=!0,this.clearTimers();let e=this.ws;this.ws=null,e&&e.readyState===this.WS.OPEN&&e.send(JSON.stringify({pad:{...Sa,touch:null}})),e?.close()}},ao=`ps5upload.pad.device`;function oo(e,t=e=>crypto.getRandomValues(e)){let n=e.get(ao);if(n&&/^[0-9a-f]{32}$/.test(n))return n;let r=new Uint8Array(16);t(r);let i=Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``);return e.set(ao,i),i}var so=new Set,co={held:new Set,touch:null,touchPad:Sa,mapping:!1,get paused(){return so.size>0},motion:null},lo={s:.85,m:1,l:1.15},uo=.25;function fo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(uo,e))}var po={overlay:{width:844,height:390},deck:{width:390,height:480}},mo=.7,ho=1.4;function go(e,t,n,r){let i=lo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?po.deck:po.overlay,o=Math.min(ho,Math.max(mo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var _o=34;function vo(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+_o>t}function yo(e,t,n){let r=e/32767,i=t/32767,a=Math.hypot(r,i),o=a>1?1/a:1;return{dx:r*o*n,dy:i*o*n}}var bo=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),L=s(((e,t)=>{t.exports=bo()}))(),xo=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,So=32767,Co=12;function wo({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Tn(),s=(0,T.useRef)(new Map),c=(0,T.useRef)({...Sa}),[l,u]=(0,T.useState)({...Sa}),[d,f]=(0,T.useState)({l:!1,r:!1,touchpad:!1}),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({width:0,height:0});(0,T.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();h(e=>e.width===t.width&&e.height===t.height?e:{width:t.width,height:t.height})};if(t(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t);let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),(0,T.useEffect)(()=>()=>{co.touchPad={...Sa}},[]);let g=()=>{let t={...Sa,touch:null},n={l:!1,r:!1,touchpad:!1};for(let e of s.current.values())e.kind===`stick`&&(n[e.which]=!0),e.kind===`touchpad`&&(n.touchpad=!0),e.kind===`button`&&(t.buttons|=e.bit),e.kind===`trigger`&&(t[e.which]=255),e.kind===`touchpad`&&e.pressed&&(t.buttons|=F.TOUCHPAD);t.lx=c.current.lx,t.ly=c.current.ly,t.rx=c.current.rx,t.ry=c.current.ry,t.touch=c.current.touch??null,co.touchPad=t,e?.sendPad(),u(t),f(e=>e.l===n.l&&e.r===n.r&&e.touchpad===n.touchpad?e:n)},_=(e,t,n)=>{let r=Math.max(-1,Math.min(1,(t-e.cx)/e.radius)),i=Math.max(-1,Math.min(1,(n-e.cy)/e.radius));c.current[e.which===`l`?`lx`:`rx`]=Math.round(r*So),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*So)},v=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget;try{n.setPointerCapture(e.pointerId)}catch{}let r=t(n);s.current.set(e.pointerId,r),r.kind===`stick`&&_(r,e.clientX,e.clientY),r.kind===`touchpad`&&(c.current.touch=Ca((e.clientX-r.rect.left)/r.rect.width,(e.clientY-r.rect.top)/r.rect.height)),navigator.vibrate?.(8),g()},y=e=>{let t=s.current.get(e.pointerId);if(t){if(e.stopPropagation(),t.kind===`stick`)_(t,e.clientX,e.clientY);else if(t.kind===`touchpad`)c.current.touch=Ca((e.clientX-t.rect.left)/t.rect.width,(e.clientY-t.rect.top)/t.rect.height),t.pressed&&Math.hypot(e.clientX-t.x0,e.clientY-t.y0)>Co&&(t.pressed=!1);else return;g()}},b=e=>{let t=s.current.get(e.pointerId);t&&(e.stopPropagation(),s.current.delete(e.pointerId),t.kind===`stick`&&(c.current[t.which===`l`?`lx`:`rx`]=0,c.current[t.which===`l`?`ly`:`ry`]=0),t.kind===`touchpad`&&(c.current.touch=null),g())},x=e=>e.stopPropagation(),S={onPointerMove:y,onPointerUp:b,onPointerCancel:b,onClick:x,onDoubleClick:x},ee=e=>(l.buttons&e)!==0,te=e=>`border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.35)] transition-colors duration-75 ${e?`border-white bg-white/50`:`border-white/70 bg-white/10`}`,C=`text-white [text-shadow:0_1px_2px_rgba(0,0,0,0.6)]`,ne={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},w=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),re=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,ie={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ae=(e,t,n,r)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${re} ${n}`,style:ie,children:r}),oe=(e,t,n,r)=>(0,L.jsx)(`span`,{className:`flex h-[32px] w-[76px] items-center justify-center text-[13px] font-semibold tracking-wide ${C} ${te(t)}`,style:{borderRadius:r?n===`l`?`16px 9px 9px 9px`:`9px 16px 9px 9px`:`9px`},children:e}),se=(e,t,n,r)=>ae(e,t,`h-[44px] w-[84px]`,oe(e,ee(t),n,r)),ce=(e,t,n)=>(0,L.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${re} h-[44px] w-[84px]`,style:ie,children:oe(e,l[t]>0,n,!0)}),le=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:(0,L.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...w(ee(t)),children:[(0,L.jsx)(`path`,{d:`M10 9 Q10 3 16 3 L36 3 Q42 3 42 9 L42 30 Q42 34.5 38.5 38 L29.5 47 Q26 50.5 22.5 47 L13.5 38 Q10 34.5 10 30 Z`}),(0,L.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),ue=(e,t,n)=>ae(e,t,`h-[52px] w-[52px]`,(0,L.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:ne,children:[(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...w(ee(t))}),(0,L.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),de=(e,t)=>ae(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,L.jsx)(`span`,{className:`flex h-[24px] items-center rounded-full px-[10px] text-[10px] font-semibold uppercase tracking-wider ${C} ${te(ee(t))}`,children:e})),fe=(e,t)=>ae(e,t,`h-[44px] w-[44px]`,(0,L.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${C} ${te(ee(t))}`,children:e})),pe=e=>{let{dx:t,dy:n}=yo(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,L.jsx)(`div`,{"aria-label":e===`l`?o(`rp_touch_left_stick`,void 0,`Left stick`):o(`rp_touch_right_stick`,void 0,`Right stick`),onPointerDown:t=>v(t,t=>{let n=t.getBoundingClientRect();return{kind:`stick`,which:e,cx:n.left+n.width/2,cy:n.top+n.height/2,radius:n.width/2}}),...S,className:`pointer-events-auto relative h-[124px] w-[124px] touch-none rounded-full border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${r?`border-white/80 bg-white/[0.12]`:`border-white/45 bg-white/[0.05]`}`,children:(0,L.jsx)(`div`,{className:`absolute left-1/2 top-1/2 h-[54px] w-[54px] rounded-full ${te(r)}`,style:{transform:`translate(calc(-50% + ${t}px), calc(-50% + ${n}px))`}})})},E=t===`deck`,me=go(r,m.width,m.height,E),he=e=>`${e}px * var(--k)`,ge=`max(12px, env(safe-area-inset-left))`,ve=`max(12px, env(safe-area-inset-right))`,ye=`max(12px, env(safe-area-inset-bottom))`,be=E?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,xe=(e,t,n=0)=>t?n?`calc(${e} + max(${he(t)}, ${n}px))`:`calc(${e} + ${he(t)})`:e,Se=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),Ce=E&&vo(me,m.height),D=E?void 0:`58%`,O=e=>E?{top:xe(be,Ce?96:112,Ce?72:90),[e]:e===`left`?ge:ve}:{top:D,translate:`0 -50%`,[e]:e===`left`?ge:ve},we=e=>({bottom:Ce?ye:xe(ye,E?56:0,44),[e]:Ce?`calc(${e===`left`?ge:ve} + 8px + max(${he(80)}, 44px))`:xe(e===`left`?ge:ve,E?40:168)}),Te=!!a&&!E;return(0,L.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${E?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:E?i:void 0,"--k":me},"data-testid":`rp-touch`,"data-layout":t,"data-scale":me,onContextMenu:e=>e.preventDefault(),children:[(0,L.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:fo(n)},children:[(0,L.jsx)(`div`,{style:Se(`top left`,{top:be,left:ge}),children:(0,L.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:E?void 0:`6deg`,transformOrigin:`top left`},children:[ce(`L2`,`l2`,`l`),se(`L1`,F.L1,`l`,!1)]})}),(0,L.jsx)(`div`,{style:Se(`top right`,{top:be,right:ve}),children:(0,L.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:E?void 0:`-6deg`,transformOrigin:`top right`},children:[ce(`R2`,`r2`,`r`),se(`R1`,F.R1,`r`,!1)]})}),(0,L.jsx)(`div`,{"aria-label":o(`rp_touch_touchpad`,void 0,`Touchpad`),onPointerDown:e=>v(e,t=>({kind:`touchpad`,rect:t.getBoundingClientRect(),x0:e.clientX,y0:e.clientY,pressed:!0})),...S,className:`pointer-events-auto absolute touch-none rounded-2xl border-[1.5px] shadow-[0_0_3px_rgba(0,0,0,0.3)] transition-colors duration-75 ${d.touchpad?`border-white/80 bg-white/25`:`border-white/40 bg-white/[0.05]`}`,style:E?{top:xe(be,6),left:xe(ge,104),right:xe(ve,104),height:`max(44px, calc(${he(64)}))`}:{top:be,left:`50%`,translate:`-50% 0`,width:`min(calc(${he(250)}), 34vw)`,height:`max(44px, calc(${he(56)}))`}}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top left`:`left center`,O(`left`)),children:[(0,L.jsx)(`span`,{}),le(`↑`,F.UP,0),(0,L.jsx)(`span`,{}),le(`←`,F.LEFT,-90),(0,L.jsx)(`span`,{}),le(`→`,F.RIGHT,90),(0,L.jsx)(`span`,{}),le(`↓`,F.DOWN,180),(0,L.jsx)(`span`,{})]}),(0,L.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:Se(E?`top right`:`right center`,O(`right`)),children:[(0,L.jsx)(`span`,{}),ue(`△`,F.TRIANGLE,(0,L.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,L.jsx)(`span`,{}),ue(`□`,F.SQUARE,(0,L.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,L.jsx)(`span`,{}),ue(`○`,F.CIRCLE,(0,L.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,L.jsx)(`span`,{}),ue(`✕`,F.CROSS,(0,L.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,L.jsx)(`span`,{})]}),(0,L.jsx)(`div`,{style:Se(`bottom left`,we(`left`)),children:pe(`l`)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,we(`right`)),children:pe(`r`)}),(0,L.jsx)(`div`,{style:Se(`bottom left`,{bottom:ye,left:ge}),children:de(`Create`,F.SHARE)}),(0,L.jsx)(`div`,{style:Se(`bottom right`,{bottom:ye,right:ve}),children:de(`Options`,F.OPTIONS)}),(0,L.jsx)(`div`,{style:Se(`bottom center`,{bottom:Ce?xe(ye,124,88):xe(ye,Te?48:0,48),left:xo,translate:`-50% 0`}),children:fe(`PS`,F.PS)})]}),Te&&(0,L.jsx)(`div`,{style:{...Se(`bottom center`,{bottom:ye,left:`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,translate:`-50% 0`}),opacity:Math.max(.7,fo(n))},children:(0,L.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a?.()},onDoubleClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"aria-label":o(`rp_menu`,void 0,`Menu`),"aria-haspopup":`dialog`,className:`${re} h-[44px] w-[56px]`,style:ie,"data-testid":`rp-menu-handle`,children:(0,L.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${C} ${te(!1)}`,children:(0,L.jsx)(_e,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var To=class{constructor(e,t=()=>1){this.sink=e,this.speed=t,this.fingers=new Map,this.most=0,this.moved=!1,this.gestureT0=0,this.lastTap=null,this.dragging=!1}down(e,t,n,r){if(!this.fingers.size){this.most=0,this.moved=!1,this.gestureT0=r;let e=this.lastTap;e&&r-e.t<=300&&Math.hypot(t-e.x,n-e.y)<=40&&(this.dragging=!0,this.sink.button(0,!0)),this.lastTap=null}this.fingers.set(e,{x:t,y:n,x0:t,y0:n,t0:r}),this.most=Math.max(this.most,this.fingers.size)}move(e,t,n){let r=this.fingers.get(e);if(!r)return;let i=t-r.x,a=n-r.y;if(r.x=t,r.y=n,!this.moved&&Math.hypot(t-r.x0,n-r.y0)>10&&(this.moved=!0),!this.moved)return;if(this.fingers.size>=2){if(this.dragging)return;let e=this.fingers.size;this.sink.scroll(-a/e,-i/e);return}if(this.most>=2)return;let o=this.speed();this.sink.move(i*o,a*o)}up(e,t){let n=this.fingers.get(e);if(!n||(this.fingers.delete(e),this.fingers.size))return;if(this.dragging){this.dragging=!1,this.sink.button(0,!1);return}let r=t-this.gestureT0<=250+(this.most>=2?150:0);if(this.moved||!r)return;let i=this.most>=2?2:0;this.sink.button(i,!0),this.sink.button(i,!1),i===0&&(this.lastTap={t,x:n.x,y:n.y})}cancel(){this.fingers.clear(),this.lastTap=null,this.dragging&&(this.dragging=!1,this.sink.button(0,!1))}},Eo={" ":`Space`,"-":`Minus`,"=":`Equal`,"[":`BracketLeft`,"]":`BracketRight`,"\\":`Backslash`,";":`Semicolon`,"'":`Quote`,"`":`Backquote`,",":`Comma`,".":`Period`,"/":`Slash`,"\n":`Enter`,"\r":`Enter`," ":`Tab`},Do={"!":`Digit1`,"@":`Digit2`,"#":`Digit3`,$:`Digit4`,"%":`Digit5`,"^":`Digit6`,"&":`Digit7`,"*":`Digit8`,"(":`Digit9`,")":`Digit0`,_:`Minus`,"+":`Equal`,"{":`BracketLeft`,"}":`BracketRight`,"|":`Backslash`,":":`Semicolon`,'"':`Quote`,"~":`Backquote`,"<":`Comma`,">":`Period`,"?":`Slash`};function Oo(e){return e.length===1?e>=`a`&&e<=`z`?{code:`Key${e.toUpperCase()}`,shift:!1}:e>=`A`&&e<=`Z`?{code:`Key${e}`,shift:!0}:e>=`0`&&e<=`9`?{code:`Digit${e}`,shift:!1}:Eo[e]?{code:Eo[e],shift:!1}:Do[e]?{code:Do[e],shift:!0}:null:null}var ko={Backspace:`Backspace`,Enter:`Enter`,Tab:`Tab`,Escape:`Escape`,Delete:`Delete`,ArrowUp:`ArrowUp`,ArrowDown:`ArrowDown`,ArrowLeft:`ArrowLeft`,ArrowRight:`ArrowRight`,Home:`Home`,End:`End`,PageUp:`PageUp`,PageDown:`PageDown`};function Ao(e){return ko[e]??null}function jo(e,t){let n=``;for(let r of t){let t=Oo(r);t?Mo(e,t.code,t.shift):n+=r}return n}function Mo(e,t,n=!1){let r=n&&!e.shiftHeld?.();r&&e.key(`ShiftLeft`,!0),e.key(t,!0),e.key(t,!1),r&&e.key(`ShiftLeft`,!1)}function No(e,t){let n=[...e],r=[...t],i=0;for(;i{o.current=e,s.current=t});let c=(0,T.useRef)(null),l=()=>c.current??=new To({move:(e,t)=>o.current?.move(e,t),button:(e,t)=>o.current?.button(e,t),scroll:(e,t)=>o.current?.scroll(e,t)},()=>s.current);(0,T.useEffect)(()=>()=>c.current?.cancel(),[]);let u=e=>e.stopPropagation();return(0,L.jsx)(`div`,{className:`touch-none select-none [-webkit-touch-callout:none] ${n}`,style:r,"data-testid":a,onPointerDown:e=>{u(e);try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}l().down(e.pointerId,e.clientX,e.clientY,e.timeStamp)},onPointerMove:e=>{u(e),l().move(e.pointerId,e.clientX,e.clientY)},onPointerUp:e=>{u(e),l().up(e.pointerId,e.timeStamp)},onPointerCancel:e=>{u(e),l().cancel()},onClick:u,onDoubleClick:u,onContextMenu:e=>{e.preventDefault(),u(e)},children:i})}var R=` `,Fo=40;function Io({sink:e,onUntypeable:t,className:n=``}){let r=Tn(),i=(0,T.useRef)(null),a=(0,T.useRef)(R),o=(0,T.useRef)(!1),[s,c]=(0,T.useState)(!1),[l,u]=(0,T.useState)(!1);(0,T.useEffect)(()=>{if(!l)return;let e=window.setTimeout(()=>u(!1),3e3);return()=>window.clearTimeout(e)},[l]);let d=()=>{let e=i.current;e&&!o.current&&(!e.value.startsWith(R)||e.value.length>Fo)&&(e.value=R,a.current=R)},f=()=>{let n=i.current;if(!n||!e)return;let{deleted:r,inserted:o}=No(a.current,n.value);a.current=n.value;for(let t=0;te.stopPropagation(),onClick:e=>{e.stopPropagation();let t=i.current;t&&(s?t.blur():(t.value=R,a.current=R,t.focus({preventScroll:!0}),t.setSelectionRange(t.value.length,t.value.length)))},className:`flex h-11 w-11 items-center justify-center rounded-full border border-white/25 bg-black/45 text-white backdrop-blur-sm disabled:opacity-40 ${s?`bg-white/30`:``} ${n}`,"data-testid":`rp-tp-keyboard`,children:(0,L.jsx)(he,{size:18,"aria-hidden":!0})}),(0,L.jsx)(`input`,{ref:i,type:`text`,defaultValue:R,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,spellCheck:!1,enterKeyHint:`send`,"aria-label":r(`rp_tp_keyboard`,void 0,`Keyboard`),className:`pointer-events-none fixed bottom-0 left-1/2 h-px w-px opacity-0`,"data-testid":`rp-tp-keyboard-input`,"data-rp-typing":``,onFocus:()=>c(!0),onBlur:()=>c(!1),onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onKeyDown:t=>{if(t.stopPropagation(),!e||t.nativeEvent.isComposing)return;let n=Ao(t.key);n&&(t.preventDefault(),Mo(e,n))},onKeyUp:e=>e.stopPropagation(),onCompositionStart:()=>{o.current=!0},onCompositionEnd:()=>{o.current=!1,f()},onInput:f}),l&&(0,L.jsx)(`div`,{className:`pointer-events-none fixed bottom-20 left-1/2 z-[300] w-max max-w-[min(22rem,calc(100%-2rem))] -translate-x-1/2 rounded-full bg-black/80 px-3 py-1.5 text-center text-xs text-white`,"data-testid":`rp-tp-untypeable`,children:r(`rp_tp_untypeable`,void 0,`Only English letters, numbers and symbols can be typed here. Use a text field on the PS5 for others.`)})]})}function Lo({mode:e,onChange:t,blocked:n,style:r,touchpadLabel:i,tight:a=!1,hidden:o=!1}){let s=Tn(),c=(r,i,o)=>{let s=r===`touchpad`&&!!n;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":e===r,"aria-disabled":s||void 0,"aria-label":a&&e!==r?o:void 0,title:s?n:o,onClick:e=>{e.stopPropagation(),s||t(r)},onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),className:`flex h-8 items-center gap-1 rounded-full px-2.5 text-xs ${e===r?`bg-white text-black`:`text-white`} ${s?`opacity-40`:``}`,"data-testid":`rp-touch-mode-${r}`,children:[i,(!a||e===r)&&(0,L.jsx)(`span`,{children:o})]})};return(0,L.jsxs)(`div`,{role:`radiogroup`,"aria-label":s(`rp_tp_mode`,void 0,`Touch controls`),"aria-hidden":o||void 0,className:`absolute left-1/2 z-30 flex -translate-x-1/2 gap-0.5 rounded-full border border-white/20 bg-black/50 p-0.5 backdrop-blur-sm transition-opacity duration-200 ${o?`pointer-events-none opacity-0`:`pointer-events-auto opacity-100`}`,style:r,"data-testid":`rp-touch-mode`,children:[c(`controller`,(0,L.jsx)(E,{size:14,"aria-hidden":!0}),s(`rp_kbm_controller`,void 0,`Controller`)),c(`touchpad`,(0,L.jsx)(ye,{size:14,"aria-hidden":!0}),i??s(`rp_tp_touchpad`,void 0,`Touchpad`))]})}var Ro={0:1,2:2,1:4,3:8,4:16},zo={ControlLeft:1,ShiftLeft:2,AltLeft:4,MetaLeft:8,OSLeft:8,ControlRight:16,ShiftRight:32,AltRight:64,MetaRight:128,OSRight:128};function Bo(){let e={};for(let t=0;t<26;t++)e[`Key${String.fromCharCode(65+t)}`]=4+t;for(let t=1;t<=9;t++)e[`Digit${t}`]=30+t-1;e.Digit0=39,Object.assign(e,{Enter:40,Escape:41,Backspace:42,Tab:43,Space:44,Minus:45,Equal:46,BracketLeft:47,BracketRight:48,Backslash:49,IntlHash:50,Semicolon:51,Quote:52,Backquote:53,Comma:54,Period:55,Slash:56,CapsLock:57,PrintScreen:70,ScrollLock:71,Pause:72,Insert:73,Home:74,PageUp:75,Delete:76,End:77,PageDown:78,ArrowRight:79,ArrowLeft:80,ArrowDown:81,ArrowUp:82,NumLock:83,NumpadDivide:84,NumpadMultiply:85,NumpadSubtract:86,NumpadAdd:87,NumpadEnter:88,NumpadDecimal:99,IntlBackslash:100,ContextMenu:101,NumpadEqual:103,IntlRo:135,KanaMode:136,IntlYen:137,Convert:138,NonConvert:139,Lang1:144,Lang2:145});for(let t=1;t<=9;t++)e[`Numpad${t}`]=89+t-1;e.Numpad0=98;for(let t=1;t<=12;t++)e[`F${t}`]=58+t-1;for(let t=13;t<=24;t++)e[`F${t}`]=104+t-13;return e}var Vo=Bo(),Ho=(e,t,n)=>Math.max(t,Math.min(n,Math.trunc(e)));function Uo(e,t=0,n=0,r=0,i=0){let a=new Uint8Array(17),o=new DataView(a.buffer);return a[0]=8,a[1]=e.buttons&255,a[2]=e.mods&255,o.setInt16(3,Ho(t,-32768,32767),!0),o.setInt16(5,Ho(n,-32768,32767),!0),o.setInt8(7,Ho(r,-128,127)),o.setInt8(8,Ho(i,-128,127)),e.keys.slice(0,8).forEach((e,t)=>a[9+t]=e&255),a}function Wo(e){let t={buttons:0,mods:0,keys:[]};for(let n of e){t.buttons|=n.buttons,t.mods|=n.mods;for(let e of n.keys)!t.keys.includes(e)&&t.keys.length<8&&t.keys.push(e)}return t}function z(e,t,n){let r=e+t/(n===1?3:n===2?1:100),i=Math.trunc(r);return{notches:-i,carry:r-i}}var B=class{constructor(e){this.st={buttons:0,mods:0,keys:[]},this.dx=0,this.dy=0,this.wheel=0,this.hwheel=0,this.wheelCarry=0,this.hwheelCarry=0,this.moveTimer=null,this.hb=null,this.want={mouse:!1,keyboard:!1},this.guests=new Map,this.d={setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>window.clearTimeout(e),setRepeat:(e,t)=>window.setInterval(e,t),clearRepeat:e=>window.clearInterval(e),...e}}get state(){return this.st}shiftHeld(){return(this.st.mods&(zo.ShiftLeft|zo.ShiftRight))!==0}get holding(){return this.st.buttons!==0||this.st.mods!==0||this.st.keys.length>0}setWant(e){let t=e.mouse||e.keyboard,n=e.mouse!==this.want.mouse||e.keyboard!==this.want.keyboard;this.want={...e},n&&(this.hb!==null&&this.d.clearRepeat(this.hb),this.hb=null,this.beat(),t&&(this.hb=this.d.setRepeat(()=>this.beat(),500)))}get wanted(){return this.want}beat(){let e=this.want.mouse||this.want.keyboard;this.d.send({kbm:e?{on:!0,mouse:this.want.mouse,keyboard:this.want.keyboard}:{on:!1}})}key(e,t){let n=zo[e];if(n){let e=t?this.st.mods|n:this.st.mods&~n;return e!==this.st.mods&&(this.st={...this.st,mods:e},this.flush()),!0}let r=Vo[e];if(!r)return!1;let i=this.st.keys.includes(r);return t&&!i&&this.st.keys.length<8?(this.st={...this.st,keys:[...this.st.keys,r]},this.flush()):!t&&i&&(this.st={...this.st,keys:this.st.keys.filter(e=>e!==r)},this.flush()),!0}button(e,t){let n=Ro[e];if(!n)return;let r=t?this.st.buttons|n:this.st.buttons&~n;r!==this.st.buttons&&(this.st={...this.st,buttons:r},this.flush())}guest(e,t){if(t)this.guests.set(e,{buttons:t.buttons,mods:t.mods,keys:t.keys.slice(0,8)});else if(!this.guests.delete(e))return;this.flush()}guestMotion(e,t,n,r){this.dx+=e,this.dy+=t,this.wheel+=n,this.hwheel+=r,(e||t||n||r)&&this.later()}get guestIds(){return[...this.guests.keys()]}move(e,t){this.dx+=e,this.dy+=t,this.later()}scroll(e,t,n){let r=z(this.wheelCarry,e,n),i=z(this.hwheelCarry,t,n);this.wheelCarry=r.carry,this.hwheelCarry=i.carry,this.wheel+=r.notches,this.hwheel-=i.notches,(this.wheel||this.hwheel)&&this.later()}later(){this.moveTimer===null&&(this.moveTimer=this.d.setTimer(()=>this.flush(),4))}flush(){this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null;let e=this.guests.size?Wo([this.st,...this.guests.values()]):this.st;do{let t=Ho(this.dx,-32768,32767),n=Ho(this.dy,-32768,32767),r=Ho(this.wheel,-128,127),i=Ho(this.hwheel,-128,127);this.dx-=t,this.dy-=n,this.wheel-=r,this.hwheel-=i,this.d.send(Uo(e,t,n,r,i))}while(Math.abs(this.dx)>=1||Math.abs(this.dy)>=1||this.wheel||this.hwheel)}releaseAll(){this.dx=this.dy=this.wheel=this.hwheel=0,this.wheelCarry=this.hwheelCarry=0;let e=this.holding;this.st={buttons:0,mods:0,keys:[]},this.moveTimer!==null&&this.d.clearTimer(this.moveTimer),this.moveTimer=null,e&&this.d.send(Uo(this.guests.size?Wo(this.guests.values()):this.st))}dispose(){this.guests.clear(),this.releaseAll(),this.setWant({mouse:!1,keyboard:!1})}},Go=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,Ko=null,qo=null;function Jo(e){e.play().catch(()=>{if(qo||Ko!==e)return;let t=()=>{Yo(),Ko===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),qo=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function Yo(){qo?.(),qo=null}function Xo(){if(typeof document<`u`){if(!Ko){let e=document.createElement(`video`);e.muted=!0,e.loop=!0,e.playsInline=!0,e.setAttribute(`playsinline`,``),e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-testid`,`keep-screen-video`),e.style.cssText=`position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none`,e.src=Go,document.body.appendChild(e),Ko=e}Jo(Ko)}}function Zo(){Yo(),Ko&&=(Ko.pause(),Ko.removeAttribute(`src`),Ko.remove(),null)}function Qo(){return typeof navigator>`u`?null:navigator.wakeLock??null}function V(){return Te()||!gn()}var $o=new Set,es=null,ts=Promise.resolve(),ns=!1;async function rs(){if($o.size===0||es&&!es.released)return;let e=Qo();if(!e)Te()&&Xo();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{es===t&&(es=null)}),es=t}catch{}}async function is(){Zo();let e=es;if(es=null,e&&!e.released)try{await e.release()}catch{}}function as(){ns||typeof document>`u`||(ns=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&$o.size>0&&(ts=ts.then(rs))}))}function os(e,t){if(!V())return;as();let n=$o.size>0;t?$o.add(e):$o.delete(e);let r=$o.size>0;n!==r&&(ts=ts.then(r?rs:is))}var ss=new Set;function cs(){if(typeof window<`u`)return window.PS5UploadPad}function ls(e,t){let n=ss.size>0;t?ss.add(e):ss.delete(e);let r=ss.size>0;if(n!==r)try{cs()?.setActive(r)}catch{}}function us(e,t){let[n,r]=(0,T.useState)(!1);return(0,T.useEffect)(()=>{if(!e||!t)return;let n=!0;return Pe(e,je).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function ds({href:e}){let t=Tn();return(0,L.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t(`join_open_lan_body`,void 0,`Can't reach the internet? If you're on the same Wi-Fi as your friend, open the game there.`)}),(0,L.jsx)(`a`,{href:e,rel:`noreferrer`,className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`open-on-wifi-link`,children:t(`join_open_lan`,void 0,`Open on this Wi-Fi`)})]})}function fs(e,t,n){switch(t.kind){case`connecting`:return e(`pad_connecting`,void 0,`Connecting…`);case`asking`:return e(`pad_asking`,{name:n},`Waiting for ${n} to allow this phone…`);case`joined`:return t.host?t.passcode&&!t.playing?e(`pad_wait_passcode`,{name:n},`Waiting for the passcode on ${n}`):t.playing?e(`pad_playing`,{host:t.host},`Controller for ${t.host}`):e(`pad_starting`,void 0,`Connected. The stream is starting…`):e(`pad_no_session`,void 0,`Connected. Waiting for Remote Play to start on the computer.`);case`refused`:return t.why===`denied`?e(`pad_denied`,void 0,`The computer said no.`):t.why===`no_answer`?e(`pad_no_answer`,void 0,`The computer didn't answer in time. Try again.`):t.why===`kicked`?e(`pad_kicked`,void 0,`The computer took this phone out of the game.`):t.why===`closed`?e(`pad_link_closed`,void 0,`The computer closed the link. Scan the new code to play again.`):t.why===`key`?e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`):t.why===`full`?e(`pad_full`,void 0,`Four phones are playing already.`):t.why===`no_stream`?e(`pad_watch_no_stream`,void 0,`Nothing is streaming on the computer right now.`):t.why.startsWith(`net:`)?ps(e,t.why.slice(4)):e(`pad_refused`,void 0,`The computer did not let this phone in.`);case`reconnecting`:return e(`pad_reconnecting`,void 0,`Connection lost. Reconnecting…`);case`lost`:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ps(e,t){switch(t){case`mismatch`:return e(`join_net_mismatch`,void 0,`This link doesn't match the host; ask them for a new one.`);case`no_direct`:return e(`join_net_no_direct`,void 0,`A direct connection isn't possible from this network (both sides' routers are strict). Try Wi-Fi instead of mobile data, or ask the host to turn on UPnP.`);case`no_room`:return e(`pad_old_code`,void 0,`This code has expired. Scan the new one on the computer.`);case`net_full`:return e(`pad_full`,void 0,`Four phones are playing already.`);case`no_hub`:return e(`join_net_no_hub`,void 0,`Couldn't reach the PS5Upload invite service. Check your internet connection, then try again.`);case`offer`:case`no_webrtc`:return e(`join_net_no_webrtc`,void 0,`This browser can't make direct connections. Try a recent Chrome, Safari or Firefox.`);default:return e(`pad_lost`,void 0,`Lost the connection to the computer.`)}}function ms(e){return e.kind!==`refused`||e.why!==`kicked`&&e.why!==`closed`}async function hs(){try{await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)}catch{}}function gs(e,t){return t?.mouse?null:t?.reason===`vinput_helper_old`||t?.reason===`helper_old`?e(`rp_kbm_helper_old`,void 0,`Update the PS5 helper to use a keyboard and mouse.`):t?.reason===`vinput_needs_loader`?e(`rp_kbm_needs_loader`,void 0,`Needs a payload loader on port 9021`):e(`rp_kbm_unavailable`,void 0,`Native keyboard & mouse isn't available on this console yet.`)}function _s({client:e,caps:t}){let n=Tn(),r=(0,T.useMemo)(()=>new B({send:t=>e.sendKbm(t)}),[e]);(0,T.useEffect)(()=>{r.setWant({mouse:!0,keyboard:t.keyboard})},[r,t.keyboard]),(0,T.useEffect)(()=>()=>r.dispose(),[r]);let i=(0,T.useMemo)(()=>({move:(e,t)=>r.move(e,t),button:(e,t)=>r.button(e,t),scroll:(e,t)=>r.scroll(e,t,0),key:(e,t)=>r.key(e,t),shiftHeld:()=>r.shiftHeld()}),[r]);return(0,L.jsxs)(Po,{sink:i,speed:1.5,className:`absolute inset-0 z-10`,testId:`pad-touchpad`,children:[(0,L.jsx)(`p`,{className:`pointer-events-none absolute inset-x-6 top-1/2 -translate-y-1/2 text-center text-xs leading-5 text-white/50`,children:n(`rp_tp_tips`,void 0,`Drag to move. Tap to click. Two fingers: tap to right-click, drag to scroll. Tap, then touch and drag to select.`)}),(0,L.jsx)(`div`,{className:`absolute`,style:{right:`max(12px, env(safe-area-inset-right))`,bottom:`max(12px, env(safe-area-inset-bottom))`},children:(0,L.jsx)(Io,{sink:t.keyboard?i:null})})]})}function vs({url:e,computer:t,onLeave:n,watch:r=!1,transport:i,hello:a,onReconnectToken:o,lanUrl:s=null}){let c=Tn(),l=us(i?e:null,s),u=t??c(`pad_net_computer`,void 0,`the computer`),[d,f]=(0,T.useState)({kind:`connecting`}),[p,m]=(0,T.useState)(0),[h,g]=(0,T.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),ee=(0,T.useRef)(null),te=(0,T.useRef)(null),[C,ne]=(0,T.useState)(!r),[w,re]=(0,T.useState)(null),[ie,ae]=(0,T.useState)(!1),[oe,se]=(0,T.useState)(null),[ce,le]=(0,T.useState)(`controller`);(0,T.useEffect)(()=>(os(`pad-remote`,!0),ls(`pad-remote`,!0),()=>{os(`pad-remote`,!1),ls(`pad-remote`,!1)}),[]),(0,T.useEffect)(()=>{if(!x)return;let e=Ae(e=>{co.motion=e});return()=>{e(),co.motion=null}},[x]),(0,T.useEffect)(()=>{let t=r?Zi(re,`watch`,()=>n.askKeyframe()):null;ee.current=t,t&&te.current?.appendChild(t.element),ne(!r),ae(!1);let n=new io({url:e,WebSocketImpl:i,hello:a,onReconnectToken:o,onStage:f,touchPad:()=>co.touchPad,onLight:v,onKbmCaps:se,motion:()=>co.motion,watch:t?{onFrame:e=>t.onMessage(e),onCodec:e=>t.setHevc(e),onControl:ne}:void 0});b(n),n.start();let s=()=>{let e=document.visibilityState===`hidden`;n.setNeutral(e),e||n.wake()},c=()=>n.setNeutral(!0);return document.addEventListener(`visibilitychange`,s),window.addEventListener(`blur`,c),window.addEventListener(`focus`,s),()=>{document.removeEventListener(`visibilitychange`,s),window.removeEventListener(`blur`,c),window.removeEventListener(`focus`,s),n.stop(),t?.stop(),t?.element.remove()}},[e,p,r]),(0,T.useEffect)(()=>{let e=()=>g(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ue=d.kind===`refused`||d.kind===`lost`,de=d.kind===`joined`||d.kind===`reconnecting`,pe=!!s&&!de&&(l||d.kind===`refused`&&d.why===`net:no_hub`);return(0,L.jsxs)(`div`,{className:`fixed inset-0 select-none overflow-hidden bg-black text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},"data-testid":`pad-app`,children:[(0,L.jsxs)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex items-center justify-center gap-2 px-3 pt-[max(6px,env(safe-area-inset-top))] text-xs text-white/80`,children:[(0,L.jsx)(`span`,{className:`inline-block h-2 w-2 shrink-0 rounded-full`,style:{background:d.kind===`joined`?_?`rgb(${_[0]},${_[1]},${_[2]})`:`var(--color-success,#22c55e)`:ue?`var(--color-bad,#ef4444)`:`#eab308`}}),(0,L.jsx)(`span`,{className:`truncate`,"data-testid":`pad-stage`,children:r&&d.kind===`joined`&&d.host&&(!d.passcode||d.playing)?C?c(`pad_watch_control`,void 0,`Watching, and you have the controller`):c(`pad_watch_watching`,{host:d.host},`Watching ${d.host}`):fs(c,d,u)}),de&&typeof document<`u`&&!!document.documentElement.requestFullscreen&&!document.fullscreenElement&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void hs(),className:`flex items-center gap-1 rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-full`,children:[(0,L.jsx)(fe,{size:12}),c(`pad_fill`,void 0,`Full screen`)]}),de&&k()&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>{x?S(!1):ke().then(S)},"aria-pressed":x,className:`rounded-full px-2 py-1 ${x?`bg-white text-black`:`bg-white/15`}`,"data-testid":`pad-motion`,children:c(`pad_motion`,void 0,`Motion`)}),n&&(0,L.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-2 py-1`,"data-testid":`pad-leave`,children:c(`pad_leave`,void 0,`Stop being a controller`)})]}),(0,L.jsx)(`div`,{ref:te,className:`absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),r&&de&&!ie&&(0,L.jsxs)(`button`,{type:`button`,onClick:()=>{ee.current?.startSound(),ae(!0)},className:`absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full bg-white/90 px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`watch-sound`,children:[(0,L.jsx)(Ce,{size:14}),c(`pad_watch_sound`,void 0,`Sound`)]}),r&&w&&(0,L.jsx)(`p`,{className:`absolute inset-x-4 top-1/2 z-10 -translate-y-1/2 text-center text-sm text-white/85`,"data-testid":`watch-problem`,children:w===`no_hevc`?c(`pad_watch_no_hevc`,void 0,`This device can't play this stream's picture: the computer streams HEVC, and this device plays only H.264.`):c(`pad_watch_decode`,void 0,`The picture could not be played here.`)}),de&&C&&(ce===`touchpad`&&oe?.mouse&&y?(0,L.jsx)(_s,{client:y,caps:oe}):(0,L.jsx)(wo,{stream:y,layout:`overlay`})),de&&C&&(0,L.jsx)(Lo,{mode:ce===`touchpad`&&oe?.mouse?`touchpad`:`controller`,onChange:le,blocked:gs(c,oe),touchpadLabel:c(`pad_touchpad_tab`,void 0,`Touchpad & keyboard`),style:{top:`calc(max(6px, env(safe-area-inset-top)) + 2rem)`}}),de&&h&&(0,L.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center`,children:(0,L.jsxs)(`span`,{className:`flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-xs text-white/85`,children:[(0,L.jsx)(xe,{size:14}),c(`pad_turn`,void 0,`Turn the phone sideways`)]})}),pe&&!ue&&s&&(0,L.jsx)(`div`,{className:`absolute inset-x-0 bottom-8 z-10 flex justify-center px-6`,children:(0,L.jsx)(ds,{href:s})}),ue&&(0,L.jsxs)(`div`,{className:`absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 px-6 text-center text-sm`,children:[(0,L.jsx)(`p`,{className:`max-w-sm text-white/85`,children:fs(c,d,u)}),pe&&s&&(0,L.jsx)(ds,{href:s}),ms(d)&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e+1),className:`rounded-full bg-white px-4 py-2 text-sm font-medium text-black`,"data-testid":`pad-retry`,children:c(`pad_retry`,void 0,`Try again`)})]})]})}var ys=`ps5upload.openIn`,bs=`ps5upload.openIn.tab`;function xs(){try{return sessionStorage.getItem(bs)===`browser`}catch{return!1}}function Ss(){try{sessionStorage.setItem(bs,`browser`)}catch{}}function Cs(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function ws({appLink:e,children:t}){let n=Tn(),[r,i]=(0,T.useState)(()=>xs()?`browser`:Cs(yt(ys))),[a,o]=(0,T.useState)(!1);if((0,T.useEffect)(()=>{r===`opening`&&yt(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,L.jsx)(L.Fragment,{children:t});let s=()=>{a&&vt(ys,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?vt(ys,`browser`):r===`opening`&&yt(`ps5upload.openIn`)===`app`&&bt(ys),Ss(),i(`browser`)};return(0,L.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,"data-join-ui":``,children:(0,L.jsx)(`div`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,children:r===`ask`?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_body`,void 0,`Have the PS5Upload app on this device? Open this there, or carry on in the browser.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:s,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-app`,children:n(`open_in_app`,void 0,`Open in the app`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)}),(0,L.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,L.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked),"data-testid":`open-in-remember`}),n(`open_in_remember`,void 0,`Remember my choice on this device`)]})]}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:`space-y-1`,children:[(0,L.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,L.jsx)(`p`,{className:`text-sm text-white/60`,children:n(`open_in_not_opened`,void 0,`Nothing happened? The app may not be on this device.`)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>location.href=e,autoFocus:!0,className:`w-full rounded-full bg-white py-2.5 text-sm font-semibold text-black`,"data-testid":`open-in-again`,children:n(`open_in_again`,void 0,`Try again`)}),(0,L.jsx)(`button`,{type:`button`,onClick:c,className:`w-full rounded-full border border-white/20 py-2.5 text-sm font-semibold text-white hover:bg-white/10`,"data-testid":`open-in-browser`,children:n(`open_in_browser`,void 0,`Continue in browser`)})]})})})}function Ts(e){return`ps5upload://pad?link=${encodeURIComponent(e)}`}function Es(e){let t=(e??``).trim().replace(/^\[|\]$/g,``).toLowerCase(),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(n){let e=n.slice(1).map(Number);if(e.some(e=>e>255))return null;let[t,r]=e;return t===10||t===172&&r>=16&&r<32||t===192&&r===168||t===169&&r===254||t===127?0:t===100&&r>=64&&r<128?1:2}if(!t.includes(`:`)||!/^[0-9a-f:.]+$/.test(t))return null;if(t.startsWith(`fd7a:115c:a1e0:`))return 1;let r=parseInt(t.split(`:`)[0]||`0`,16);return(r&65024)==64512||(r&65472)==65152||t===`::1`?0:2}function Ds(e,t){let n=Es(e),r=Es(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Os(e){let t=[];if(typeof e.forEach==`function`)e.forEach(e=>t.push(e));else for(let n of e)t.push(n);let n=new Map(t.map(e=>[String(e.id),e])),r=t.filter(e=>e.type===`candidate-pair`),i=t.filter(e=>e.type===`transport`&&typeof e.selectedCandidatePairId==`string`).map(e=>n.get(String(e.selectedCandidatePairId))).find(Boolean)??r.find(e=>e.selected===!0)??r.find(e=>e.nominated===!0&&e.state===`succeeded`);if(!i)return null;let a=e=>{let t=n.get(String(e));if(!t)return null;let r=t.address??t.ip;return typeof r==`string`?r:null};return Ds(a(i.localCandidateId),a(i.remoteCandidateId))}function ks(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function As(e){let t=new Set;for(let n of e.matchAll(/^a=fingerprint:sha-256[ \t]+([0-9A-Fa-f:]+)[ \t]*\r?$/gim))t.add(n[1].toUpperCase());return/^a=fingerprint:(?!sha-256[ \t])/im.test(e)?null:t.size===1?[...t][0]:null}function js(e,t){let n=As(e);return n!==null&&n===t.toUpperCase()}var Ms=16777216;function Ns(e){let t=16383,n=Math.max(1,Math.ceil(e.length/t)),r=[];for(let i=0;ithis.max)return this.parts=[],this.size=0,{kind:`error`,why:`too_big`};if(this.parts.push(r.slice()),this.size+=r.length,n===1)return{kind:`partial`};let i=new Uint8Array(this.size),a=0;for(let e of this.parts)i.set(e,a),a+=e.length;return this.parts=[],this.size=0,{kind:`message`,data:i.buffer}}};function Fs(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Is=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Ls=1500,Rs=2e4;function zs(e){let t=e?.codecs??[],n=e=>t.filter(t=>t.mimeType.toLowerCase()===e);return[...n(`video/h264`),...n(`video/h265`),...n(`video/rtx`)]}var Bs=null;function Vs(e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}function Hs(e,t){let n=Bs;return n?(Bs=null,n.timer&&clearTimeout(n.timer),n.url!==e||n.room!==t||n.ws.readyState>1||n.msgs.some(e=>e.t===`error`||e.t===`closed`)?(Vs(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Us(e,t={}){var n;let r=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket),i=t.PeerConnection??(typeof RTCPeerConnection>`u`?void 0:RTCPeerConnection),a=t.iceTimeoutMs??15e3,o=t.log??(()=>{});class s{constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.readyState=0,this.binaryType=`arraybuffer`,this.onopen=null,this.onmessage=null,this.onclose=null,this.onerror=null,this.hub=null,this.pc=null,this.dc=null,this.timer=null,this.rx=new Ps,this.answered=!1,this.early=[],this.hubBackUntil=0,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[],this.media=null,setTimeout(()=>this.begin(),0)}begin(){if(this.readyState!==0)return;if(!i||!r){this.fail(`no_webrtc`);return}let n=t.signalUrl??ks(e.hub),a=t.signalUrl||t.lan?null:Hs(n,e.room),s;if(a)s=a.ws,o(`hub: joined early`);else try{s=new r(n)}catch{this.fail(`no_hub`);return}if(this.hub=s,this.prepare(),this.readyState===0){s.onopen=()=>s.send(JSON.stringify(t.lan?{v:1,t:`join`,lan:!0}:{v:1,t:`join`,room:e.room})),s.onmessage=e=>{if(typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}this.onHub(t)},s.onclose=e=>{this.hub===s&&(this.hub=null,this.readyState===0&&(this.answered||e?.code===1001&&this.hubRestarting()||this.fail(`no_hub`)))},s.onerror=()=>{};for(let e of a?.msgs??[])this.onHub(e)}}signal(e){let t=this.hub;t&&t.readyState===1&&t.send(JSON.stringify({t:`signal`,to:`host`,data:e}))}onHub(e){if(this.readyState===0)switch(e.t){case`joined`:o(`hub: joined room as ${e.gid??`?`}`),this.sendOffer();return;case`signal`:e.from===`host`&&e.data&&typeof e.data==`object`&&this.onSignal(e.data);return;case`closed`:this.fail(`no_room`);return;case`error`:if(o(`hub: error ${e.why??`?`}`),e.why===`no_room`&&this.hubBackUntil&&this.hubRestarting())return;this.fail(e.why===`no_room`?`no_room`:e.why===`room_full`?`net_full`:`no_hub`);return}}prepare(){if(!i)return;this.offerSent=!1,this.ownEarly=[];let e;try{e=new i({iceServers:[{urls:Is}]})}catch{this.fail(`no_webrtc`);return}this.pc=e;let n=e.createDataChannel(t.label??`join`,{ordered:!0});if(n.binaryType=`arraybuffer`,this.dc=n,n.onopen=()=>this.opened(n),n.onmessage=e=>this.fromChannel(e.data),n.onclose=()=>{this.dc===n&&this.dropped()},t.video&&e.addTransceiver){try{let t=e.addTransceiver(`video`,{direction:`recvonly`}),n=zs(globalThis.RTCRtpReceiver?.getCapabilities?.(`video`));n.length&&t.setCodecPreferences&&t.setCodecPreferences(n)}catch{}try{e.addTransceiver(`audio`,{direction:`recvonly`})}catch{}e.ontrack=t=>{if(this.pc!==e)return;let n=this.media?.stream??t.streams[0]??new MediaStream;n.getTracks().includes(t.track)||n.addTrack(t.track),this.media=t.track.kind===`audio`?{stream:n,receiver:this.media?.receiver??t.receiver,audio:t.receiver}:{stream:n,receiver:t.receiver,...this.media?.audio?{audio:this.media.audio}:{}}}}e.onicecandidate=t=>{if(this.pc!==e)return;let n=t.candidate;if(!n||!n.candidate)return;let r={type:`candidate`,candidate:n.candidate,sdpMid:n.sdpMid??`0`};this.offerSent?this.signal(r):this.ownEarly.push(r)},e.oniceconnectionstatechange=()=>{if(this.pc!==e)return;let t=e.iceConnectionState;o(`ice: ${t}`),t===`failed`&&(this.readyState===0?this.fail(`no_direct`):this.dropped())},this.offerSdp=(async()=>{let t=await e.createOffer();return await e.setLocalDescription(t),e.localDescription?.sdp??t.sdp??``})().catch(()=>(this.pc===e&&this.fail(`no_webrtc`),null))}async sendOffer(){let e=this.pc,t=this.offerSdp;if(!e||!t||this.offerSent)return;this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.readyState===0&&this.fail(`no_direct`)},a);let n=await t;if(this.pc===e&&n!==null&&this.readyState===0){this.signal({type:`offer`,sdp:n}),this.offerSent=!0;for(let e of this.ownEarly.splice(0))this.signal(e)}}async onSignal(t){let n=this.pc;if(t.type===`bye`)this.fail(t.why===`full`?`net_full`:`offer`);else if(n){if(t.type===`answer`){if(this.answered||typeof t.sdp!=`string`)return;if(e.fp?!js(t.sdp,e.fp):As(t.sdp)===null){o(`answer: fingerprint does not match the link`),this.fail(`mismatch`);return}this.answered=!0;try{await n.setRemoteDescription({type:`answer`,sdp:t.sdp});for(let e of this.early.splice(0))await n.addIceCandidate(e).catch(()=>{})}catch{this.fail(`offer`)}}else if(t.type===`candidate`&&typeof t.candidate==`string`&&t.candidate){let e={candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:`0`,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:0};this.answered?await n.addIceCandidate(e).catch(()=>{}):this.early.push(e)}}}opened(e){this.dc===e&&this.readyState===0&&(this.clearTimer(),this.readyState=1,o(`channel open`),this.leaveHub(),this.onopen?.(new Event(`open`)))}fromChannel(e){if(this.readyState!==1)return;if(typeof e==`string`){this.onmessage?.(new MessageEvent(`message`,{data:e}));return}if(!(e instanceof ArrayBuffer))return;let t=this.rx.push(e);switch(t.kind){case`ping`:try{this.dc?.send(Fs(t.data))}catch{}return;case`message`:this.onmessage?.(new MessageEvent(`message`,{data:t.data}));return;case`error`:o(`channel: bad binary message (${t.why})`),this.dropped();return;default:return}}async netPath(){let e=this.pc;if(!e||this.readyState!==1||typeof e.getStats!=`function`)return null;try{return Os(await e.getStats())}catch{return null}}send(e){let t=this.dc;if(this.readyState!==1||!t||t.readyState!==`open`)throw Error(`not open`);if(typeof e==`string`){t.send(e);return}let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(let e of Ns(n))t.send(e)}close(){this.readyState!==3&&(this.teardown(),this.emitClose(1e3,``,!0))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null}leaveHub(){let e=this.hub;if(this.hub=null,e)try{e.readyState===1&&e.send(JSON.stringify({t:`leave`})),e.close(1e3)}catch{}}hubRestarting(){let e=Date.now();return this.hubBackUntil||=e+Rs,e>=this.hubBackUntil?!1:(o(`hub: restarting, trying again`),this.clearTimer(),this.leaveHub(),this.closePeer(),this.answered=!1,this.early=[],this.timer=setTimeout(()=>{this.timer=null,this.begin()},Ls),!0)}teardown(){this.readyState=3,this.clearTimer(),this.leaveHub(),this.closePeer()}closePeer(){let e=this.pc,t=this.dc;this.pc=null,this.dc=null,this.media=null,this.offerSdp=null,this.offerSent=!1,this.ownEarly=[];try{t?.close()}catch{}try{e?.close()}catch{}}dropped(){this.readyState!==3&&(this.teardown(),this.emitClose(1006,``,!1))}fail(e){this.readyState!==3&&(o(`failed: ${e}`),this.teardown(),this.emitClose(Ie,`net:${e}`,!1))}emitClose(e,t,n){let r=this.onclose;if(!r)return;let i=typeof CloseEvent>`u`?{type:`close`,code:e,reason:t,wasClean:n}:new CloseEvent(`close`,{code:e,reason:t,wasClean:n});setTimeout(()=>r(i),0)}}return n=s,n.CONNECTING=0,n.OPEN=1,n.CLOSING=2,n.CLOSED=3,s}function Ws(e,t=0){return/iPad/.test(e)||/Macintosh/.test(e)&&t>1?`ipad`:/iPhone|iPod/.test(e)?`iphone`:/Android/.test(e)?`android`:`phone`}var Gs=new URLSearchParams(location.hash.slice(1)),Ks=Gs.get(`t`)??``,qs=Gs.get(`w`)===`1`,Js=Ws(navigator.userAgent,navigator.maxTouchPoints),Ys=oo({get:yt,set:vt}),Xs=Be(location.hash),Zs=(0,x.createRoot)(document.getElementById(`root`));if(Xs){let e=Us(Xs,{label:`pad`,log:e=>console.info(`[pad] ${e}`)}),t=`ps5upload.pad.rt.${Xs.room}`,n=yt(t),r={t:Xs.key,name:Js,d:Ys,...qs?{w:1}:{},...n?{rt:n}:{}},i=Me(location.hash,`pad`);Zs.render((0,L.jsx)(vs,{url:ks(Xs.hub),computer:null,watch:qs,transport:e,hello:r,onReconnectToken:e=>vt(t,e),lanUrl:i?Ne(i,{watch:qs}):null}))}else{let e=location.pathname.replace(/\/pad\/?$/,``),t=`${location.protocol===`https:`?`wss`:`ws`}://${location.host}${e}/api/pad/ws?t=${encodeURIComponent(Ks)}&name=${Js}&d=${Ys}${qs?`&w=1`:``}`;Zs.render((0,L.jsx)(ws,{appLink:Ts(location.href),children:(0,L.jsx)(vs,{url:t,computer:location.hostname,watch:qs})}))} From 6659e594f2e08526ea107996fd223137af0916c8 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 05:24:49 -0800 Subject: [PATCH 27/27] Android build: the app's lockfile takes the FTP library with name encodings The engine's FTP name fix uses suppaftp's Encoding, new in 12.2; the app's lockfile still had 12.1.0, so the Android build failed. Require 12.2.1 and move the app's lockfile to it (only that entry). A save restore test no longer prints the refusal text, which code scanning read as a user id. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/Cargo.lock | 4 ++-- engine/crates/ps5upload-engine/Cargo.toml | 2 +- engine/crates/ps5upload-engine/src/save_backup.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index e63897f3f..e4678a8a8 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -6445,9 +6445,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "suppaftp" -version = "12.1.0" +version = "12.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d79f066c76927a775d61b5642e0b712a17582ebe7f62b7e5abba246e619878f7" +checksum = "2b58fcf921745cca6f0127c9f822069947da8c6dbeff52e9004750bcc448171f" dependencies = [ "async-trait", "chrono", diff --git a/engine/crates/ps5upload-engine/Cargo.toml b/engine/crates/ps5upload-engine/Cargo.toml index caa56fe58..f5b8b3404 100644 --- a/engine/crates/ps5upload-engine/Cargo.toml +++ b/engine/crates/ps5upload-engine/Cargo.toml @@ -73,7 +73,7 @@ tower-http.workspace = true tower = { version = "0.5", default-features = false, features = ["util"] } uuid.workspace = true unicode-normalization = "0.1.25" -suppaftp = { version = "12", default-features = false, features = ["tokio-rustls-ring", "deprecated"] } +suppaftp = { version = "12.2.1", default-features = false, features = ["tokio-rustls-ring", "deprecated"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "logging"] } tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] } # Public roots for the Play Together relay's wss:// (already in the tree through ureq). diff --git a/engine/crates/ps5upload-engine/src/save_backup.rs b/engine/crates/ps5upload-engine/src/save_backup.rs index 0394bf6c8..f4e82edd7 100644 --- a/engine/crates/ps5upload-engine/src/save_backup.rs +++ b/engine/crates/ps5upload-engine/src/save_backup.rs @@ -3611,7 +3611,7 @@ mod tests { .unwrap_err(); assert!( e.contains("not a save folder") || e.contains("not a title ID"), - "{path:?} {title:?}: {e}" + "{path:?} {title:?}: refused for another reason" ); } let ok = "/user/home/1/savedata_prospero/PPSA01234";