From 182a49725d0de5a09a0d9d53813d87068a6a9c0d Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:22:17 -0800 Subject: [PATCH 01/25] Remove the above-13.60 fake-package warning: no public jailbreak goes past 13.60, so it can't show Keeps the fake-package note and the 11.61-13.60 kstuff hint on a failed launch. Convert marks the package once a game is checked; the image-on-this-firmware recommendation and its strings go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- FAQ.md | 7 +- .../FakeGameFirmwareNotice.test.tsx | 39 ----------- .../src/components/FakeGameFirmwareNotice.tsx | 67 ------------------- client/src/i18n/locales/ar.ts | 8 --- client/src/i18n/locales/bn.ts | 8 --- client/src/i18n/locales/de.ts | 8 --- client/src/i18n/locales/en.ts | 8 --- client/src/i18n/locales/es.ts | 8 --- client/src/i18n/locales/fa.ts | 8 --- client/src/i18n/locales/fr.ts | 8 --- client/src/i18n/locales/hi.ts | 8 --- client/src/i18n/locales/hu.ts | 8 --- client/src/i18n/locales/id.ts | 8 --- client/src/i18n/locales/it.ts | 8 --- client/src/i18n/locales/ja.ts | 8 --- client/src/i18n/locales/ko.ts | 8 --- client/src/i18n/locales/pl.ts | 8 --- client/src/i18n/locales/pt-BR.ts | 8 --- client/src/i18n/locales/ru.ts | 8 --- client/src/i18n/locales/th.ts | 8 --- client/src/i18n/locales/tr.ts | 8 --- client/src/i18n/locales/vi.ts | 8 --- client/src/i18n/locales/zh-CN.ts | 8 --- client/src/i18n/locales/zh-TW.ts | 8 --- client/src/lib/ps5Firmware.test.ts | 40 +---------- client/src/lib/ps5Firmware.ts | 26 +------ client/src/lib/useGameLaunch.tsx | 14 +--- client/src/screens/FpkgConvert/MakeCard.tsx | 35 ++-------- client/src/screens/FpkgConvert/cards.test.tsx | 33 ++++----- client/src/screens/FpkgConvert/index.tsx | 14 +--- client/src/screens/InstallPackage/index.tsx | 13 ---- client/src/state/fpkgConversion.test.ts | 17 ----- client/src/state/fpkgConversion.ts | 18 ----- scripts/i18n-source-hashes.json | 8 --- 34 files changed, 26 insertions(+), 473 deletions(-) delete mode 100644 client/src/components/FakeGameFirmwareNotice.test.tsx delete mode 100644 client/src/components/FakeGameFirmwareNotice.tsx diff --git a/FAQ.md b/FAQ.md index 0a12579eb..4dd89bcc2 100644 --- a/FAQ.md +++ b/FAQ.md @@ -98,8 +98,7 @@ running. **Q: Which firmware limits apply to what I install?** - **PS5 fake *game* packages play on firmware up to 13.60.** Above 11.60 (11.61, 12.xx, 13.xx) they need a kstuff build with fake-package support for that firmware, released in November - 2026; with an older kstuff the package installs, but the game does not start. Above 13.60 they - install but do not start. PS4 fake packages work and PS5 homebrew apps launch. The note at the + 2026; with an older kstuff the package installs, but the game does not start. PS4 fake packages work and PS5 homebrew apps launch. The note at the top of **Upload & Install** says so before you send anything. - On **13.60**, Stream & install is the dependable route. @@ -2079,8 +2078,8 @@ refuses to start the title. Check these in order. kstuff build that supports fake packages on that firmware, released in November 2026. With an older kstuff the package installs, but the game does not start: load the newer kstuff, reboot if an older one was running, and - launch again. Above 13.60 an installed PS5 fake package does not start, and - the app warns about that on Install and Convert. You can also mount the + launch again; when a launch fails on these firmware versions, the app says + so. You can also mount the package with Kraken Mount instead: with Kraken Mount running on the PS5, Upload & Install puts the `.pkg` in a folder it scans, and the game plays straight from the package, with nothing installed. PS4 packages are fine, diff --git a/client/src/components/FakeGameFirmwareNotice.test.tsx b/client/src/components/FakeGameFirmwareNotice.test.tsx deleted file mode 100644 index 0652a0e91..000000000 --- a/client/src/components/FakeGameFirmwareNotice.test.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import { describe, expect, it, vi } from "vitest"; - -vi.mock("../state/lang", () => ({ - useTr: () => (key: string, vars?: Record, fallback?: string) => { - let s = fallback ?? key; - for (const [k, v] of Object.entries(vars ?? {})) s = s.replace(`{${k}}`, String(v)); - return s; - }, -})); - -import { FakeGameFirmwareNotice } from "./FakeGameFirmwareNotice"; - -const K = (fw: string) => `FreeBSD 11.0-RELEASE-p0 #1 r229358/releases/${fw} Jul 17 2026`; -const PS5_GAME = "UP4433-PPSA17221_00-MINECRAFTPS50000"; - -const html = (kernel: string | null, id: string | null, compact = false) => - renderToStaticMarkup(); - -describe("FakeGameFirmwareNotice", () => { - it("says it installs but isn't playable, for a PS5 game above 13.60", () => { - const out = html(K("14.00"), PS5_GAME); - expect(out).toContain("Installed, this PS5 game won't start on FW 14.00"); - expect(out).toContain("PS5 fake packages play on firmware up to 13.60"); - expect(out).toContain("PS4 packages and PS5 homebrew apps are fine"); - }); - it("renders the one-line form for a list row", () => { - expect(html(K("13.61"), PS5_GAME, true)).toContain("up to 13.60"); - }); - it("renders nothing up to 13.60 (fake-package kstuff, November 2026), PS4, homebrew or an unknown firmware", () => { - expect(html(K("13.60"), PS5_GAME)).toBe(""); - expect(html(K("12.00"), PS5_GAME)).toBe(""); - expect(html(K("11.60"), PS5_GAME)).toBe(""); - expect(html(K("13.60"), "UP9000-CUSA00207_00-BLOODBORNE000000")).toBe(""); - expect(html(K("13.60"), "IV0002-ITEM00001_00-ITEMZFLOWIV00000")).toBe(""); - expect(html("unknown build", PS5_GAME)).toBe(""); - expect(html(null, PS5_GAME)).toBe(""); - }); -}); diff --git a/client/src/components/FakeGameFirmwareNotice.tsx b/client/src/components/FakeGameFirmwareNotice.tsx deleted file mode 100644 index 40db85e93..000000000 --- a/client/src/components/FakeGameFirmwareNotice.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { useInRouterContext, Link } from "react-router"; - -import { DOC_ANCHORS, faqLink } from "../lib/installErrorDoc"; -import { LAST_PS5_FAKE_GAME_FIRMWARE, ps5FakeGameUnplayableFirmware } from "../lib/ps5Firmware"; -import { useTr } from "../state/lang"; -import { Callout } from "./Callout"; - -/** - * A fake PS5 game package on firmware above LAST_PS5_FAKE_GAME_FIRMWARE installs but does not - * start. Renders nothing for a PS4 package, for PS5 homebrew (IV…/ITEM…), for that firmware and - * older, or when the firmware can't be read: the warning needs a PS5 game id AND a known - * firmware above the line. - */ -export function FakeGameFirmwareNotice({ - kernel, - contentId, - className = "", - compact = false, -}: { - /** The console's kernel string (`ps5Kernel`). */ - kernel: string | null | undefined; - /** The package's content id or title id. */ - contentId: string | null | undefined; - className?: string; - /** One line of text instead of a titled callout, for a list row. */ - compact?: boolean; -}) { - const tr = useTr(); - const inRouter = useInRouterContext(); - const fw = ps5FakeGameUnplayableFirmware(kernel, contentId); - if (!fw) return null; - const body = tr( - "fakegame.fw.body_v3", - { fw, last: LAST_PS5_FAKE_GAME_FIRMWARE }, - `PS5 fake packages play on firmware up to ${LAST_PS5_FAKE_GAME_FIRMWARE}. On FW ${fw} the package installs, but the game doesn't start. PS4 packages and PS5 homebrew apps are fine.`, - ); - const help = inRouter ? ( - - {tr("fakegame.fw.more", undefined, "Why?")} - - ) : null; - if (compact) { - return ( -

- {body} - {help} -

- ); - } - return ( - - {body} - {help} - - ); -} diff --git a/client/src/i18n/locales/ar.ts b/client/src/i18n/locales/ar.ts index 050aaa9de..0368a3594 100644 --- a/client/src/i18n/locales/ar.ts +++ b/client/src/i18n/locales/ar.ts @@ -3474,8 +3474,6 @@ cshares_delete_body: "لن يعرضه Minion بعد الآن. لا شيء يتغ "cq_skipped_later_part": "تم تخطي {count}: جزء لاحق من أرشيف متعدد الأجزاء. أضف جزأه الأول (.part1.rar) بدلًا منه.", "fpkg.cancel_stop_queue": "إلغاء وإيقاف قائمة الانتظار", "fpkg.cancelled": "أُلغي. لم يكتمل شيء.", -"fpkg.unpacked_unplayable_title": "قد لا تعمل هذه الحزمة", -"fpkg.unpacked_unplayable": "هذه اللعبة ستُثبّت كحزمة لكنها لن تعمل على FW {fw}. ألغِ وأنشئ صورة لعبة بدلًا منها.", "fpkg.unpack_lost": "أُغلق التطبيق أثناء فك الضغط، فلم تُنشأ اللعبة. ابدأ من جديد.", "fpkg.make.archive_later": "يُفحص الأرشيف بعد فك ضغطه، لذا لا يُحدَّد خيار هنا.", "fpkg.lowSpaceCompressed": "المساحة الحرة قليلة: حجم اللعبة {size}، وعادة ما تكون الصورة المضغوطة بنصف ذلك تقريبًا، وفي محرك الإخراج {free}. قد لا تتسع.", @@ -4003,9 +4001,7 @@ shell_description_v2: "اكتب أوامر تُنفَّذ على PS5 داخل ع "fpkg.make.image_title": "صورة لعبة", "fpkg.make.image_body": "ملف واحد على قرص PS5 يركّبه ShadowMount+ ويعرضه في الشاشة الرئيسية. لا يُثبّت شيء، ويعمل على أنظمة لا تعمل فيها حزمة PS5.", "fpkg.make.recommended": "موصى به", -"fpkg.make.recommended_fw": "موصى به على FW {fw}", "fpkg.make.pick_game": "افحص لعبة في ① وسيُحدَّد الخيار الأفضل لجهازك.", -"fpkg.make.why_image": "هذه اللعبة ستُثبّت كحزمة لكنها لن تعمل على FW {fw}؛ كصورة تعمل.", "fpkg.make.why_pkg": "الحزمة هي الخيار المعتاد: تُثبّت وتعمل كأي لعبة أخرى.", "fpkg.run.summary": "ينشئ {what} من {title} في {dir}.", "fpkg.run.what_image": "صورة لعبة {ext}", @@ -5228,9 +5224,6 @@ cheats_toast_loaded: "تم تحميل أكواد الغش لـ {name}", engine_job_files_done: "{done} من {total} ملف", engine_job_running_title: "لا يزال نقل قيد التشغيل على المحرك", err_launch_homebrew_refused: "رفض جهاز PS5 تشغيل هذا العنوان (0x80940033). الجهاز لا يشغّل حاليًا تطبيقات homebrew أو ألعاب الحزم المزيفة: حمّل kstuff (أو أعد التشغيل وشغّل كسر الحماية مرة أخرى)، ثم حاول مجددًا.", -"fakegame.fw.more": "لماذا؟", -"fakegame.fw.title_v2": "بعد تثبيتها، لن تعمل لعبة PS5 هذه على FW {fw}", -"fakegame.fw.body_v3": "تعمل حزم PS5 المزيفة على البرامج الثابتة حتى {last}. على FW {fw} تُثبَّت الحزمة، لكن اللعبة لا تبدأ. حزم PS4 وتطبيقات PS5 المنزلية لا مشكلة فيها.", first_run_helper_only: "أرسل ps5upload فقط", first_run_helper_only_hint: "هل تحمّل kstuff بنفسك بالفعل (محمّل تلقائي، etaHEN، elf-arsenal)؟ أرسل ps5upload فقط. تحميل kstuff مرة ثانية يضيف نسخة أخرى فوق الأولى. يُترك المساعد الذي يعمل إذا كان بهذا الإصدار أو أحدث. لا يُتخطّى kstuff وShadowMount+ إلا إذا كان المساعد يعمل بالفعل، لأن التطبيق يحتاج إليه لمعرفة ما يعمل.", first_run_step_already_running: "يعمل بالفعل — لن يُرسل مجددًا", @@ -5257,7 +5250,6 @@ install_path_fallback_label: "التثبيت عبر مسار الملف عندم "installed_fix_permissions_done": "تم إصلاح الأذونات: كل ملف في مجلد هذه اللعبة أصبح الآن 0777. اضغط تشغيل.", "installed_fix_permissions_short": "إصلاح الأذونات", "installed_launch_homebrew_refused": "رفض جهاز PS5 تشغيل هذه اللعبة (0x80940033). الجهاز لا يشغّل حاليًا تطبيقات homebrew أو ألعاب الحزم المزيفة: أعد تحميل kstuff (أو أعد التشغيل وشغّل كسر الحماية مرة أخرى)، ثم اضغط تشغيل مجددًا.", -"fakegame.fw.launch_v3": "على البرامج الثابتة الأحدث من {last} (هذا الجهاز على {fw}) لا تبدأ لعبة PS5 المثبتة من حزمة مزيفة. حزم PS4 لا مشكلة فيها.", "fakegame.fw.launch_kstuff": "إذا ثُبّتت هذه اللعبة من حزمة مزيفة: على FW {fw} لا تبدأ إلا مع إصدار kstuff يدعم الحزم المزيفة هناك (نوفمبر 2026 أو أحدث). حمّل ذلك الـ kstuff ثم اضغط تشغيل مرة أخرى.", "installed_launch_no_kstuff": "رفض جهاز PS5 تشغيل هذه اللعبة (0x80940033) لأن kstuff لا يعمل. من دونه لا يشغّل الجهاز أي تطبيق homebrew أو لعبة من حزمة مزيفة. حمّل kstuff (المحمّل التلقائي لديك، أو الاتصال → إعداد) ثم اضغط تشغيل مجددًا.", job_why_lanes: "الاتصالات: {avg} في المتوسط، و{max} كحد أقصى؛ الجزء {chunk}", diff --git a/client/src/i18n/locales/bn.ts b/client/src/i18n/locales/bn.ts index 6d9972e6a..8b5733e9c 100644 --- a/client/src/i18n/locales/bn.ts +++ b/client/src/i18n/locales/bn.ts @@ -3474,8 +3474,6 @@ cshares_delete_body: "Minion আর এটি দেখাবে না। স "cq_skipped_later_part": "{count}টি বাদ: বহু-খণ্ড আর্কাইভের পরের অংশ। এর বদলে প্রথম অংশ (.part1.rar) যোগ করুন।", "fpkg.cancel_stop_queue": "বাতিল করুন ও সারি থামান", "fpkg.cancelled": "বাতিল। কিছুই শেষ হয়নি।", -"fpkg.unpacked_unplayable_title": "এই প্যাকেজ না-ও চলতে পারে", -"fpkg.unpacked_unplayable": "এই PS5 গেম প্যাকেজ হিসেবে ইনস্টল হবে কিন্তু FW {fw}-এ চলবে না। বাতিল করে গেম ইমেজ বানান।", "fpkg.unpack_lost": "আনপ্যাক চলাকালীন অ্যাপ বন্ধ হয়েছে, তাই গেম তৈরি হয়নি। আবার শুরু করুন।", "fpkg.make.archive_later": "আর্কাইভ আনপ্যাকের পরে দেখা হয়, তাই এখানে কিছু চিহ্নিত নেই।", "fpkg.lowSpaceCompressed": "জায়গা কম: এই গেম {size}, সংকুচিত ইমেজ সাধারণত এর প্রায় অর্ধেক, আর আউটপুট ড্রাইভে আছে {free}। না-ও ধরতে পারে।", @@ -4003,9 +4001,7 @@ shell_description_v2: "এমন কমান্ড টাইপ করুন "fpkg.make.image_title": "একটি গেম ইমেজ", "fpkg.make.image_body": "PS5 ড্রাইভে একটি ফাইল, যা ShadowMount+ মাউন্ট করে হোম স্ক্রিনে দেখায়। কিছু ইনস্টল হয় না, আর যে ফার্মওয়্যারে PS5 প্যাকেজ চলে না সেখানেও চলে।", "fpkg.make.recommended": "প্রস্তাবিত", -"fpkg.make.recommended_fw": "FW {fw}-এ প্রস্তাবিত", "fpkg.make.pick_game": "①-এ একটি গেম চেক করুন, আপনার PS5-এর জন্য ভালো পছন্দটি চিহ্নিত হবে।", -"fpkg.make.why_image": "এই PS5 গেম প্যাকেজ হিসেবে ইনস্টল হবে কিন্তু FW {fw}-এ চলবে না; ইমেজ হিসেবে চলে।", "fpkg.make.why_pkg": "প্যাকেজই সাধারণ পছন্দ: অন্য গেমের মতো ইনস্টল হয় ও চলে।", "fpkg.run.summary": "{dir}-এ {title}-এর {what} বানায়।", "fpkg.run.what_image": "একটি {ext} গেম ইমেজ", @@ -5228,9 +5224,6 @@ cheats_toast_loaded: "{name}-এর জন্য চিট লোড হয় engine_job_files_done: "{total}টির মধ্যে {done}টি ফাইল", engine_job_running_title: "ইঞ্জিনে একটি ট্রান্সফার এখনও চলছে", err_launch_homebrew_refused: "PS5 এই টাইটেলটি চালু করতে অস্বীকার করেছে (0x80940033)। কনসোল এখন homebrew বা নকল-প্যাকেজ গেম চালু করছে না: kstuff লোড করুন (অথবা রিবুট করে আবার জেলব্রেক চালান), তারপর আবার চেষ্টা করুন।", -"fakegame.fw.more": "কেন?", -"fakegame.fw.title_v2": "ইনস্টল করলে এই PS5 গেম FW {fw}-এ চালু হবে না", -"fakegame.fw.body_v3": "PS5 ফেক প্যাকেজ {last} পর্যন্ত ফার্মওয়্যারে চলে। FW {fw}-এ প্যাকেজ ইনস্টল হয়, কিন্তু গেম চালু হয় না। PS4 প্যাকেজ ও PS5 হোমব্রু অ্যাপে সমস্যা নেই।", first_run_helper_only: "শুধু ps5upload পাঠান", first_run_helper_only_hint: "আপনি কি আগে থেকেই নিজে kstuff লোড করেন (একটি autoloader, etaHEN, elf-arsenal)? শুধু ps5upload পাঠান। kstuff দ্বিতীয়বার লোড করলে আরেকটি কপি জমা হয়। এই সংস্করণের বা নতুন হেল্পার চলতে থাকে। kstuff ও ShadowMount+ তখনই বাদ যায় যখন হেল্পার আগে থেকে চলছে, কারণ কী চলছে তা দেখতে অ্যাপের এটি দরকার।", first_run_step_already_running: "আগে থেকেই চলছে — আবার পাঠানো হয়নি", @@ -5257,7 +5250,6 @@ install_path_fallback_label: "PS5 এই কম্পিউটারে পৌ "installed_fix_permissions_done": "অনুমতি ঠিক করা হয়েছে: এই গেমের ফোল্ডারের প্রতিটি ফাইল এখন 0777। চালান চাপুন।", "installed_fix_permissions_short": "অনুমতি ঠিক করুন", "installed_launch_homebrew_refused": "PS5 এই গেমটি চালু করতে অস্বীকার করেছে (0x80940033)। কনসোল এখন homebrew বা নকল-প্যাকেজ গেম চালু করছে না: kstuff আবার লোড করুন (অথবা রিবুট করে আবার জেলব্রেক চালান), তারপর আবার চালান চাপুন।", -"fakegame.fw.launch_v3": "{last}-এর চেয়ে নতুন ফার্মওয়্যারে (এই কনসোল {fw}-এ) ফেক প্যাকেজ থেকে ইনস্টল করা PS5 গেম চালু হয় না। PS4 প্যাকেজে সমস্যা নেই।", "fakegame.fw.launch_kstuff": "এই গেমটি ফেক প্যাকেজ থেকে ইনস্টল হলে: FW {fw}-এ এটি শুধু সেখানে ফেক প্যাকেজ সাপোর্ট করা kstuff বিল্ডে চালু হয় (নভেম্বর 2026 বা নতুন)। সেই kstuff লোড করে আবার Play চাপুন।", "installed_launch_no_kstuff": "kstuff চলছে না বলে PS5 এই গেমটি চালু করতে অস্বীকার করেছে (0x80940033)। এটি ছাড়া কনসোল কোনো homebrew বা নকল-প্যাকেজ গেম চালু করে না। kstuff লোড করুন (আপনার autoloader, অথবা সংযোগ → সেট আপ) এবং আবার চালান চাপুন।", job_why_lanes: "সংযোগ: গড়ে {avg}, সর্বোচ্চ {max}; চাঙ্ক {chunk}", diff --git a/client/src/i18n/locales/de.ts b/client/src/i18n/locales/de.ts index 505781409..938a3dfc6 100644 --- a/client/src/i18n/locales/de.ts +++ b/client/src/i18n/locales/de.ts @@ -3482,8 +3482,6 @@ cshares_delete_body: "Minion zeigt sie nicht mehr an. Auf dem Server ändert sic "cq_skipped_later_part": "{count} übersprungen: ein späterer Teil eines mehrteiligen Archivs. Füge stattdessen den ersten Teil (.part1.rar) hinzu.", "fpkg.cancel_stop_queue": "Abbrechen und Warteschlange anhalten", "fpkg.cancelled": "Abgebrochen. Nichts wurde fertig.", -"fpkg.unpacked_unplayable_title": "Dieses Paket läuft vielleicht nicht", -"fpkg.unpacked_unplayable": "Dieses PS5-Spiel ließe sich als Paket installieren, läuft auf FW {fw} aber nicht. Brich ab und erstelle stattdessen ein Spiel-Image.", "fpkg.unpack_lost": "Die App wurde beim Entpacken geschlossen, daher wurde das Spiel nicht erstellt. Starte es neu.", "fpkg.make.archive_later": "Ein Archiv wird erst nach dem Entpacken geprüft, daher ist hier nichts markiert.", "fpkg.lowSpaceCompressed": "Wenig freier Platz: Dieses Spiel hat {size}, ein komprimiertes Image meist etwa die Hälfte, und das Ziellaufwerk hat {free}. Es passt vielleicht nicht.", @@ -4011,9 +4009,7 @@ shell_description_v2: "Gib Befehle ein, die auf der PS5 im Prozess des Helfers l "fpkg.make.image_title": "Ein Spiel-Image", "fpkg.make.image_body": "Eine Datei auf einem PS5-Laufwerk, die ShadowMount+ einbindet und auf dem Startbildschirm zeigt. Nichts wird installiert, und es läuft auf Firmware, auf der ein PS5-Paket nicht läuft.", "fpkg.make.recommended": "Empfohlen", -"fpkg.make.recommended_fw": "Empfohlen auf FW {fw}", "fpkg.make.pick_game": "Prüfe ein Spiel unter ①, dann wird die bessere Wahl für deine PS5 markiert.", -"fpkg.make.why_image": "Dieses PS5-Spiel ließe sich als Paket installieren, läuft auf FW {fw} aber nicht; als Image schon.", "fpkg.make.why_pkg": "Ein Paket ist die übliche Wahl: es wird installiert und läuft wie jedes andere Spiel.", "fpkg.run.summary": "Erstellt {what} von {title} in {dir}.", "fpkg.run.what_image": "ein {ext}-Spiel-Image", @@ -5236,9 +5232,6 @@ cheats_toast_loaded: "Cheats für {name} geladen", engine_job_files_done: "{done} von {total} Dateien", engine_job_running_title: "Auf der Engine läuft noch eine Übertragung", err_launch_homebrew_refused: "Die PS5 hat den Start dieses Titels abgelehnt (0x80940033). Die Konsole startet gerade keine Homebrew- oder Fake-Paket-Spiele: Lade kstuff (oder starte neu und führe den Jailbreak erneut aus) und versuche es dann noch einmal.", -"fakegame.fw.more": "Warum?", -"fakegame.fw.title_v2": "Installiert startet dieses PS5-Spiel auf FW {fw} nicht", -"fakegame.fw.body_v3": "PS5-Fake-Pakete laufen auf Firmware bis {last}. Auf FW {fw} wird das Paket installiert, aber das Spiel startet nicht. PS4-Pakete und PS5-Homebrew-Apps funktionieren.", first_run_helper_only: "Nur ps5upload senden", first_run_helper_only_hint: "Lädst du kstuff schon selbst (ein Autoloader, etaHEN, elf-arsenal)? Sende nur ps5upload. kstuff ein zweites Mal zu laden, stapelt eine weitere Kopie. Ein Helfer dieser oder einer neueren Version läuft einfach weiter. kstuff und ShadowMount+ werden nur übersprungen, wenn der Helfer schon läuft, denn die App braucht ihn, um zu sehen, was läuft.", first_run_step_already_running: "läuft bereits — nicht erneut gesendet", @@ -5265,7 +5258,6 @@ install_path_fallback_label: "Über den Dateipfad installieren, wenn die PS5 die "installed_fix_permissions_done": "Berechtigungen repariert: Jede Datei im Ordner dieses Spiels ist jetzt 0777. Drücke auf Spielen.", "installed_fix_permissions_short": "Berechtigungen reparieren", "installed_launch_homebrew_refused": "Die PS5 hat den Start dieses Spiels abgelehnt (0x80940033). Die Konsole startet gerade keine Homebrew- oder Fake-Paket-Spiele: Lade kstuff neu (oder starte neu und führe den Jailbreak erneut aus) und drücke dann erneut auf Spielen.", -"fakegame.fw.launch_v3": "Auf Firmware über {last} (diese Konsole hat {fw}) startet ein PS5-Spiel, das aus einem Fake-Paket installiert wurde, nicht. PS4-Pakete funktionieren.", "fakegame.fw.launch_kstuff": "Falls dieses Spiel aus einem Fake-Paket installiert wurde: Auf FW {fw} startet es nur mit einem kstuff-Build, der dort Fake-Pakete unterstützt (November 2026 oder neuer). Lade diesen kstuff und drücke dann erneut auf Spielen.", "installed_launch_no_kstuff": "Die PS5 hat den Start dieses Spiels abgelehnt (0x80940033), weil kstuff nicht läuft. Ohne kstuff startet die Konsole keine Homebrew- oder Fake-Paket-Spiele. Lade kstuff (über deinen Autoloader oder Verbindung → Einrichten) und drücke erneut auf Spielen.", job_why_lanes: "Verbindungen: {avg} im Schnitt, höchstens {max}; Block {chunk}", diff --git a/client/src/i18n/locales/en.ts b/client/src/i18n/locales/en.ts index 7b8244eb8..ecdcc4852 100644 --- a/client/src/i18n/locales/en.ts +++ b/client/src/i18n/locales/en.ts @@ -4134,8 +4134,6 @@ v5_home_servers_connect: "Connect a NAS or server", "cq_skipped_later_part": "Skipped {count}: a later part of a multi-part archive. Add its first part (.part1.rar) instead.", "fpkg.cancel_stop_queue": "Cancel and stop the queue", "fpkg.cancelled": "Cancelled. Nothing was finished.", -"fpkg.unpacked_unplayable_title": "This package may not play", -"fpkg.unpacked_unplayable": "This PS5 game would install as a package but not play on FW {fw}. Cancel and make a game image instead.", "fpkg.unpack_lost": "The app closed while this was unpacking, so its game was not made. Start it again.", "fpkg.make.archive_later": "An archive is looked at after it is unpacked, so no choice is marked here.", "fpkg.lowSpaceCompressed": "Low on free space: this game is {size}, a compressed image is usually about half that, and the output drive has {free}. It may not fit.", @@ -4354,16 +4352,12 @@ queue_rar_password_retry: "Retry with password", "joberr.ava1_failed": "The PS5 helper started but its transfer server did not. Restart the console, then retry.", "joberr.helper_not_running": "No helper is running on the PS5. Send it from the Connection screen, then retry.", install_hint_setup_exe: "The installer has opened: follow it, and it updates PS5Upload in place.", -"fakegame.fw.title_v2": "Installed, this PS5 game won't start on FW {fw}", -"fakegame.fw.body_v3": "PS5 fake packages play on firmware up to {last}. On FW {fw} the package installs, but the game doesn't start. PS4 packages and PS5 homebrew apps are fine.", "installed_fix_permissions": "Fix permissions: make this game's folder readable and runnable by the PS5 (chmod 777)", "installed_fix_permissions_short": "Fix permissions", "installed_fix_permissions_done": "Permissions fixed: every file in this game's folder is now 0777. Press Play.", "installed_launch_no_kstuff": "The PS5 refused to start this game (0x80940033) because kstuff isn't running. Without it the console starts no homebrew or fake-package game. Load kstuff (your autoloader, or Connection → Set up) and press Play again.", "installed_launch_homebrew_refused": "The PS5 refused to start this game (0x80940033). The console isn't starting homebrew or fake-package games right now: reload kstuff (or reboot and run the jailbreak again), then press Play again.", -"fakegame.fw.launch_v3": "On firmware above {last} (this console is on {fw}) a PS5 game installed from a fake package doesn't start. PS4 packages are fine.", "fakegame.fw.launch_kstuff": "If this game was installed from a fake package: on FW {fw} it starts only with a kstuff build that supports fake packages there (November 2026 or newer). Load that kstuff, then press Play again.", -"fakegame.fw.more": "Why?", "install_help_wont_launch": "Game won't launch?", "install_help_what_means": "What does this mean?", job_why_window_full: "Receive window full {pct} %: data was sent faster than the console acknowledged it, while the console reported neither its drive nor its workers as the limit. That usually means a slow network link (Wi-Fi, a weak signal or a busy network); a wired connection is the usual fix.", @@ -4712,9 +4706,7 @@ videos_description_browser_v2: "Video clips saved on the PS5 (its Capture Galler "fpkg.make.image_title": "A game image", "fpkg.make.image_body": "One file on a PS5 drive that ShadowMount+ mounts and shows on the home screen. Nothing is installed, and it plays on firmware where a PS5 package will not.", "fpkg.make.recommended": "Recommended", -"fpkg.make.recommended_fw": "Recommended on FW {fw}", "fpkg.make.pick_game": "Check a game under ① and the better choice for it on your PS5 is marked.", -"fpkg.make.why_image": "This PS5 game would install as a package but not play on FW {fw}; as an image it does.", "fpkg.make.why_pkg": "A package is the ordinary choice: it installs and plays like any other game.", "fpkg.run.summary": "Makes {what} of {title} in {dir}.", "fpkg.run.what_image": "a {ext} game image", diff --git a/client/src/i18n/locales/es.ts b/client/src/i18n/locales/es.ts index b1ea91cb7..980a84f5f 100644 --- a/client/src/i18n/locales/es.ts +++ b/client/src/i18n/locales/es.ts @@ -3427,8 +3427,6 @@ cshares_delete_body: "Minion deja de mostrarla. Nada cambia en el servidor.", "cq_skipped_later_part": "Omitidos {count}: una parte posterior de un archivo de varias partes. Añade en su lugar la primera parte (.part1.rar).", "fpkg.cancel_stop_queue": "Cancelar y detener la cola", "fpkg.cancelled": "Cancelado. No se terminó nada.", -"fpkg.unpacked_unplayable_title": "Puede que este paquete no funcione", -"fpkg.unpacked_unplayable": "Este juego de PS5 se instalaría como paquete pero no funcionaría en FW {fw}. Cancela y crea una imagen de juego.", "fpkg.unpack_lost": "La app se cerró mientras se descomprimía, así que el juego no se creó. Vuelve a empezar.", "fpkg.make.archive_later": "Un archivo se examina después de descomprimirlo, así que aquí no se marca ninguna opción.", "fpkg.lowSpaceCompressed": "Poco espacio libre: este juego ocupa {size}, una imagen comprimida suele ser cerca de la mitad, y la unidad de salida tiene {free}. Puede que no quepa.", @@ -3956,9 +3954,7 @@ shell_description_v2: "Escribe comandos que se ejecutan en la PS5, en el proceso "fpkg.make.image_title": "Una imagen de juego", "fpkg.make.image_body": "Un archivo en una unidad de la PS5 que ShadowMount+ monta y muestra en la pantalla de inicio. No se instala nada y funciona en firmwares donde un paquete de PS5 no.", "fpkg.make.recommended": "Recomendado", -"fpkg.make.recommended_fw": "Recomendado en FW {fw}", "fpkg.make.pick_game": "Comprueba un juego en ① y se marcará la mejor opción para tu PS5.", -"fpkg.make.why_image": "Este juego de PS5 se instalaría como paquete pero no funcionaría en FW {fw}; como imagen sí.", "fpkg.make.why_pkg": "Un paquete es la opción habitual: se instala y funciona como cualquier otro juego.", "fpkg.run.summary": "Crea {what} de {title} en {dir}.", "fpkg.run.what_image": "una imagen de juego {ext}", @@ -5181,9 +5177,6 @@ cheats_toast_loaded: "Trucos cargados para {name}", engine_job_files_done: "{done} de {total} archivos", engine_job_running_title: "Todavía hay una transferencia en curso en el motor", err_launch_homebrew_refused: "La PS5 se negó a iniciar este título (0x80940033). La consola no está iniciando homebrew ni juegos de paquetes falsos en este momento: carga kstuff (o reinicia y vuelve a ejecutar el jailbreak) y vuelve a intentarlo.", -"fakegame.fw.more": "¿Por qué?", -"fakegame.fw.title_v2": "Instalado, este juego de PS5 no arranca con FW {fw}", -"fakegame.fw.body_v3": "Los paquetes falsos de PS5 funcionan en firmware hasta {last}. En el FW {fw} el paquete se instala, pero el juego no arranca. Los paquetes de PS4 y las apps homebrew de PS5 funcionan.", first_run_helper_only: "Enviar solo ps5upload", first_run_helper_only_hint: "¿Ya cargas kstuff por tu cuenta (un autoloader, etaHEN, elf-arsenal)? Envía solo ps5upload. Cargar kstuff una segunda vez apila otra copia. Un ayudante de esta versión o más nuevo se deja en marcha. kstuff y ShadowMount+ solo se omiten si el ayudante ya está en marcha, porque la app lo necesita para ver qué se está ejecutando.", first_run_step_already_running: "ya en ejecución — no se vuelve a enviar", @@ -5210,7 +5203,6 @@ install_path_fallback_label: "Instalar por ruta de archivo cuando la PS5 no pued "installed_fix_permissions_done": "Permisos corregidos: todos los archivos de la carpeta de este juego son ahora 0777. Pulsa Jugar.", "installed_fix_permissions_short": "Corregir permisos", "installed_launch_homebrew_refused": "La PS5 se negó a iniciar este juego (0x80940033). La consola no está iniciando homebrew ni juegos de paquetes falsos en este momento: vuelve a cargar kstuff (o reinicia y vuelve a ejecutar el jailbreak) y pulsa Jugar de nuevo.", -"fakegame.fw.launch_v3": "En firmware superior a {last} (esta consola tiene {fw}) un juego de PS5 instalado desde un paquete falso no arranca. Los paquetes de PS4 funcionan.", "fakegame.fw.launch_kstuff": "Si este juego se instaló desde un paquete falso: en el FW {fw} solo arranca con una versión de kstuff compatible con paquetes falsos ahí (noviembre de 2026 o posterior). Carga ese kstuff y vuelve a pulsar Jugar.", "installed_launch_no_kstuff": "La PS5 se negó a iniciar este juego (0x80940033) porque kstuff no se está ejecutando. Sin él, la consola no inicia ningún homebrew ni juego de paquete falso. Carga kstuff (tu autoloader, o Conexión → Configurar) y pulsa Jugar de nuevo.", job_why_lanes: "Conexiones: {avg} de media, {max} como máximo; bloque {chunk}", diff --git a/client/src/i18n/locales/fa.ts b/client/src/i18n/locales/fa.ts index 641d7629d..2abe041aa 100644 --- a/client/src/i18n/locales/fa.ts +++ b/client/src/i18n/locales/fa.ts @@ -3833,8 +3833,6 @@ v5_home_servers_connect: "اتصال به NAS یا سرور", "cq_skipped_later_part": "{count} مورد رد شد: بخش بعدی یک آرشیو چندبخشی. به‌جای آن بخش اول (.part1.rar) را اضافه کنید.", "fpkg.cancel_stop_queue": "لغو و توقف صف", "fpkg.cancelled": "لغو شد. چیزی تمام نشد.", -"fpkg.unpacked_unplayable_title": "شاید این بسته اجرا نشود", -"fpkg.unpacked_unplayable": "این بازی PS5 به‌صورت بسته نصب می‌شود ولی روی FW {fw} اجرا نمی‌شود. لغو کنید و به‌جای آن ایمیج بازی بسازید.", "fpkg.unpack_lost": "برنامه هنگام باز کردن بسته شد، پس بازی ساخته نشد. دوباره شروع کنید.", "fpkg.make.archive_later": "آرشیو پس از باز شدن بررسی می‌شود، پس اینجا گزینه‌ای علامت نمی‌خورد.", "fpkg.lowSpaceCompressed": "فضای خالی کم است: این بازی {size} است، ایمیج فشرده معمولاً حدود نصف آن است و درایو خروجی {free} دارد. شاید جا نشود.", @@ -4028,9 +4026,6 @@ notif_first_run_ready_body: "ps5upload روی {host} در حال اجراست.", "joberr.ava1_failed": "هلپر PS5 راه‌اندازی شد اما سرور انتقال آن بالا نیامد. کنسول را راه‌اندازی مجدد کنید، سپس دوباره تلاش کنید.", "joberr.helper_not_running": "هیچ کمک‌یاری روی PS5 در حال اجرا نیست. آن را از صفحه‌ی اتصال بفرستید، سپس دوباره تلاش کنید.", "install_hint_setup_exe": "نصب‌کننده باز شد: از آن پیروی کنید تا PS5Upload را در جا به‌روزرسانی کند.", -"fakegame.fw.title_v2": "پس از نصب، این بازی PS5 روی FW {fw} اجرا نمی‌شود", -"fakegame.fw.body_v3": "بسته‌های جعلی PS5 روی فریمور تا {last} اجرا می‌شوند. روی FW {fw} بسته نصب می‌شود، اما بازی اجرا نمی‌شود. بسته‌های PS4 و برنامه‌های هوم‌بروی PS5 مشکلی ندارند.", -"fakegame.fw.more": "چرا؟", "install_help_wont_launch": "بازی اجرا نمی‌شود؟", "install_help_what_means": "این یعنی چه؟", fs_upload_retrying: "اتصال قطع شد. تلاش دوباره ({attempt} از {of})…", @@ -4313,9 +4308,7 @@ shell_description_v2: "فرمان‌هایی تایپ کنید که روی PS5 "fpkg.make.image_title": "یک تصویر بازی", "fpkg.make.image_body": "یک فایل روی درایو PS5 که ShadowMount+ آن را مونت می‌کند و در صفحهٔ اصلی نشان می‌دهد. چیزی نصب نمی‌شود و روی فرم‌ویرهایی که بستهٔ PS5 اجرا نمی‌شود کار می‌کند.", "fpkg.make.recommended": "پیشنهادی", -"fpkg.make.recommended_fw": "پیشنهادی روی FW {fw}", "fpkg.make.pick_game": "یک بازی را در ① بررسی کنید تا گزینهٔ بهتر برای PS5 شما مشخص شود.", -"fpkg.make.why_image": "این بازی PS5 به‌صورت بسته نصب می‌شود ولی روی FW {fw} اجرا نمی‌شود؛ به‌صورت تصویر اجرا می‌شود.", "fpkg.make.why_pkg": "بسته انتخاب معمول است: مثل هر بازی دیگری نصب و اجرا می‌شود.", "fpkg.run.summary": "{what} از {title} را در {dir} می‌سازد.", "fpkg.run.what_image": "یک تصویر بازی {ext}", @@ -5557,7 +5550,6 @@ install_path_fallback_label: "نصب از طریق مسیر فایل وقتی PS "installed_fix_permissions_done": "مجوزها اصلاح شد: همه‌ی فایل‌های پوشه‌ی این بازی اکنون 0777 هستند. بازی را بزنید.", "installed_fix_permissions_short": "اصلاح مجوزها", "installed_launch_homebrew_refused": "PS5 از اجرای این بازی خودداری کرد (0x80940033). کنسول در حال حاضر برنامه‌های homebrew یا بازی‌های بسته‌ی جعلی را اجرا نمی‌کند: kstuff را دوباره بارگذاری کنید (یا راه‌اندازی مجدد کنید و جیلبریک را دوباره اجرا کنید)، سپس دوباره بازی را بزنید.", -"fakegame.fw.launch_v3": "روی فریمور بالاتر از {last} (این کنسول روی {fw} است) بازی PS5 نصب‌شده از بسته جعلی اجرا نمی‌شود. بسته‌های PS4 مشکلی ندارند.", "fakegame.fw.launch_kstuff": "اگر این بازی از بسته جعلی نصب شده: روی FW {fw} فقط با نسخه‌ای از kstuff اجرا می‌شود که آنجا از بسته جعلی پشتیبانی کند (نوامبر 2026 یا جدیدتر). آن kstuff را بارگذاری کنید و دوباره اجرا را بزنید.", "installed_launch_no_kstuff": "PS5 از اجرای این بازی خودداری کرد (0x80940033) چون kstuff در حال اجرا نیست. بدون آن کنسول هیچ برنامه‌ی homebrew یا بازی بسته‌ی جعلی را اجرا نمی‌کند. kstuff را بارگذاری کنید (autoloader خودتان، یا اتصال → راه‌اندازی) و دوباره بازی را بزنید.", job_why_window_full: "پنجره‌ی دریافت پر {pct} %: داده سریع‌تر از آنچه کنسول تأیید می‌کرد ارسال شد، در حالی که کنسول نه درایو و نه کارگرهایش را محدودیت گزارش کرد. این معمولاً یعنی اتصال شبکه کند است (Wi-Fi، سیگنال ضعیف یا شبکه‌ی شلوغ)؛ راه‌حل معمول اتصال سیمی است.", diff --git a/client/src/i18n/locales/fr.ts b/client/src/i18n/locales/fr.ts index 99b263fbb..934935622 100644 --- a/client/src/i18n/locales/fr.ts +++ b/client/src/i18n/locales/fr.ts @@ -3500,8 +3500,6 @@ cshares_delete_body: "Minion ne l'affiche plus. Rien ne change sur le serveur.", "cq_skipped_later_part": "{count} ignoré(s) : une partie suivante d'une archive en plusieurs parties. Ajoutez plutôt la première partie (.part1.rar).", "fpkg.cancel_stop_queue": "Annuler et arrêter la file", "fpkg.cancelled": "Annulé. Rien n'a été terminé.", -"fpkg.unpacked_unplayable_title": "Ce paquet risque de ne pas fonctionner", -"fpkg.unpacked_unplayable": "Ce jeu PS5 s'installerait en paquet mais ne fonctionnerait pas sur FW {fw}. Annulez et créez plutôt une image de jeu.", "fpkg.unpack_lost": "L'app s'est fermée pendant la décompression, le jeu n'a donc pas été créé. Recommencez.", "fpkg.make.archive_later": "Une archive est examinée après sa décompression, aucun choix n'est donc indiqué ici.", "fpkg.lowSpaceCompressed": "Peu d'espace libre : ce jeu fait {size}, une image compressée en fait souvent environ la moitié, et le disque de sortie a {free}. Il se peut que ça ne tienne pas.", @@ -4019,9 +4017,7 @@ shell_description_v2: "Saisissez des commandes exécutées sur la PS5, dans le p "fpkg.make.image_title": "Une image de jeu", "fpkg.make.image_body": "Un fichier sur un disque de la PS5 que ShadowMount+ monte et affiche sur l'écran d'accueil. Rien n'est installé, et il fonctionne sur les firmwares où un paquet PS5 ne fonctionne pas.", "fpkg.make.recommended": "Recommandé", -"fpkg.make.recommended_fw": "Recommandé sur FW {fw}", "fpkg.make.pick_game": "Vérifiez un jeu sous ① et le meilleur choix pour votre PS5 sera indiqué.", -"fpkg.make.why_image": "Ce jeu PS5 s'installerait en paquet mais ne fonctionnerait pas sur FW {fw} ; en image, oui.", "fpkg.make.why_pkg": "Un paquet est le choix habituel : il s'installe et fonctionne comme tout autre jeu.", "fpkg.run.summary": "Crée {what} de {title} dans {dir}.", "fpkg.run.what_image": "une image de jeu {ext}", @@ -5244,9 +5240,6 @@ cheats_toast_loaded: "Codes chargés pour {name}", engine_job_files_done: "{done} fichiers sur {total}", engine_job_running_title: "Un transfert est toujours en cours sur le moteur", err_launch_homebrew_refused: "La PS5 a refusé de lancer ce titre (0x80940033). La console ne lance pas de homebrew ni de jeux en faux paquet pour le moment : charge kstuff (ou redémarre et relance le jailbreak), puis réessaie.", -"fakegame.fw.more": "Pourquoi ?", -"fakegame.fw.title_v2": "Installé, ce jeu PS5 ne démarre pas sur le FW {fw}", -"fakegame.fw.body_v3": "Les faux paquets PS5 fonctionnent sur les firmwares jusqu'à {last}. Sur le FW {fw}, le paquet s'installe, mais le jeu ne démarre pas. Les paquets PS4 et les applis homebrew PS5 fonctionnent.", first_run_helper_only: "Envoyer seulement ps5upload", first_run_helper_only_hint: "Tu charges déjà kstuff toi-même (un autoloader, etaHEN, elf-arsenal) ? Envoie seulement ps5upload. Charger kstuff une seconde fois en empile une autre copie. Un assistant de cette version ou plus récent reste en place. kstuff et ShadowMount+ ne sont ignorés que si l’assistant tourne déjà, car l’app en a besoin pour voir ce qui tourne.", first_run_step_already_running: "déjà en cours — pas renvoyé", @@ -5273,7 +5266,6 @@ install_path_fallback_label: "Installer par chemin de fichier quand la PS5 ne pe "installed_fix_permissions_done": "Permissions corrigées : chaque fichier du dossier de ce jeu est maintenant en 0777. Appuie sur Jouer.", "installed_fix_permissions_short": "Corriger les permissions", "installed_launch_homebrew_refused": "La PS5 a refusé de lancer ce jeu (0x80940033). La console ne lance pas de homebrew ni de jeux en faux paquet pour le moment : recharge kstuff (ou redémarre et relance le jailbreak), puis appuie à nouveau sur Jouer.", -"fakegame.fw.launch_v3": "Sur un firmware au-delà de {last} (cette console est en {fw}), un jeu PS5 installé depuis un faux paquet ne démarre pas. Les paquets PS4 fonctionnent.", "fakegame.fw.launch_kstuff": "Si ce jeu a été installé depuis un faux paquet : sur le FW {fw}, il ne démarre qu'avec une version de kstuff qui y prend en charge les faux paquets (novembre 2026 ou plus récente). Chargez ce kstuff, puis appuyez de nouveau sur Jouer.", "installed_launch_no_kstuff": "La PS5 a refusé de lancer ce jeu (0x80940033) car kstuff n'est pas en cours d'exécution. Sans lui, la console ne lance aucun homebrew ni jeu en faux paquet. Charge kstuff (ton autoloader, ou Connexion → Configurer) et appuie à nouveau sur Jouer.", job_why_lanes: "Connexions : {avg} en moyenne, {max} au maximum ; bloc {chunk}", diff --git a/client/src/i18n/locales/hi.ts b/client/src/i18n/locales/hi.ts index 4431dfc3f..27c186466 100644 --- a/client/src/i18n/locales/hi.ts +++ b/client/src/i18n/locales/hi.ts @@ -3498,8 +3498,6 @@ cshares_delete_body: "Minion इसे दिखाना बंद कर द "cq_skipped_later_part": "{count} छोड़े गए: बहु-भाग आर्काइव का बाद वाला भाग। इसके बजाय पहला भाग (.part1.rar) जोड़ें।", "fpkg.cancel_stop_queue": "रद्द करें और कतार रोकें", "fpkg.cancelled": "रद्द। कुछ पूरा नहीं हुआ।", -"fpkg.unpacked_unplayable_title": "यह पैकेज शायद न चले", -"fpkg.unpacked_unplayable": "यह PS5 गेम पैकेज के रूप में इंस्टॉल होगा पर FW {fw} पर नहीं चलेगा। रद्द करें और गेम इमेज बनाएँ।", "fpkg.unpack_lost": "अनपैक होते समय ऐप बंद हो गया, इसलिए गेम नहीं बना। फिर से शुरू करें।", "fpkg.make.archive_later": "आर्काइव अनपैक होने के बाद देखा जाता है, इसलिए यहाँ कोई विकल्प चिह्नित नहीं है।", "fpkg.lowSpaceCompressed": "खाली जगह कम है: यह गेम {size} का है, संपीड़ित इमेज आमतौर पर इसका लगभग आधा होती है, और आउटपुट ड्राइव पर {free} है। शायद न आए।", @@ -4017,9 +4015,7 @@ shell_description_v2: "ऐसे कमांड टाइप करें ज "fpkg.make.image_title": "एक गेम इमेज", "fpkg.make.image_body": "PS5 ड्राइव पर एक फ़ाइल जिसे ShadowMount+ माउंट करके होम स्क्रीन पर दिखाता है। कुछ इंस्टॉल नहीं होता, और यह उन फ़र्मवेयर पर भी चलती है जहाँ PS5 पैकेज नहीं चलता।", "fpkg.make.recommended": "अनुशंसित", -"fpkg.make.recommended_fw": "FW {fw} पर अनुशंसित", "fpkg.make.pick_game": "① में कोई गेम जाँचें, आपके PS5 के लिए बेहतर विकल्प चिह्नित होगा।", -"fpkg.make.why_image": "यह PS5 गेम पैकेज के रूप में इंस्टॉल होगा पर FW {fw} पर नहीं चलेगा; इमेज के रूप में चलता है।", "fpkg.make.why_pkg": "पैकेज सामान्य विकल्प है: यह किसी भी अन्य गेम की तरह इंस्टॉल होता और चलता है।", "fpkg.run.summary": "{dir} में {title} का {what} बनाता है।", "fpkg.run.what_image": "एक {ext} गेम इमेज", @@ -5242,9 +5238,6 @@ cheats_toast_loaded: "{name} के लिए चीट लोड किए ग engine_job_files_done: "{total} में से {done} फ़ाइलें", engine_job_running_title: "इंजन पर एक ट्रांसफ़र अभी भी चल रहा है", err_launch_homebrew_refused: "PS5 ने यह टाइटल शुरू करने से मना कर दिया (0x80940033)। कंसोल अभी homebrew या नकली-पैकेज गेम शुरू नहीं कर रहा है: kstuff लोड करें (या रीबूट करके फिर से जेलब्रेक चलाएँ), फिर दोबारा कोशिश करें।", -"fakegame.fw.more": "क्यों?", -"fakegame.fw.title_v2": "इंस्टॉल होने पर यह PS5 गेम FW {fw} पर शुरू नहीं होगा", -"fakegame.fw.body_v3": "PS5 फ़ेक पैकेज {last} तक के फ़र्मवेयर पर चलते हैं। FW {fw} पर पैकेज इंस्टॉल हो जाता है, पर गेम शुरू नहीं होता। PS4 पैकेज और PS5 होमब्रू ऐप ठीक हैं।", first_run_helper_only: "केवल ps5upload भेजें", first_run_helper_only_hint: "क्या आप पहले से ही kstuff ख़ुद लोड करते हैं (कोई autoloader, etaHEN, elf-arsenal)? केवल ps5upload भेजें। kstuff को दूसरी बार लोड करने से उसकी एक और कॉपी जुड़ जाती है। इस या नए संस्करण का हेल्पर चलता रहता है। kstuff और ShadowMount+ तभी छोड़े जाते हैं जब हेल्पर पहले से चल रहा हो, क्योंकि क्या चल रहा है यह देखने के लिए ऐप को उसकी ज़रूरत होती है।", first_run_step_already_running: "पहले से चल रहा है — दोबारा नहीं भेजा गया", @@ -5271,7 +5264,6 @@ install_path_fallback_label: "जब PS5 इस कंप्यूटर तक "installed_fix_permissions_done": "अनुमतियाँ ठीक कर दी गईं: इस गेम के फ़ोल्डर की हर फ़ाइल अब 0777 है। चलाएँ दबाएँ।", "installed_fix_permissions_short": "अनुमतियाँ ठीक करें", "installed_launch_homebrew_refused": "PS5 ने यह गेम शुरू करने से मना कर दिया (0x80940033)। कंसोल अभी homebrew या नकली-पैकेज गेम शुरू नहीं कर रहा है: kstuff दोबारा लोड करें (या रीबूट करके फिर से जेलब्रेक चलाएँ), फिर दोबारा चलाएँ दबाएँ।", -"fakegame.fw.launch_v3": "{last} से ऊपर के फ़र्मवेयर पर (यह कंसोल {fw} पर है) फ़ेक पैकेज से इंस्टॉल किया PS5 गेम शुरू नहीं होता। PS4 पैकेज ठीक हैं।", "fakegame.fw.launch_kstuff": "अगर यह गेम फ़ेक पैकेज से इंस्टॉल हुआ है: FW {fw} पर यह सिर्फ़ उस kstuff बिल्ड से शुरू होता है जो वहाँ फ़ेक पैकेज सपोर्ट करता है (नवंबर 2026 या नया)। वह kstuff लोड करें, फिर दोबारा Play दबाएँ।", "installed_launch_no_kstuff": "PS5 ने यह गेम शुरू करने से मना कर दिया (0x80940033) क्योंकि kstuff नहीं चल रहा है। इसके बिना कंसोल कोई homebrew या नकली-पैकेज गेम शुरू नहीं करता। kstuff लोड करें (आपका autoloader, या कनेक्शन → सेट करें) और दोबारा चलाएँ दबाएँ।", job_why_lanes: "कनेक्शन: औसतन {avg}, अधिकतम {max}; चंक {chunk}", diff --git a/client/src/i18n/locales/hu.ts b/client/src/i18n/locales/hu.ts index 31670ec85..1f18314b7 100644 --- a/client/src/i18n/locales/hu.ts +++ b/client/src/i18n/locales/hu.ts @@ -3854,8 +3854,6 @@ cshares_delete_body: "A Minion többé nem mutatja. A szerveren semmi sem válto "cq_skipped_later_part": "{count} kihagyva: egy többrészes archívum későbbi része. Helyette az első részt (.part1.rar) add hozzá.", "fpkg.cancel_stop_queue": "Megszakítás és a sor leállítása", "fpkg.cancelled": "Megszakítva. Semmi sem készült el.", -"fpkg.unpacked_unplayable_title": "Lehet, hogy ez a csomag nem fut", -"fpkg.unpacked_unplayable": "Ez a PS5-játék csomagként települne, de FW {fw} alatt nem futna. Szakítsd meg, és készíts inkább játék-lemezképet.", "fpkg.unpack_lost": "Az alkalmazás kicsomagolás közben bezárult, így a játék nem készült el. Kezdd újra.", "fpkg.make.archive_later": "Az archívumot kicsomagolás után vizsgáljuk, ezért itt nincs kijelölve semmi.", "fpkg.lowSpaceCompressed": "Kevés a szabad hely: a játék {size}, a tömörített lemezkép általában ennek nagyjából a fele, a célmeghajtón pedig {free} van. Lehet, hogy nem fér el.", @@ -4295,9 +4293,7 @@ shell_description_v2: "Írj be parancsokat, amelyek a PS5-ön, a segédfolyamato "fpkg.make.image_title": "Egy játékképfájl", "fpkg.make.image_body": "Egy fájl a PS5 meghajtóján, amelyet a ShadowMount+ csatol és a kezdőképernyőn mutat. Semmi nem települ, és olyan firmware-en is fut, ahol egy PS5-csomag nem.", "fpkg.make.recommended": "Ajánlott", -"fpkg.make.recommended_fw": "Ajánlott FW {fw} esetén", "fpkg.make.pick_game": "Ellenőrizz egy játékot az ① alatt, és a PS5-ödhöz jobb választás meg lesz jelölve.", -"fpkg.make.why_image": "Ez a PS5-játék csomagként települne, de FW {fw} alatt nem futna; képfájlként igen.", "fpkg.make.why_pkg": "A csomag a szokásos választás: úgy települ és fut, mint bármely más játék.", "fpkg.run.summary": "{what} készít a(z) {title} játékból ide: {dir}.", "fpkg.run.what_image": "{ext} játékképfájlt", @@ -5520,9 +5516,6 @@ cheats_toast_loaded: "Csalások betöltve ehhez: {name}", engine_job_files_done: "{done} / {total} fájl", engine_job_running_title: "A motoron még fut egy átvitel", err_launch_homebrew_refused: "A PS5 megtagadta a cím indítását (0x80940033). A konzol most nem indít homebrew-t és hamis csomagos játékot: töltsd be a kstuffot (vagy indítsd újra, és futtasd újra a jailbreaket), majd próbáld újra.", -"fakegame.fw.more": "Miért?", -"fakegame.fw.title_v2": "Telepítve ez a PS5-játék nem indul el a(z) {fw} firmware-en", -"fakegame.fw.body_v3": "A PS5 hamis csomagok {last} firmware-ig futnak. FW {fw} alatt a csomag települ, de a játék nem indul el. A PS4 csomagok és a PS5 homebrew alkalmazások rendben vannak.", first_run_helper_only: "Csak a ps5upload küldése", first_run_helper_only_hint: "Már magad töltöd be a kstuffot (autoloader, etaHEN, elf-arsenal)? Küldd csak a ps5uploadot. A kstuff másodszori betöltése egy újabb példányt tesz rá. Az ilyen vagy újabb verziójú segédprogram tovább fut. A kstuff és a ShadowMount+ csak akkor marad ki, ha a segédprogram már fut, mert az alkalmazásnak szüksége van rá, hogy lássa, mi fut.", first_run_step_already_running: "már fut — nincs újraküldve", @@ -5549,7 +5542,6 @@ install_path_fallback_label: "Telepítés fájlútvonal alapján, ha a PS5 nem "installed_fix_permissions_done": "Jogosultságok javítva: a játék mappájában minden fájl most 0777. Nyomd meg a Játék gombot.", "installed_fix_permissions_short": "Jogosultságok javítása", "installed_launch_homebrew_refused": "A PS5 megtagadta a játék indítását (0x80940033). A konzol most nem indít homebrew-t és hamis csomagos játékot: töltsd be újra a kstuffot (vagy indítsd újra, és futtasd újra a jailbreaket), majd nyomd meg újra a Játék gombot.", -"fakegame.fw.launch_v3": "{last} feletti firmware-en (ez a konzol {fw}) a hamis csomagból telepített PS5 játék nem indul el. A PS4 csomagok rendben vannak.", "fakegame.fw.launch_kstuff": "Ha ez a játék hamis csomagból települt: FW {fw} alatt csak olyan kstuff-fal indul, amely ott támogatja a hamis csomagokat (2026. novemberi vagy újabb). Töltsd be azt a kstuff-ot, majd nyomd meg újra a Játék gombot.", "installed_launch_no_kstuff": "A PS5 megtagadta a játék indítását (0x80940033), mert a kstuff nem fut. Nélküle a konzol semmilyen homebrew-t vagy hamis csomagos játékot nem indít. Töltsd be a kstuffot (az autoloadereddel vagy a Kapcsolat → Beállítás menüben), és nyomd meg újra a Játék gombot.", job_why_lanes: "Kapcsolatok: átlagosan {avg}, legfeljebb {max}; blokk {chunk}", diff --git a/client/src/i18n/locales/id.ts b/client/src/i18n/locales/id.ts index 7c272ad78..78b123681 100644 --- a/client/src/i18n/locales/id.ts +++ b/client/src/i18n/locales/id.ts @@ -3493,8 +3493,6 @@ cshares_delete_body: "Minion tidak lagi menampilkannya. Tidak ada yang berubah d "cq_skipped_later_part": "{count} dilewati: bagian lanjutan dari arsip multi-bagian. Tambahkan bagian pertamanya (.part1.rar).", "fpkg.cancel_stop_queue": "Batalkan dan hentikan antrean", "fpkg.cancelled": "Dibatalkan. Tidak ada yang selesai.", -"fpkg.unpacked_unplayable_title": "Paket ini mungkin tidak jalan", -"fpkg.unpacked_unplayable": "Game PS5 ini bisa dipasang sebagai paket tapi tidak jalan di FW {fw}. Batalkan dan buat image game.", "fpkg.unpack_lost": "Aplikasi tertutup saat membongkar, jadi game tidak dibuat. Mulai lagi.", "fpkg.make.archive_later": "Arsip diperiksa setelah dibongkar, jadi tidak ada pilihan yang ditandai di sini.", "fpkg.lowSpaceCompressed": "Ruang kosong sedikit: game ini {size}, image terkompresi biasanya sekitar setengahnya, dan drive keluaran punya {free}. Mungkin tidak muat.", @@ -4012,9 +4010,7 @@ shell_description_v2: "Ketik perintah yang berjalan di PS5, di dalam proses help "fpkg.make.image_title": "Image game", "fpkg.make.image_body": "Satu berkas di drive PS5 yang di-mount ShadowMount+ dan tampil di layar utama. Tidak ada yang dipasang, dan jalan di firmware yang tidak bisa menjalankan paket PS5.", "fpkg.make.recommended": "Disarankan", -"fpkg.make.recommended_fw": "Disarankan di FW {fw}", "fpkg.make.pick_game": "Periksa game di ①, pilihan yang lebih cocok untuk PS5 Anda akan ditandai.", -"fpkg.make.why_image": "Game PS5 ini bisa dipasang sebagai paket tapi tidak jalan di FW {fw}; sebagai image, jalan.", "fpkg.make.why_pkg": "Paket adalah pilihan biasa: terpasang dan jalan seperti game lain.", "fpkg.run.summary": "Membuat {what} dari {title} di {dir}.", "fpkg.run.what_image": "image game {ext}", @@ -5237,9 +5233,6 @@ cheats_toast_loaded: "Cheat dimuat untuk {name}", engine_job_files_done: "{done} dari {total} file", engine_job_running_title: "Sebuah transfer masih berjalan di engine", err_launch_homebrew_refused: "PS5 menolak menjalankan judul ini (0x80940033). Konsol sedang tidak menjalankan homebrew atau game paket palsu: muat kstuff (atau reboot dan jalankan jailbreak lagi), lalu coba lagi.", -"fakegame.fw.more": "Kenapa?", -"fakegame.fw.title_v2": "Saat terpasang, game PS5 ini tidak mau mulai di FW {fw}", -"fakegame.fw.body_v3": "Paket palsu PS5 berjalan di firmware hingga {last}. Di FW {fw} paket terpasang, tetapi game tidak mau mulai. Paket PS4 dan aplikasi homebrew PS5 tidak terpengaruh.", first_run_helper_only: "Kirim hanya ps5upload", first_run_helper_only_hint: "Sudah memuat kstuff sendiri (autoloader, etaHEN, elf-arsenal)? Kirim hanya ps5upload. Memuat kstuff untuk kedua kalinya menumpuk salinan lain. Helper versi ini atau lebih baru dibiarkan berjalan. kstuff dan ShadowMount+ hanya dilewati jika helper sudah berjalan, karena aplikasi memerlukannya untuk melihat apa yang berjalan.", first_run_step_already_running: "sudah berjalan — tidak dikirim lagi", @@ -5266,7 +5259,6 @@ install_path_fallback_label: "Pasang lewat path file saat PS5 tidak bisa menjang "installed_fix_permissions_done": "Izin diperbaiki: setiap file di folder game ini sekarang 0777. Tekan Mainkan.", "installed_fix_permissions_short": "Perbaiki izin", "installed_launch_homebrew_refused": "PS5 menolak menjalankan game ini (0x80940033). Konsol sedang tidak menjalankan homebrew atau game paket palsu: muat ulang kstuff (atau reboot dan jalankan jailbreak lagi), lalu tekan Mainkan lagi.", -"fakegame.fw.launch_v3": "Di firmware di atas {last} (konsol ini di {fw}) game PS5 yang dipasang dari paket palsu tidak mau mulai. Paket PS4 tidak terpengaruh.", "fakegame.fw.launch_kstuff": "Jika game ini dipasang dari paket palsu: di FW {fw} game hanya mulai dengan build kstuff yang mendukung paket palsu di sana (November 2026 atau lebih baru). Muat kstuff itu, lalu tekan Main lagi.", "installed_launch_no_kstuff": "PS5 menolak menjalankan game ini (0x80940033) karena kstuff tidak berjalan. Tanpanya, konsol tidak menjalankan homebrew atau game paket palsu apa pun. Muat kstuff (autoloader-mu, atau Koneksi → Siapkan) lalu tekan Mainkan lagi.", job_why_lanes: "Koneksi: rata-rata {avg}, paling banyak {max}; chunk {chunk}", diff --git a/client/src/i18n/locales/it.ts b/client/src/i18n/locales/it.ts index ab65ef6ee..3adc16c99 100644 --- a/client/src/i18n/locales/it.ts +++ b/client/src/i18n/locales/it.ts @@ -3437,8 +3437,6 @@ cshares_delete_body: "Minion smette di mostrarla. Sul server non cambia nulla.", "cq_skipped_later_part": "{count} saltati: una parte successiva di un archivio in più parti. Aggiungi invece la prima parte (.part1.rar).", "fpkg.cancel_stop_queue": "Annulla e ferma la coda", "fpkg.cancelled": "Annullato. Non è stato completato nulla.", -"fpkg.unpacked_unplayable_title": "Questo pacchetto potrebbe non funzionare", -"fpkg.unpacked_unplayable": "Questo gioco PS5 si installerebbe come pacchetto ma non funzionerebbe su FW {fw}. Annulla e crea invece un'immagine di gioco.", "fpkg.unpack_lost": "L'app si è chiusa durante l'estrazione, quindi il gioco non è stato creato. Ricomincia.", "fpkg.make.archive_later": "Un archivio viene esaminato dopo l'estrazione, quindi qui non è segnata nessuna scelta.", "fpkg.lowSpaceCompressed": "Poco spazio libero: questo gioco occupa {size}, un'immagine compressa di solito circa la metà, e l'unità di destinazione ha {free}. Potrebbe non bastare.", @@ -3956,9 +3954,7 @@ shell_description_v2: "Digita comandi che vengono eseguiti sulla PS5, nel proces "fpkg.make.image_title": "Un'immagine di gioco", "fpkg.make.image_body": "Un file su un disco della PS5 che ShadowMount+ monta e mostra nella schermata iniziale. Non si installa nulla e funziona sui firmware dove un pacchetto PS5 non funziona.", "fpkg.make.recommended": "Consigliato", -"fpkg.make.recommended_fw": "Consigliato su FW {fw}", "fpkg.make.pick_game": "Controlla un gioco in ① e verrà segnata la scelta migliore per la tua PS5.", -"fpkg.make.why_image": "Questo gioco PS5 si installerebbe come pacchetto ma non funzionerebbe su FW {fw}; come immagine sì.", "fpkg.make.why_pkg": "Un pacchetto è la scelta abituale: si installa e funziona come qualsiasi altro gioco.", "fpkg.run.summary": "Crea {what} di {title} in {dir}.", "fpkg.run.what_image": "un'immagine di gioco {ext}", @@ -5181,9 +5177,6 @@ cheats_toast_loaded: "Trucchi caricati per {name}", engine_job_files_done: "{done} di {total} file", engine_job_running_title: "Un trasferimento è ancora in corso sul motore", err_launch_homebrew_refused: "La PS5 ha rifiutato di avviare questo titolo (0x80940033). Al momento la console non avvia homebrew né giochi da pacchetti fake: carica kstuff (oppure riavvia ed esegui di nuovo il jailbreak), poi riprova.", -"fakegame.fw.more": "Perché?", -"fakegame.fw.title_v2": "Installato, questo gioco PS5 non si avvia con il FW {fw}", -"fakegame.fw.body_v3": "I pacchetti fake PS5 funzionano sui firmware fino al {last}. Sul FW {fw} il pacchetto si installa, ma il gioco non parte. I pacchetti PS4 e le app homebrew PS5 funzionano.", first_run_helper_only: "Invia solo ps5upload", first_run_helper_only_hint: "Carichi già kstuff da solo (un autoloader, etaHEN, elf-arsenal)? Invia solo ps5upload. Caricare kstuff una seconda volta ne impila un'altra copia. Un helper di questa versione o più recente resta in esecuzione. kstuff e ShadowMount+ vengono saltati solo se l'helper è già attivo, perché l'app ne ha bisogno per vedere cosa è in esecuzione.", first_run_step_already_running: "già in esecuzione — non reinviato", @@ -5210,7 +5203,6 @@ install_path_fallback_label: "Installa tramite percorso del file quando la PS5 n "installed_fix_permissions_done": "Permessi corretti: ogni file nella cartella di questo gioco ora è 0777. Premi Gioca.", "installed_fix_permissions_short": "Correggi permessi", "installed_launch_homebrew_refused": "La PS5 ha rifiutato di avviare questo gioco (0x80940033). Al momento la console non avvia homebrew né giochi da pacchetti fake: ricarica kstuff (oppure riavvia ed esegui di nuovo il jailbreak), poi premi di nuovo Gioca.", -"fakegame.fw.launch_v3": "Sui firmware oltre il {last} (questa console è al {fw}) un gioco PS5 installato da un pacchetto fake non parte. I pacchetti PS4 funzionano.", "fakegame.fw.launch_kstuff": "Se questo gioco è stato installato da un pacchetto fake: sul FW {fw} parte solo con una build di kstuff che lì supporta i pacchetti fake (novembre 2026 o più recente). Carica quel kstuff, poi premi di nuovo Gioca.", "installed_launch_no_kstuff": "La PS5 ha rifiutato di avviare questo gioco (0x80940033) perché kstuff non è in esecuzione. Senza di esso la console non avvia homebrew né giochi da pacchetti fake. Carica kstuff (con il tuo autoloader, oppure Connessione → Configura) e premi di nuovo Gioca.", job_why_lanes: "Connessioni: {avg} in media, {max} al massimo; blocco {chunk}", diff --git a/client/src/i18n/locales/ja.ts b/client/src/i18n/locales/ja.ts index 3db7ae5fa..eeca1dbc0 100644 --- a/client/src/i18n/locales/ja.ts +++ b/client/src/i18n/locales/ja.ts @@ -3503,8 +3503,6 @@ cshares_delete_body: "Minion に表示されなくなります。サーバー側 "cq_skipped_later_part": "{count} 件をスキップ:複数パートのアーカイブの後続パートです。代わりに最初のパート (.part1.rar) を追加してください。", "fpkg.cancel_stop_queue": "キャンセルしてキューを止める", "fpkg.cancelled": "キャンセルしました。何も完成していません。", -"fpkg.unpacked_unplayable_title": "このパッケージは起動しない可能性があります", -"fpkg.unpacked_unplayable": "この PS5 ゲームはパッケージではインストールできても FW {fw} では起動しません。キャンセルしてゲームイメージを作ってください。", "fpkg.unpack_lost": "展開中にアプリが閉じたため、ゲームは作成されませんでした。もう一度始めてください。", "fpkg.make.archive_later": "アーカイブは展開後に確認するため、ここでは何も示しません。", "fpkg.lowSpaceCompressed": "空き容量が少なめです。このゲームは {size}、圧縮イメージは通常その半分ほどで、出力先ドライブには {free} あります。入らない可能性があります。", @@ -4022,9 +4020,7 @@ shell_description_v2: "PS5 のヘルパープロセス内で実行されるコ "fpkg.make.image_title": "ゲームイメージ", "fpkg.make.image_body": "PS5 のドライブに置く 1 ファイルで、ShadowMount+ がマウントしてホーム画面に表示します。何もインストールされず、PS5 パッケージが動かないファームウェアでも動きます。", "fpkg.make.recommended": "おすすめ", -"fpkg.make.recommended_fw": "FW {fw} ではおすすめ", "fpkg.make.pick_game": "① でゲームを確認すると、お使いの PS5 に合う方に印が付きます。", -"fpkg.make.why_image": "この PS5 ゲームはパッケージではインストールできても FW {fw} では起動しません。イメージなら起動します。", "fpkg.make.why_pkg": "パッケージが通常の選択です。他のゲームと同じようにインストールして遊べます。", "fpkg.run.summary": "{title} の{what}を {dir} に作成します。", "fpkg.run.what_image": "{ext} ゲームイメージ", @@ -5247,9 +5243,6 @@ cheats_toast_loaded: "{name} のチートを読み込みました", engine_job_files_done: "{done} / {total} ファイル", engine_job_running_title: "エンジンで転送がまだ実行中です", err_launch_homebrew_refused: "PS5 がこのタイトルの起動を拒否しました(0x80940033)。本体は現在、自作アプリやフェイクパッケージのゲームを起動しない状態です。kstuff を読み込んで(または再起動してもう一度脱獄して)から、再試行してください。", -"fakegame.fw.more": "なぜ?", -"fakegame.fw.title_v2": "インストールしても、この PS5 ゲームは FW {fw} では起動しません", -"fakegame.fw.body_v3": "PS5 のフェイクパッケージはファームウェア {last} まで動作します。FW {fw} ではパッケージはインストールされますが、ゲームは起動しません。PS4 パッケージと PS5 の自作アプリは問題ありません。", first_run_helper_only: "ps5upload だけを送信", first_run_helper_only_hint: "kstuff をすでに自分で読み込んでいますか(オートローダー、etaHEN、elf-arsenal)? ps5upload だけを送信してください。kstuff を 2 回読み込むと別のコピーが重なります。このバージョン以降のヘルパーはそのまま動作を続けます。kstuff と ShadowMount+ が省略されるのはヘルパーがすでに動作している場合だけです。何が動作中かを確認するのにヘルパーが必要なためです。", first_run_step_already_running: "すでに実行中 — 再送信しません", @@ -5276,7 +5269,6 @@ install_path_fallback_label: "PS5 がこのコンピューターに接続でき "installed_fix_permissions_done": "権限を修正しました。このゲームのフォルダー内のすべてのファイルが 0777 になりました。プレイを押してください。", "installed_fix_permissions_short": "権限を修正", "installed_launch_homebrew_refused": "PS5 がこのゲームの起動を拒否しました(0x80940033)。本体は現在、自作アプリやフェイクパッケージのゲームを起動しない状態です。kstuff を読み込み直して(または再起動してもう一度脱獄して)から、もう一度プレイを押してください。", -"fakegame.fw.launch_v3": "{last} より新しいファームウェア(この本体は {fw})では、フェイクパッケージからインストールした PS5 ゲームは起動しません。PS4 パッケージは問題ありません。", "fakegame.fw.launch_kstuff": "このゲームをフェイクパッケージからインストールした場合:FW {fw} では、そこでフェイクパッケージに対応した kstuff(2026 年 11 月以降)でしか起動しません。その kstuff を読み込んでから、もう一度プレイを押してください。", "installed_launch_no_kstuff": "kstuff が実行されていないため、PS5 がこのゲームの起動を拒否しました(0x80940033)。kstuff がないと、本体は自作アプリやフェイクパッケージのゲームを起動しません。kstuff を読み込んで(オートローダー、または 接続 → セットアップ)、もう一度プレイを押してください。", job_why_lanes: "接続数: 平均 {avg}、最大 {max}。チャンク {chunk}", diff --git a/client/src/i18n/locales/ko.ts b/client/src/i18n/locales/ko.ts index 05a8f2f2a..7515001cd 100644 --- a/client/src/i18n/locales/ko.ts +++ b/client/src/i18n/locales/ko.ts @@ -3501,8 +3501,6 @@ cshares_delete_body: "Minion에 더 이상 표시되지 않습니다. 서버에 "cq_skipped_later_part": "{count}개 건너뜀: 여러 부분으로 된 압축 파일의 뒷부분입니다. 대신 첫 부분(.part1.rar)을 추가하세요.", "fpkg.cancel_stop_queue": "취소하고 대기열 중지", "fpkg.cancelled": "취소되었습니다. 완료된 것은 없습니다.", -"fpkg.unpacked_unplayable_title": "이 패키지는 실행되지 않을 수 있습니다", -"fpkg.unpacked_unplayable": "이 PS5 게임은 패키지로 설치되지만 FW {fw}에서 실행되지 않습니다. 취소하고 게임 이미지를 만드세요.", "fpkg.unpack_lost": "압축을 푸는 중에 앱이 닫혀 게임이 만들어지지 않았습니다. 다시 시작하세요.", "fpkg.make.archive_later": "압축 파일은 푼 뒤에 확인하므로 여기에는 표시되는 선택이 없습니다.", "fpkg.lowSpaceCompressed": "여유 공간이 적습니다. 이 게임은 {size}이고 압축 이미지는 보통 그 절반 정도이며, 출력 드라이브에는 {free} 있습니다. 들어가지 않을 수 있습니다.", @@ -4020,9 +4018,7 @@ shell_description_v2: "PS5의 헬퍼 프로세스 안에서 실행되는 명령 "fpkg.make.image_title": "게임 이미지", "fpkg.make.image_body": "PS5 드라이브에 두는 파일 하나로, ShadowMount+가 마운트해 홈 화면에 표시합니다. 아무것도 설치되지 않으며 PS5 패키지가 실행되지 않는 펌웨어에서도 실행됩니다.", "fpkg.make.recommended": "추천", -"fpkg.make.recommended_fw": "FW {fw}에서 추천", "fpkg.make.pick_game": "①에서 게임을 확인하면 PS5에 더 맞는 쪽이 표시됩니다.", -"fpkg.make.why_image": "이 PS5 게임은 패키지로 설치되지만 FW {fw}에서 실행되지 않습니다. 이미지로는 실행됩니다.", "fpkg.make.why_pkg": "패키지가 일반적인 선택입니다. 다른 게임처럼 설치되고 실행됩니다.", "fpkg.run.summary": "{title}의 {what}을(를) {dir}에 만듭니다.", "fpkg.run.what_image": "{ext} 게임 이미지", @@ -5245,9 +5241,6 @@ cheats_toast_loaded: "{name}의 치트를 불러왔습니다", engine_job_files_done: "파일 {total}개 중 {done}개", engine_job_running_title: "엔진에서 전송이 아직 실행 중입니다", err_launch_homebrew_refused: "PS5가 이 타이틀의 시작을 거부했습니다(0x80940033). 지금 본체가 홈브루나 가짜 패키지 게임을 시작하지 않는 상태입니다. kstuff를 로드한 다음(또는 재부팅 후 탈옥을 다시 실행한 다음) 다시 시도하세요.", -"fakegame.fw.more": "왜 그런가요?", -"fakegame.fw.title_v2": "설치하면 이 PS5 게임은 FW {fw}에서 시작되지 않습니다", -"fakegame.fw.body_v3": "PS5 페이크 패키지는 펌웨어 {last}까지 실행됩니다. FW {fw}에서는 패키지가 설치되지만 게임이 시작되지 않습니다. PS4 패키지와 PS5 홈브루 앱은 문제없습니다.", first_run_helper_only: "ps5upload만 보내기", first_run_helper_only_hint: "kstuff를 이미 직접 로드하나요(오토로더, etaHEN, elf-arsenal)? ps5upload만 보내세요. kstuff를 두 번 로드하면 사본이 하나 더 쌓입니다. 이 버전 이상의 헬퍼는 그대로 실행됩니다. kstuff와 ShadowMount+는 헬퍼가 이미 실행 중일 때만 건너뜁니다. 무엇이 실행 중인지 확인하려면 헬퍼가 필요하기 때문입니다.", first_run_step_already_running: "이미 실행 중 — 다시 보내지 않음", @@ -5274,7 +5267,6 @@ install_path_fallback_label: "PS5가 이 컴퓨터에 연결할 수 없을 때 "installed_fix_permissions_done": "권한이 수정되었습니다. 이 게임 폴더의 모든 파일이 이제 0777입니다. 실행을 누르세요.", "installed_fix_permissions_short": "권한 수정", "installed_launch_homebrew_refused": "PS5가 이 게임의 시작을 거부했습니다(0x80940033). 지금 본체가 홈브루나 가짜 패키지 게임을 시작하지 않는 상태입니다. kstuff를 다시 로드한 다음(또는 재부팅 후 탈옥을 다시 실행한 다음) 실행을 다시 누르세요.", -"fakegame.fw.launch_v3": "{last}보다 높은 펌웨어(이 콘솔은 {fw})에서는 페이크 패키지로 설치한 PS5 게임이 시작되지 않습니다. PS4 패키지는 문제없습니다.", "fakegame.fw.launch_kstuff": "이 게임을 페이크 패키지로 설치했다면: FW {fw}에서는 그 펌웨어의 페이크 패키지를 지원하는 kstuff 빌드(2026년 11월 이후)로만 시작됩니다. 그 kstuff를 불러온 뒤 다시 플레이를 누르세요.", "installed_launch_no_kstuff": "kstuff가 실행 중이 아니어서 PS5가 이 게임의 시작을 거부했습니다(0x80940033). kstuff가 없으면 본체는 홈브루나 가짜 패키지 게임을 시작하지 않습니다. kstuff를 로드하고(오토로더, 또는 연결 → 설정) 실행을 다시 누르세요.", job_why_lanes: "연결: 평균 {avg}개, 최대 {max}개, 청크 {chunk}", diff --git a/client/src/i18n/locales/pl.ts b/client/src/i18n/locales/pl.ts index c961ff642..8c618766a 100644 --- a/client/src/i18n/locales/pl.ts +++ b/client/src/i18n/locales/pl.ts @@ -3721,8 +3721,6 @@ cshares_delete_body: "Minion przestanie go pokazywać. Na serwerze nic się nie "cq_skipped_later_part": "Pominięto {count}: dalsza część archiwum wieloczęściowego. Dodaj zamiast tego pierwszą część (.part1.rar).", "fpkg.cancel_stop_queue": "Anuluj i zatrzymaj kolejkę", "fpkg.cancelled": "Anulowano. Nic nie ukończono.", -"fpkg.unpacked_unplayable_title": "Ten pakiet może nie działać", -"fpkg.unpacked_unplayable": "Ta gra PS5 zainstalowałaby się jako pakiet, ale nie ruszy na FW {fw}. Anuluj i utwórz obraz gry.", "fpkg.unpack_lost": "Aplikacja zamknęła się podczas rozpakowywania, więc gra nie powstała. Zacznij od nowa.", "fpkg.make.archive_later": "Archiwum jest sprawdzane po rozpakowaniu, więc nic nie jest tu zaznaczone.", "fpkg.lowSpaceCompressed": "Mało wolnego miejsca: ta gra ma {size}, skompresowany obraz zwykle około połowy tego, a dysk docelowy ma {free}. Może się nie zmieścić.", @@ -4240,9 +4238,7 @@ shell_description_v2: "Wpisuj polecenia wykonywane na PS5 w procesie pomocnika. "fpkg.make.image_title": "Obraz gry", "fpkg.make.image_body": "Jeden plik na dysku PS5, który ShadowMount+ montuje i pokazuje na ekranie głównym. Nic nie jest instalowane, a działa na firmware, na którym pakiet PS5 nie ruszy.", "fpkg.make.recommended": "Zalecane", -"fpkg.make.recommended_fw": "Zalecane na FW {fw}", "fpkg.make.pick_game": "Sprawdź grę w ①, a lepszy wybór dla twojej PS5 zostanie oznaczony.", -"fpkg.make.why_image": "Ta gra PS5 zainstalowałaby się jako pakiet, ale nie ruszy na FW {fw}; jako obraz działa.", "fpkg.make.why_pkg": "Pakiet to zwykły wybór: instaluje się i działa jak każda inna gra.", "fpkg.run.summary": "Tworzy {what} gry {title} w {dir}.", "fpkg.run.what_image": "obraz gry {ext}", @@ -5465,9 +5461,6 @@ cheats_toast_loaded: "Wczytano kody dla {name}", engine_job_files_done: "{done} z {total} plików", engine_job_running_title: "Na silniku nadal trwa transfer", err_launch_homebrew_refused: "PS5 odmówiła uruchomienia tego tytułu (0x80940033). Konsola nie uruchamia teraz homebrew ani gier z fałszywych pakietów: wczytaj kstuff (albo uruchom ponownie i wykonaj jailbreak jeszcze raz), a potem spróbuj ponownie.", -"fakegame.fw.more": "Dlaczego?", -"fakegame.fw.title_v2": "Zainstalowana, ta gra PS5 nie uruchomi się na FW {fw}", -"fakegame.fw.body_v3": "Fałszywe pakiety PS5 działają na oprogramowaniu do {last}. Na FW {fw} pakiet się instaluje, ale gra się nie uruchamia. Pakiety PS4 i aplikacje homebrew PS5 działają.", first_run_helper_only: "Wyślij tylko ps5upload", first_run_helper_only_hint: "Wczytujesz już kstuff samodzielnie (autoloader, etaHEN, elf-arsenal)? Wyślij tylko ps5upload. Ponowne wczytanie kstuff nakłada kolejną kopię. Pomocnik w tej lub nowszej wersji pozostaje uruchomiony. kstuff i ShadowMount+ są pomijane tylko wtedy, gdy pomocnik już działa, bo aplikacja potrzebuje go, by zobaczyć, co jest uruchomione.", first_run_step_already_running: "już działa — nie wysłano ponownie", @@ -5494,7 +5487,6 @@ install_path_fallback_label: "Instaluj według ścieżki pliku, gdy PS5 nie moż "installed_fix_permissions_done": "Uprawnienia naprawione: każdy plik w folderze tej gry ma teraz 0777. Naciśnij Graj.", "installed_fix_permissions_short": "Napraw uprawnienia", "installed_launch_homebrew_refused": "PS5 odmówiła uruchomienia tej gry (0x80940033). Konsola nie uruchamia teraz homebrew ani gier z fałszywych pakietów: wczytaj ponownie kstuff (albo uruchom ponownie i wykonaj jailbreak jeszcze raz), a potem znów naciśnij Graj.", -"fakegame.fw.launch_v3": "Na oprogramowaniu nowszym niż {last} (ta konsola ma {fw}) gra PS5 zainstalowana z fałszywego pakietu się nie uruchamia. Pakiety PS4 działają.", "fakegame.fw.launch_kstuff": "Jeśli ta gra została zainstalowana z fałszywego pakietu: na FW {fw} uruchamia się tylko z wersją kstuff obsługującą tam fałszywe pakiety (z listopada 2026 lub nowszą). Załaduj ten kstuff i ponownie naciśnij Graj.", "installed_launch_no_kstuff": "PS5 odmówiła uruchomienia tej gry (0x80940033), bo kstuff nie działa. Bez niego konsola nie uruchamia żadnego homebrew ani gry z fałszywego pakietu. Wczytaj kstuff (autoloaderem albo przez Połączenie → Skonfiguruj) i znów naciśnij Graj.", job_why_lanes: "Połączenia: średnio {avg}, maksymalnie {max}; blok {chunk}", diff --git a/client/src/i18n/locales/pt-BR.ts b/client/src/i18n/locales/pt-BR.ts index 52a3dd55e..6255569d3 100644 --- a/client/src/i18n/locales/pt-BR.ts +++ b/client/src/i18n/locales/pt-BR.ts @@ -3499,8 +3499,6 @@ cshares_delete_body: "O Minion deixa de mostrá-lo. Nada muda no servidor.", "cq_skipped_later_part": "{count} ignorados: uma parte posterior de um arquivo em várias partes. Adicione a primeira parte (.part1.rar).", "fpkg.cancel_stop_queue": "Cancelar e parar a fila", "fpkg.cancelled": "Cancelado. Nada foi concluído.", -"fpkg.unpacked_unplayable_title": "Este pacote pode não rodar", -"fpkg.unpacked_unplayable": "Este jogo de PS5 instalaria como pacote, mas não rodaria no FW {fw}. Cancele e crie uma imagem de jogo.", "fpkg.unpack_lost": "O app fechou durante a extração, então o jogo não foi criado. Comece de novo.", "fpkg.make.archive_later": "Um arquivo é examinado depois de extraído, então nenhuma opção é marcada aqui.", "fpkg.lowSpaceCompressed": "Pouco espaço livre: este jogo tem {size}, uma imagem comprimida costuma ter cerca da metade, e a unidade de saída tem {free}. Pode não caber.", @@ -4018,9 +4016,7 @@ shell_description_v2: "Digite comandos que rodam no PS5, no processo do auxiliar "fpkg.make.image_title": "Uma imagem de jogo", "fpkg.make.image_body": "Um arquivo em um drive do PS5 que o ShadowMount+ monta e mostra na tela inicial. Nada é instalado, e roda em firmwares onde um pacote de PS5 não roda.", "fpkg.make.recommended": "Recomendado", -"fpkg.make.recommended_fw": "Recomendado no FW {fw}", "fpkg.make.pick_game": "Verifique um jogo em ① e a melhor escolha para o seu PS5 será marcada.", -"fpkg.make.why_image": "Este jogo de PS5 instalaria como pacote, mas não rodaria no FW {fw}; como imagem, roda.", "fpkg.make.why_pkg": "Um pacote é a escolha comum: instala e roda como qualquer outro jogo.", "fpkg.run.summary": "Cria {what} de {title} em {dir}.", "fpkg.run.what_image": "uma imagem de jogo {ext}", @@ -5243,9 +5239,6 @@ cheats_toast_loaded: "Truques carregados para {name}", engine_job_files_done: "{done} de {total} arquivos", engine_job_running_title: "Uma transferência ainda está em andamento no motor", err_launch_homebrew_refused: "O PS5 se recusou a iniciar este título (0x80940033). O console não está iniciando homebrew nem jogos de pacotes falsos no momento: carregue o kstuff (ou reinicie e execute o jailbreak novamente) e tente de novo.", -"fakegame.fw.more": "Por quê?", -"fakegame.fw.title_v2": "Instalado, este jogo de PS5 não inicia no FW {fw}", -"fakegame.fw.body_v3": "Pacotes fake de PS5 rodam em firmware até {last}. No FW {fw} o pacote instala, mas o jogo não abre. Pacotes de PS4 e apps homebrew de PS5 funcionam.", first_run_helper_only: "Enviar só o ps5upload", first_run_helper_only_hint: "Você já carrega o kstuff por conta própria (um autoloader, etaHEN, elf-arsenal)? Envie só o ps5upload. Carregar o kstuff uma segunda vez empilha outra cópia. Um auxiliar desta versão ou mais novo continua em execução. kstuff e ShadowMount+ só são ignorados se o auxiliar já estiver em execução, porque o app precisa dele para ver o que está rodando.", first_run_step_already_running: "já em execução — não enviado de novo", @@ -5272,7 +5265,6 @@ install_path_fallback_label: "Instalar pelo caminho do arquivo quando o PS5 não "installed_fix_permissions_done": "Permissões corrigidas: todos os arquivos na pasta deste jogo agora são 0777. Pressione Jogar.", "installed_fix_permissions_short": "Corrigir permissões", "installed_launch_homebrew_refused": "O PS5 se recusou a iniciar este jogo (0x80940033). O console não está iniciando homebrew nem jogos de pacotes falsos no momento: recarregue o kstuff (ou reinicie e execute o jailbreak novamente) e pressione Jogar de novo.", -"fakegame.fw.launch_v3": "Em firmware acima de {last} (este console está no {fw}) um jogo de PS5 instalado de um pacote fake não abre. Pacotes de PS4 funcionam.", "fakegame.fw.launch_kstuff": "Se este jogo foi instalado de um pacote fake: no FW {fw} ele só abre com uma versão do kstuff que suporte pacotes fake ali (de novembro de 2026 ou mais nova). Carregue esse kstuff e toque em Jogar de novo.", "installed_launch_no_kstuff": "O PS5 se recusou a iniciar este jogo (0x80940033) porque o kstuff não está em execução. Sem ele, o console não inicia nenhum homebrew nem jogo de pacote falso. Carregue o kstuff (seu autoloader, ou Conexão → Configurar) e pressione Jogar de novo.", job_why_lanes: "Conexões: {avg} em média, {max} no máximo; bloco {chunk}", diff --git a/client/src/i18n/locales/ru.ts b/client/src/i18n/locales/ru.ts index 1362c29a2..4354639da 100644 --- a/client/src/i18n/locales/ru.ts +++ b/client/src/i18n/locales/ru.ts @@ -3437,8 +3437,6 @@ cshares_delete_body: "Minion перестанет её показывать. Н "cq_skipped_later_part": "Пропущено {count}: следующая часть многотомного архива. Добавьте вместо неё первую часть (.part1.rar).", "fpkg.cancel_stop_queue": "Отменить и остановить очередь", "fpkg.cancelled": "Отменено. Ничего не завершено.", -"fpkg.unpacked_unplayable_title": "Этот пакет может не запуститься", -"fpkg.unpacked_unplayable": "Эта игра PS5 установится как пакет, но не запустится на FW {fw}. Отмените и создайте образ игры.", "fpkg.unpack_lost": "Приложение закрылось во время распаковки, поэтому игра не создана. Начните заново.", "fpkg.make.archive_later": "Архив проверяется после распаковки, поэтому здесь ничего не отмечено.", "fpkg.lowSpaceCompressed": "Мало свободного места: игра занимает {size}, сжатый образ обычно примерно вдвое меньше, а на диске вывода {free}. Может не поместиться.", @@ -3956,9 +3954,7 @@ shell_description_v2: "Вводите команды, которые выпол "fpkg.make.image_title": "Образ игры", "fpkg.make.image_body": "Один файл на диске PS5, который ShadowMount+ монтирует и показывает на главном экране. Ничего не устанавливается, и он работает на прошивках, где пакет PS5 не запустится.", "fpkg.make.recommended": "Рекомендуется", -"fpkg.make.recommended_fw": "Рекомендуется на FW {fw}", "fpkg.make.pick_game": "Проверьте игру в ①, и лучший вариант для вашей PS5 будет отмечен.", -"fpkg.make.why_image": "Эта игра PS5 установится как пакет, но не запустится на FW {fw}; как образ — запустится.", "fpkg.make.why_pkg": "Пакет — обычный выбор: он устанавливается и работает как любая другая игра.", "fpkg.run.summary": "Создаёт {what} для {title} в {dir}.", "fpkg.run.what_image": "образ игры {ext}", @@ -5181,9 +5177,6 @@ cheats_toast_loaded: "Читы для {name} загружены", engine_job_files_done: "{done} из {total} файлов", engine_job_running_title: "На движке ещё идёт передача", err_launch_homebrew_refused: "PS5 отказалась запускать этот тайтл (0x80940033). Сейчас консоль не запускает homebrew и игры из фейковых пакетов: загрузите kstuff (или перезагрузитесь и снова выполните джейлбрейк), затем повторите попытку.", -"fakegame.fw.more": "Почему?", -"fakegame.fw.title_v2": "Установленная, эта игра PS5 не запустится на прошивке {fw}", -"fakegame.fw.body_v3": "Фейковые пакеты PS5 работают на прошивке до {last}. На FW {fw} пакет устанавливается, но игра не запускается. Пакеты PS4 и homebrew-приложения PS5 работают.", first_run_helper_only: "Отправить только ps5upload", first_run_helper_only_hint: "Уже загружаете kstuff сами (автозагрузчик, etaHEN, elf-arsenal)? Отправьте только ps5upload. Повторная загрузка kstuff добавляет ещё одну копию. Помощник этой или более новой версии продолжает работать. kstuff и ShadowMount+ пропускаются, только если помощник уже работает: без него приложение не видит, что запущено.", first_run_step_already_running: "уже запущен — повторно не отправлен", @@ -5210,7 +5203,6 @@ install_path_fallback_label: "Устанавливать по пути к фай "installed_fix_permissions_done": "Права исправлены: у каждого файла в папке этой игры теперь 0777. Нажмите «Играть».", "installed_fix_permissions_short": "Исправить права", "installed_launch_homebrew_refused": "PS5 отказалась запускать эту игру (0x80940033). Сейчас консоль не запускает homebrew и игры из фейковых пакетов: перезагрузите kstuff (или перезагрузите консоль и снова выполните джейлбрейк), затем снова нажмите «Играть».", -"fakegame.fw.launch_v3": "На прошивке выше {last} (эта консоль на {fw}) игра PS5, установленная из фейкового пакета, не запускается. Пакеты PS4 работают.", "fakegame.fw.launch_kstuff": "Если игра установлена из фейкового пакета: на FW {fw} она запускается только со сборкой kstuff, поддерживающей там фейковые пакеты (ноябрь 2026 или новее). Загрузите этот kstuff и снова нажмите «Играть».", "installed_launch_no_kstuff": "PS5 отказалась запускать эту игру (0x80940033), потому что kstuff не запущен. Без него консоль не запускает ни homebrew, ни игры из фейковых пакетов. Загрузите kstuff (автозагрузчиком или через Подключение → Настроить) и снова нажмите «Играть».", job_why_lanes: "Соединения: в среднем {avg}, максимум {max}; блок {chunk}", diff --git a/client/src/i18n/locales/th.ts b/client/src/i18n/locales/th.ts index ab8103eca..5e6ed8c7d 100644 --- a/client/src/i18n/locales/th.ts +++ b/client/src/i18n/locales/th.ts @@ -3491,8 +3491,6 @@ cshares_delete_body: "Minion จะไม่แสดงอีก ไม่ม "cq_skipped_later_part": "ข้าม {count}: เป็นส่วนถัดไปของไฟล์บีบอัดหลายส่วน ให้เพิ่มส่วนแรก (.part1.rar) แทน", "fpkg.cancel_stop_queue": "ยกเลิกและหยุดคิว", "fpkg.cancelled": "ยกเลิกแล้ว ไม่มีอะไรเสร็จ", -"fpkg.unpacked_unplayable_title": "แพ็กเกจนี้อาจเล่นไม่ได้", -"fpkg.unpacked_unplayable": "เกม PS5 นี้ติดตั้งเป็นแพ็กเกจได้แต่เล่นบน FW {fw} ไม่ได้ ยกเลิกแล้วสร้างอิมเมจเกมแทน", "fpkg.unpack_lost": "แอปปิดระหว่างแตกไฟล์ จึงไม่ได้สร้างเกม เริ่มใหม่อีกครั้ง", "fpkg.make.archive_later": "ไฟล์บีบอัดจะถูกตรวจหลังแตกไฟล์ จึงไม่มีตัวเลือกที่ทำเครื่องหมายไว้ที่นี่", "fpkg.lowSpaceCompressed": "พื้นที่ว่างเหลือน้อย: เกมนี้ขนาด {size} อิมเมจบีบอัดมักประมาณครึ่งหนึ่ง และไดรฟ์ปลายทางมี {free} อาจไม่พอ", @@ -4010,9 +4008,7 @@ shell_description_v2: "พิมพ์คำสั่งที่ทำงาน "fpkg.make.image_title": "อิมเมจเกม", "fpkg.make.image_body": "ไฟล์เดียวบนไดรฟ์ PS5 ที่ ShadowMount+ เมานต์และแสดงบนหน้าหลัก ไม่มีการติดตั้ง และเล่นได้บนเฟิร์มแวร์ที่แพ็กเกจ PS5 เล่นไม่ได้", "fpkg.make.recommended": "แนะนำ", -"fpkg.make.recommended_fw": "แนะนำบน FW {fw}", "fpkg.make.pick_game": "ตรวจสอบเกมใน ① แล้วตัวเลือกที่เหมาะกับ PS5 ของคุณจะถูกทำเครื่องหมาย", -"fpkg.make.why_image": "เกม PS5 นี้ติดตั้งเป็นแพ็กเกจได้แต่เล่นบน FW {fw} ไม่ได้ ส่วนอิมเมจเล่นได้", "fpkg.make.why_pkg": "แพ็กเกจคือตัวเลือกปกติ ติดตั้งและเล่นได้เหมือนเกมอื่น", "fpkg.run.summary": "สร้าง{what}ของ {title} ใน {dir}", "fpkg.run.what_image": "อิมเมจเกม {ext}", @@ -5235,9 +5231,6 @@ cheats_toast_loaded: "โหลดสูตรโกงของ {name} แล engine_job_files_done: "{done} จาก {total} ไฟล์", engine_job_running_title: "ยังมีการถ่ายโอนทำงานอยู่บนเอนจิน", err_launch_homebrew_refused: "PS5 ปฏิเสธการเริ่มเกมนี้ (0x80940033) ขณะนี้เครื่องไม่ยอมเริ่ม homebrew หรือเกมจากแพ็กเกจปลอม: โหลด kstuff (หรือรีบูตแล้วรันเจลเบรกอีกครั้ง) แล้วลองใหม่", -"fakegame.fw.more": "ทำไม?", -"fakegame.fw.title_v2": "เมื่อติดตั้งแล้ว เกม PS5 นี้จะไม่เริ่มบน FW {fw}", -"fakegame.fw.body_v3": "แพ็กเกจปลอมของ PS5 เล่นได้บนเฟิร์มแวร์ถึง {last} บน FW {fw} แพ็กเกจติดตั้งได้ แต่เกมไม่เริ่ม แพ็กเกจ PS4 และแอปโฮมบรูว์ PS5 ใช้ได้ปกติ", first_run_helper_only: "ส่งเฉพาะ ps5upload", first_run_helper_only_hint: "คุณโหลด kstuff เองอยู่แล้วใช่ไหม (ตัวโหลดอัตโนมัติ, etaHEN, elf-arsenal)? ส่งเฉพาะ ps5upload การโหลด kstuff ซ้ำเป็นครั้งที่สองจะซ้อนอีกชุดหนึ่ง ตัวช่วยรุ่นนี้หรือใหม่กว่าจะทำงานต่อไป kstuff และ ShadowMount+ จะถูกข้ามก็ต่อเมื่อตัวช่วยทำงานอยู่แล้วเท่านั้น เพราะแอปต้องใช้ตัวช่วยเพื่อดูว่ามีอะไรทำงานอยู่", first_run_step_already_running: "ทำงานอยู่แล้ว — ไม่ส่งซ้ำ", @@ -5264,7 +5257,6 @@ install_path_fallback_label: "ติดตั้งด้วยพาธไฟ "installed_fix_permissions_done": "แก้ไขสิทธิ์แล้ว: ทุกไฟล์ในโฟลเดอร์ของเกมนี้เป็น 0777 แล้ว กดเล่น", "installed_fix_permissions_short": "แก้ไขสิทธิ์", "installed_launch_homebrew_refused": "PS5 ปฏิเสธการเริ่มเกมนี้ (0x80940033) ขณะนี้เครื่องไม่ยอมเริ่ม homebrew หรือเกมจากแพ็กเกจปลอม: โหลด kstuff ใหม่ (หรือรีบูตแล้วรันเจลเบรกอีกครั้ง) แล้วกดเล่นอีกครั้ง", -"fakegame.fw.launch_v3": "บนเฟิร์มแวร์ที่สูงกว่า {last} (เครื่องนี้ใช้ {fw}) เกม PS5 ที่ติดตั้งจากแพ็กเกจปลอมจะไม่เริ่ม แพ็กเกจ PS4 ใช้ได้ปกติ", "fakegame.fw.launch_kstuff": "หากเกมนี้ติดตั้งจากแพ็กเกจปลอม: บน FW {fw} เกมจะเริ่มได้เฉพาะกับ kstuff รุ่นที่รองรับแพ็กเกจปลอมบนเฟิร์มแวร์นั้น (พฤศจิกายน 2026 หรือใหม่กว่า) โหลด kstuff นั้นแล้วกดเล่นอีกครั้ง", "installed_launch_no_kstuff": "PS5 ปฏิเสธการเริ่มเกมนี้ (0x80940033) เพราะ kstuff ไม่ได้ทำงานอยู่ หากไม่มี kstuff เครื่องจะไม่เริ่ม homebrew หรือเกมจากแพ็กเกจปลอมใด ๆ โหลด kstuff (ตัวโหลดอัตโนมัติของคุณ หรือ การเชื่อมต่อ → ตั้งค่า) แล้วกดเล่นอีกครั้ง", job_why_lanes: "การเชื่อมต่อ: เฉลี่ย {avg} สูงสุด {max}; ชังก์ {chunk}", diff --git a/client/src/i18n/locales/tr.ts b/client/src/i18n/locales/tr.ts index 9e9dec841..2bef5050e 100644 --- a/client/src/i18n/locales/tr.ts +++ b/client/src/i18n/locales/tr.ts @@ -3491,8 +3491,6 @@ cshares_delete_body: "Minion artık onu göstermez. Sunucuda hiçbir şey deği "cq_skipped_later_part": "{count} atlandı: çok parçalı arşivin sonraki bir parçası. Bunun yerine ilk parçayı (.part1.rar) ekleyin.", "fpkg.cancel_stop_queue": "İptal et ve kuyruğu durdur", "fpkg.cancelled": "İptal edildi. Hiçbir şey tamamlanmadı.", -"fpkg.unpacked_unplayable_title": "Bu paket çalışmayabilir", -"fpkg.unpacked_unplayable": "Bu PS5 oyunu paket olarak kurulur ama FW {fw} üzerinde çalışmaz. İptal edip oyun imajı oluşturun.", "fpkg.unpack_lost": "Açılırken uygulama kapandı, bu yüzden oyun oluşturulmadı. Yeniden başlatın.", "fpkg.make.archive_later": "Arşiv açıldıktan sonra incelenir, bu yüzden burada bir seçenek işaretlenmez.", "fpkg.lowSpaceCompressed": "Boş alan az: bu oyun {size}, sıkıştırılmış imaj genelde bunun yaklaşık yarısıdır ve çıktı sürücüsünde {free} var. Sığmayabilir.", @@ -4010,9 +4008,7 @@ shell_description_v2: "PS5'te yardımcı işlemin içinde çalışan komutlar ya "fpkg.make.image_title": "Bir oyun kalıbı", "fpkg.make.image_body": "PS5 sürücüsündeki tek bir dosya; ShadowMount+ bağlar ve ana ekranda gösterir. Hiçbir şey kurulmaz ve PS5 paketinin çalışmadığı yazılımlarda çalışır.", "fpkg.make.recommended": "Önerilen", -"fpkg.make.recommended_fw": "FW {fw} için önerilen", "fpkg.make.pick_game": "① altında bir oyunu denetle; PS5'in için daha iyi seçim işaretlenir.", -"fpkg.make.why_image": "Bu PS5 oyunu paket olarak kurulur ama FW {fw} üzerinde çalışmaz; kalıp olarak çalışır.", "fpkg.make.why_pkg": "Paket olağan seçimdir: diğer oyunlar gibi kurulur ve çalışır.", "fpkg.run.summary": "{title} için {dir} içinde {what} oluşturur.", "fpkg.run.what_image": "bir {ext} oyun kalıbı", @@ -5235,9 +5231,6 @@ cheats_toast_loaded: "{name} için hileler yüklendi", engine_job_files_done: "{done}/{total} dosya", engine_job_running_title: "Motorda hâlâ bir aktarım sürüyor", err_launch_homebrew_refused: "PS5 bu başlığı başlatmayı reddetti (0x80940033). Konsol şu anda homebrew ya da sahte paket oyunlarını başlatmıyor: kstuff'ı yükle (ya da yeniden başlatıp jailbreak'i tekrar çalıştır), sonra yeniden dene.", -"fakegame.fw.more": "Neden?", -"fakegame.fw.title_v2": "Kurulu hâlde bu PS5 oyunu FW {fw} üzerinde başlamaz", -"fakegame.fw.body_v3": "PS5 sahte paketleri {last} sürümüne kadar olan yazılımlarda çalışır. FW {fw} üzerinde paket yüklenir ama oyun başlamaz. PS4 paketleri ve PS5 homebrew uygulamaları sorunsuzdur.", first_run_helper_only: "Yalnızca ps5upload gönder", first_run_helper_only_hint: "kstuff'ı zaten kendin mi yüklüyorsun (bir autoloader, etaHEN, elf-arsenal)? Yalnızca ps5upload gönder. kstuff'ı ikinci kez yüklemek üst üste bir kopya daha ekler. Bu sürümdeki veya daha yeni bir yardımcı çalışmaya devam eder. kstuff ve ShadowMount+ yalnızca yardımcı zaten çalışıyorsa atlanır, çünkü uygulama neyin çalıştığını görmek için ona ihtiyaç duyar.", first_run_step_already_running: "zaten çalışıyor — yeniden gönderilmedi", @@ -5264,7 +5257,6 @@ install_path_fallback_label: "PS5 bu bilgisayara ulaşamadığında dosya yoluyl "installed_fix_permissions_done": "İzinler düzeltildi: bu oyunun klasöründeki her dosya artık 0777. Oyna'ya bas.", "installed_fix_permissions_short": "İzinleri düzelt", "installed_launch_homebrew_refused": "PS5 bu oyunu başlatmayı reddetti (0x80940033). Konsol şu anda homebrew ya da sahte paket oyunlarını başlatmıyor: kstuff'ı yeniden yükle (ya da yeniden başlatıp jailbreak'i tekrar çalıştır), sonra yeniden Oyna'ya bas.", -"fakegame.fw.launch_v3": "{last} sürümünden yeni yazılımlarda (bu konsol {fw}) sahte paketten yüklenen bir PS5 oyunu başlamaz. PS4 paketleri sorunsuzdur.", "fakegame.fw.launch_kstuff": "Bu oyun sahte paketten yüklendiyse: FW {fw} üzerinde yalnızca orada sahte paketleri destekleyen bir kstuff sürümüyle başlar (Kasım 2026 veya daha yeni). O kstuff'ı yükleyin, sonra yeniden Oyna'ya basın.", "installed_launch_no_kstuff": "PS5 bu oyunu başlatmayı reddetti (0x80940033), çünkü kstuff çalışmıyor. O olmadan konsol hiçbir homebrew ya da sahte paket oyununu başlatmaz. kstuff'ı yükle (autoloader'ınla ya da Bağlantı → Kur ile) ve yeniden Oyna'ya bas.", job_why_lanes: "Bağlantılar: ortalama {avg}, en fazla {max}; blok {chunk}", diff --git a/client/src/i18n/locales/vi.ts b/client/src/i18n/locales/vi.ts index b500427d9..9104b35cb 100644 --- a/client/src/i18n/locales/vi.ts +++ b/client/src/i18n/locales/vi.ts @@ -3486,8 +3486,6 @@ cshares_delete_body: "Minion sẽ không hiện nó nữa. Không có gì thay "cq_skipped_later_part": "Đã bỏ qua {count}: phần sau của tệp nén nhiều phần. Hãy thêm phần đầu (.part1.rar).", "fpkg.cancel_stop_queue": "Hủy và dừng hàng đợi", "fpkg.cancelled": "Đã hủy. Chưa có gì hoàn tất.", -"fpkg.unpacked_unplayable_title": "Gói này có thể không chạy", -"fpkg.unpacked_unplayable": "Game PS5 này cài được dạng gói nhưng không chạy trên FW {fw}. Hãy hủy và tạo ảnh game.", "fpkg.unpack_lost": "Ứng dụng đã đóng khi đang giải nén nên game chưa được tạo. Hãy bắt đầu lại.", "fpkg.make.archive_later": "Tệp nén được xem sau khi giải nén nên ở đây không đánh dấu lựa chọn nào.", "fpkg.lowSpaceCompressed": "Sắp hết chỗ trống: game này {size}, ảnh nén thường khoảng một nửa, và ổ đầu ra còn {free}. Có thể không đủ.", @@ -4005,9 +4003,7 @@ shell_description_v2: "Gõ các lệnh chạy trên PS5, bên trong tiến trìn "fpkg.make.image_title": "Một ảnh game", "fpkg.make.image_body": "Một tệp trên ổ PS5 mà ShadowMount+ gắn và hiển thị ở màn hình chính. Không cài gì cả, và chạy trên firmware mà gói PS5 không chạy được.", "fpkg.make.recommended": "Nên chọn", -"fpkg.make.recommended_fw": "Nên chọn trên FW {fw}", "fpkg.make.pick_game": "Kiểm tra một game ở ①, lựa chọn phù hợp hơn cho PS5 của bạn sẽ được đánh dấu.", -"fpkg.make.why_image": "Game PS5 này cài được dạng gói nhưng không chạy trên FW {fw}; dạng ảnh thì chạy.", "fpkg.make.why_pkg": "Gói là lựa chọn thông thường: cài và chạy như mọi game khác.", "fpkg.run.summary": "Tạo {what} của {title} trong {dir}.", "fpkg.run.what_image": "một ảnh game {ext}", @@ -5230,9 +5226,6 @@ cheats_toast_loaded: "Đã tải mã gian lận cho {name}", engine_job_files_done: "{done} / {total} tệp", engine_job_running_title: "Một lần truyền vẫn đang chạy trên engine", err_launch_homebrew_refused: "PS5 đã từ chối khởi chạy tựa này (0x80940033). Hiện tại máy không khởi chạy homebrew hay trò chơi từ gói giả: hãy tải kstuff (hoặc khởi động lại và chạy jailbreak lần nữa), rồi thử lại.", -"fakegame.fw.more": "Vì sao?", -"fakegame.fw.title_v2": "Khi đã cài, game PS5 này không chạy trên FW {fw}", -"fakegame.fw.body_v3": "Gói giả PS5 chạy trên firmware đến {last}. Trên FW {fw}, gói vẫn cài được nhưng game không khởi động. Gói PS4 và ứng dụng homebrew PS5 vẫn dùng bình thường.", first_run_helper_only: "Chỉ gửi ps5upload", first_run_helper_only_hint: "Bạn đã tự tải kstuff (bằng autoloader, etaHEN, elf-arsenal)? Chỉ gửi ps5upload. Tải kstuff lần thứ hai sẽ chồng thêm một bản nữa. Trình trợ giúp phiên bản này hoặc mới hơn được giữ chạy. kstuff và ShadowMount+ chỉ được bỏ qua khi trình trợ giúp đã chạy, vì ứng dụng cần nó để xem những gì đang chạy.", first_run_step_already_running: "đang chạy sẵn — không gửi lại", @@ -5259,7 +5252,6 @@ install_path_fallback_label: "Cài theo đường dẫn tệp khi PS5 không k "installed_fix_permissions_done": "Đã sửa quyền: mọi tệp trong thư mục của trò chơi này giờ là 0777. Nhấn Chơi.", "installed_fix_permissions_short": "Sửa quyền", "installed_launch_homebrew_refused": "PS5 đã từ chối khởi chạy trò chơi này (0x80940033). Hiện tại máy không khởi chạy homebrew hay trò chơi từ gói giả: hãy tải lại kstuff (hoặc khởi động lại và chạy jailbreak lần nữa), rồi nhấn Chơi lần nữa.", -"fakegame.fw.launch_v3": "Trên firmware cao hơn {last} (máy này đang ở {fw}), game PS5 cài từ gói giả không khởi động. Gói PS4 vẫn dùng bình thường.", "fakegame.fw.launch_kstuff": "Nếu game này được cài từ gói giả: trên FW {fw} game chỉ khởi động với bản kstuff hỗ trợ gói giả ở đó (tháng 11/2026 hoặc mới hơn). Hãy nạp kstuff đó rồi bấm Chơi lại.", "installed_launch_no_kstuff": "PS5 đã từ chối khởi chạy trò chơi này (0x80940033) vì kstuff không chạy. Không có nó, máy không khởi chạy homebrew hay trò chơi từ gói giả nào. Hãy tải kstuff (bằng autoloader của bạn, hoặc Kết nối → Thiết lập) rồi nhấn Chơi lần nữa.", job_why_lanes: "Kết nối: trung bình {avg}, tối đa {max}; khối {chunk}", diff --git a/client/src/i18n/locales/zh-CN.ts b/client/src/i18n/locales/zh-CN.ts index d4a438c6e..a4ceda67b 100644 --- a/client/src/i18n/locales/zh-CN.ts +++ b/client/src/i18n/locales/zh-CN.ts @@ -3443,8 +3443,6 @@ cshares_delete_body: "Minion 将不再显示它,服务器上不会有任何改 "cq_skipped_later_part": "已跳过 {count} 个:这是分卷压缩包的后续分卷。请改为添加第一卷 (.part1.rar)。", "fpkg.cancel_stop_queue": "取消并停止队列", "fpkg.cancelled": "已取消。没有完成任何内容。", -"fpkg.unpacked_unplayable_title": "此封包可能无法运行", -"fpkg.unpacked_unplayable": "这个 PS5 游戏做成封包能安装但在 FW {fw} 上无法运行。请取消并改做游戏镜像。", "fpkg.unpack_lost": "解压时应用已关闭,因此游戏未制作。请重新开始。", "fpkg.make.archive_later": "压缩包解压后才会检查,因此这里不标记选择。", "fpkg.lowSpaceCompressed": "可用空间不足:此游戏 {size},压缩镜像通常约为其一半,输出驱动器有 {free}。可能放不下。", @@ -3962,9 +3960,7 @@ shell_description_v2: "输入在 PS5 上的助手进程内运行的命令。面 "fpkg.make.image_title": "游戏镜像", "fpkg.make.image_body": "放在 PS5 硬盘上的一个文件,由 ShadowMount+ 挂载并显示在主界面。不安装任何东西,而且在 PS5 封包无法运行的固件上也能玩。", "fpkg.make.recommended": "推荐", -"fpkg.make.recommended_fw": "FW {fw} 上推荐", "fpkg.make.pick_game": "在 ① 检查一个游戏,就会标出更适合你 PS5 的选择。", -"fpkg.make.why_image": "这个 PS5 游戏做成封包能安装但在 FW {fw} 上无法运行;做成镜像可以。", "fpkg.make.why_pkg": "封包是常规选择:像其他游戏一样安装和运行。", "fpkg.run.summary": "在 {dir} 中为 {title} 生成{what}。", "fpkg.run.what_image": "{ext} 游戏镜像", @@ -5187,9 +5183,6 @@ cheats_toast_loaded: "已加载 {name} 的金手指", engine_job_files_done: "{done} / {total} 个文件", engine_job_running_title: "引擎上仍有传输在运行", err_launch_homebrew_refused: "PS5 拒绝启动此标题(0x80940033)。主机当前不会启动自制程序或伪造软件包游戏:请加载 kstuff(或重启后再次运行越狱),然后重试。", -"fakegame.fw.more": "为什么?", -"fakegame.fw.title_v2": "安装后,这款 PS5 游戏在 FW {fw} 上无法启动", -"fakegame.fw.body_v3": "PS5 伪造包可在 {last} 及以下固件上运行。在 FW {fw} 上,包可以安装,但游戏无法启动。PS4 包和 PS5 自制应用不受影响。", first_run_helper_only: "只发送 ps5upload", first_run_helper_only_hint: "你已经自己加载 kstuff 了吗(自动加载器、etaHEN、elf-arsenal)?只发送 ps5upload 即可。再次加载 kstuff 会叠加一个副本。此版本或更新版本的助手会继续运行。只有助手已在运行时才会跳过 kstuff 和 ShadowMount+,因为应用需要它才能看到正在运行的内容。", first_run_step_already_running: "已在运行——不再发送", @@ -5216,7 +5209,6 @@ install_path_fallback_label: "当 PS5 无法连接到这台电脑时,按文件 "installed_fix_permissions_done": "权限已修复:此游戏文件夹中的所有文件现在都是 0777。请按运行。", "installed_fix_permissions_short": "修复权限", "installed_launch_homebrew_refused": "PS5 拒绝启动这款游戏(0x80940033)。主机当前不会启动自制程序或伪造软件包游戏:请重新加载 kstuff(或重启后再次运行越狱),然后再次按运行。", -"fakegame.fw.launch_v3": "在高于 {last} 的固件上(这台主机为 {fw}),从伪造包安装的 PS5 游戏无法启动。PS4 包不受影响。", "fakegame.fw.launch_kstuff": "如果此游戏是从伪造包安装的:在 FW {fw} 上,只有支持该固件伪造包的 kstuff 版本(2026 年 11 月或更新)才能启动它。请加载该 kstuff,然后再次点击“游玩”。", "installed_launch_no_kstuff": "由于 kstuff 没有运行,PS5 拒绝启动这款游戏(0x80940033)。没有它,主机不会启动任何自制程序或伪造软件包游戏。请加载 kstuff(你的自动加载器,或 连接 → 设置),然后再次按运行。", job_why_lanes: "连接数:平均 {avg},最多 {max};分块 {chunk}", diff --git a/client/src/i18n/locales/zh-TW.ts b/client/src/i18n/locales/zh-TW.ts index 2967bf90a..c4208b7c7 100644 --- a/client/src/i18n/locales/zh-TW.ts +++ b/client/src/i18n/locales/zh-TW.ts @@ -3437,8 +3437,6 @@ cshares_delete_body: "Minion 將不再顯示它,伺服器上不會有任何變 "cq_skipped_later_part": "已略過 {count} 個:這是分卷壓縮檔的後續分卷。請改為新增第一卷 (.part1.rar)。", "fpkg.cancel_stop_queue": "取消並停止佇列", "fpkg.cancelled": "已取消。沒有完成任何內容。", -"fpkg.unpacked_unplayable_title": "此封包可能無法執行", -"fpkg.unpacked_unplayable": "這個 PS5 遊戲做成封包能安裝但在 FW {fw} 上無法執行。請取消並改做遊戲映像。", "fpkg.unpack_lost": "解壓縮時應用程式已關閉,因此遊戲未製作。請重新開始。", "fpkg.make.archive_later": "壓縮檔解壓縮後才會檢查,因此這裡不標記選擇。", "fpkg.lowSpaceCompressed": "可用空間不足:此遊戲 {size},壓縮映像通常約為其一半,輸出磁碟機有 {free}。可能放不下。", @@ -3956,9 +3954,7 @@ shell_description_v2: "輸入在 PS5 上的助手處理程序內執行的指令 "fpkg.make.image_title": "遊戲映像", "fpkg.make.image_body": "放在 PS5 硬碟上的一個檔案,由 ShadowMount+ 掛載並顯示在主畫面。不安裝任何東西,而且在 PS5 封包無法執行的韌體上也能玩。", "fpkg.make.recommended": "推薦", -"fpkg.make.recommended_fw": "FW {fw} 上推薦", "fpkg.make.pick_game": "在 ① 檢查一個遊戲,就會標出更適合你 PS5 的選擇。", -"fpkg.make.why_image": "這個 PS5 遊戲做成封包能安裝但在 FW {fw} 上無法執行;做成映像可以。", "fpkg.make.why_pkg": "封包是一般的選擇:像其他遊戲一樣安裝和執行。", "fpkg.run.summary": "在 {dir} 中為 {title} 建立{what}。", "fpkg.run.what_image": "{ext} 遊戲映像", @@ -5181,9 +5177,6 @@ cheats_toast_loaded: "已載入 {name} 的金手指", engine_job_files_done: "{done} / {total} 個檔案", engine_job_running_title: "引擎上仍有傳輸在執行", err_launch_homebrew_refused: "PS5 拒絕啟動此標題(0x80940033)。主機目前不會啟動自製程式或偽造套件遊戲:請載入 kstuff(或重新開機後再次執行越獄),然後再試一次。", -"fakegame.fw.more": "為什麼?", -"fakegame.fw.title_v2": "安裝後,這款 PS5 遊戲在 FW {fw} 上無法啟動", -"fakegame.fw.body_v3": "PS5 偽造套件可在 {last} 以下的韌體上執行。在 FW {fw} 上,套件可以安裝,但遊戲無法啟動。PS4 套件和 PS5 自製應用程式不受影響。", first_run_helper_only: "只傳送 ps5upload", first_run_helper_only_hint: "你已經自行載入 kstuff 了嗎(自動載入器、etaHEN、elf-arsenal)?只傳送 ps5upload 即可。再次載入 kstuff 會疊加另一個副本。此版本或更新版本的助手會繼續執行。只有助手已在執行時才會略過 kstuff 和 ShadowMount+,因為應用程式需要它才能看到正在執行的內容。", first_run_step_already_running: "已在執行——不再傳送", @@ -5210,7 +5203,6 @@ install_path_fallback_label: "當 PS5 無法連線到這台電腦時,依檔案 "installed_fix_permissions_done": "權限已修正:此遊戲資料夾中的所有檔案現在都是 0777。請按執行。", "installed_fix_permissions_short": "修正權限", "installed_launch_homebrew_refused": "PS5 拒絕啟動這款遊戲(0x80940033)。主機目前不會啟動自製程式或偽造套件遊戲:請重新載入 kstuff(或重新開機後再次執行越獄),然後再按一次執行。", -"fakegame.fw.launch_v3": "在高於 {last} 的韌體上(這台主機為 {fw}),從偽造套件安裝的 PS5 遊戲無法啟動。PS4 套件不受影響。", "fakegame.fw.launch_kstuff": "如果此遊戲是從偽造套件安裝的:在 FW {fw} 上,只有支援該韌體偽造套件的 kstuff 版本(2026 年 11 月或更新)才能啟動它。請載入該 kstuff,然後再按一次「遊玩」。", "installed_launch_no_kstuff": "由於 kstuff 沒有在執行,PS5 拒絕啟動這款遊戲(0x80940033)。沒有它,主機不會啟動任何自製程式或偽造套件遊戲。請載入 kstuff(你的自動載入器,或 連線 → 設定),然後再按一次執行。", job_why_lanes: "連線數:平均 {avg},最多 {max};區塊 {chunk}", diff --git a/client/src/lib/ps5Firmware.test.ts b/client/src/lib/ps5Firmware.test.ts index a39b79054..21a178f3b 100644 --- a/client/src/lib/ps5Firmware.test.ts +++ b/client/src/lib/ps5Firmware.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { parsePS5Firmware, ps5FakeGameNeedsNewKstuff, ps5FakeGameUnplayableFirmware } from "./ps5Firmware"; +import { parsePS5Firmware, ps5FakeGameNeedsNewKstuff } from "./ps5Firmware"; describe("parsePS5Firmware", () => { it("extracts from 'releases/09.60' kernel string", () => { @@ -38,44 +38,6 @@ describe("parsePS5Firmware", () => { }); }); -describe("ps5FakeGameUnplayableFirmware", () => { - const K = (fw: string) => `FreeBSD 11.0-RELEASE-p0 #1 r229358/releases/${fw} Jul 17 2026`; - const PS5_GAME = "UP4433-PPSA17221_00-MINECRAFTPS50000"; - const PS4_GAME = "UP9000-CUSA00207_00-BLOODBORNE000000"; - const HOMEBREW = "IV0002-ITEM00001_00-ITEMZFLOWIV00000"; - - it("warns for a PS5 game above 13.60", () => { - expect(ps5FakeGameUnplayableFirmware(K("13.61"), PS5_GAME)).toBe("13.61"); - expect(ps5FakeGameUnplayableFirmware(K("14.00"), PS5_GAME)).toBe("14.00"); - }); - it("is silent at 13.60 and below: a kstuff with fake-package support covers 11.61 to 13.60", () => { - expect(ps5FakeGameUnplayableFirmware(K("13.60"), PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("12.00"), PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("11.61"), PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("11.60"), PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("09.60"), PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("05.10"), PS5_GAME)).toBeNull(); - }); - it("never warns for a PS4 package, even on 13.60", () => { - expect(ps5FakeGameUnplayableFirmware(K("13.60"), PS4_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("13.60"), "CUSA00207")).toBeNull(); - }); - it("never warns for PS5 homebrew (Itemzflow), even on 13.60", () => { - expect(ps5FakeGameUnplayableFirmware(K("13.60"), HOMEBREW)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("13.60"), "ITEM00001")).toBeNull(); - }); - it("accepts a bare PPSA title id", () => { - expect(ps5FakeGameUnplayableFirmware(K("14.00"), "PPSA17221")).toBe("14.00"); - }); - it("never warns when the firmware or the id is unknown", () => { - expect(ps5FakeGameUnplayableFirmware(null, PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware("unknown build", PS5_GAME)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("13.60"), null)).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("13.60"), "")).toBeNull(); - expect(ps5FakeGameUnplayableFirmware(K("13.60"), "something-else")).toBeNull(); - }); -}); - describe("ps5FakeGameNeedsNewKstuff", () => { const K = (fw: string) => `FreeBSD 11.0-RELEASE-p0 #1 r229358/releases/${fw} Jul 17 2026`; const PS5_GAME = "UP4433-PPSA17221_00-MINECRAFTPS50000"; diff --git a/client/src/lib/ps5Firmware.ts b/client/src/lib/ps5Firmware.ts index f30d30b4f..ee5852cdc 100644 --- a/client/src/lib/ps5Firmware.ts +++ b/client/src/lib/ps5Firmware.ts @@ -41,11 +41,9 @@ export function parsePS5Firmware(kernel: string | null | undefined): string | nu return null; } -/** The newest firmware on which a PS5 fake (FPKG) GAME is playable. Above it - * the package still installs, but the game does not start. 11.60 until November 2026, when a - * kstuff build with fake-package support up to 13.60 was released (11.61 to 13.60 need that - * build; the fake-package note says so). PS4 fake packages and PS5 homebrew apps are not - * affected. */ +/** The newest firmware a PS5 fake (FPKG) GAME is known to play on: 13.60, since a kstuff build + * with fake-package support up to it was released in November 2026 (11.61 to 13.60 need that + * build). No public jailbreak goes above it, so nothing warns about firmware past it. */ export const LAST_PS5_FAKE_GAME_FIRMWARE = "13.60"; /** True when `id` (a content id such as `UP4433-PPSA17221_00-MINECRAFTPS50000` @@ -57,24 +55,6 @@ export function isPs5GameId(id: string | null | undefined): boolean { return !!id && /(?:^|[^A-Z0-9])PPSA\d{5}(?![0-9])/.test(id.toUpperCase()); } -/** The console's firmware ("13.60") when a PS5 fake GAME package with this id - * would install but not be playable there, else null. That needs all of: - * a PS5 game id (not PS4, not homebrew) AND a parseable firmware strictly - * above LAST_PS5_FAKE_GAME_FIRMWARE. An unparseable kernel string never produces a warning. */ -export function ps5FakeGameUnplayableFirmware( - kernel: string | null | undefined, - contentOrTitleId: string | null | undefined, -): string | null { - if (!isPs5GameId(contentOrTitleId)) return null; - const fw = parsePS5Firmware(kernel); - if (!fw) return null; - const toNum = (v: string) => { - const [maj, min] = v.split("."); - return Number(maj) * 100 + Number(min); - }; - return toNum(fw) > toNum(LAST_PS5_FAKE_GAME_FIRMWARE) ? fw : null; -} - /** The newest firmware where a PS5 fake GAME played with any kstuff that loads fake packages. * Above it, up to LAST_PS5_FAKE_GAME_FIRMWARE, the game starts only with a kstuff build that * supports fake packages on that firmware (released November 2026). */ diff --git a/client/src/lib/useGameLaunch.tsx b/client/src/lib/useGameLaunch.tsx index be51825eb..d8fb42c3b 100644 --- a/client/src/lib/useGameLaunch.tsx +++ b/client/src/lib/useGameLaunch.tsx @@ -12,11 +12,7 @@ import { isHomebrewRefusal, type RefusalOutcome, } from "./launchRefusal"; -import { - LAST_PS5_FAKE_GAME_FIRMWARE, - ps5FakeGameNeedsNewKstuff, - ps5FakeGameUnplayableFirmware, -} from "./ps5Firmware"; +import { ps5FakeGameNeedsNewKstuff } from "./ps5Firmware"; import { fetchRunningGames, type RunningGame } from "./runningGames"; import { useStaleHostGuard } from "./staleHostGuard"; import { useMakeWay } from "./useMakeWay"; @@ -89,14 +85,6 @@ export function useGameLaunch( const kernel = useConnectionStore.getState().runtimeByHost[hostOf(launchHost)] ?.ps5Kernel; - const fw = ps5FakeGameUnplayableFirmware(kernel, titleId); - if (fw) { - return `${body} ${tr( - "fakegame.fw.launch_v3", - { fw, last: LAST_PS5_FAKE_GAME_FIRMWARE }, - `On firmware above ${LAST_PS5_FAKE_GAME_FIRMWARE} (this console is on ${fw}) a PS5 game installed from a fake package doesn't start. PS4 packages are fine.`, - )}`; - } // 11.61 to 13.60: a fake PS5 game starts only with the newer kstuff (November 2026). const kfw = ps5FakeGameNeedsNewKstuff(kernel, titleId); if (!kfw) return body; diff --git a/client/src/screens/FpkgConvert/MakeCard.tsx b/client/src/screens/FpkgConvert/MakeCard.tsx index 369023f2e..d89933ab9 100644 --- a/client/src/screens/FpkgConvert/MakeCard.tsx +++ b/client/src/screens/FpkgConvert/MakeCard.tsx @@ -1,7 +1,6 @@ import { Folder, Package, HardDrive } from "lucide-react"; import { Badge, Card } from "../../components"; -import { ps5FakeGameUnplayableFirmware } from "../../lib/ps5Firmware"; import type { MakeKind } from "../../state/convertPrefs"; import { useTr } from "../../state/lang"; @@ -21,17 +20,14 @@ export function NextGameNote() { /** * ② What to make: a package the PS5 installs, a game image ShadowMount+ mounts, or (#469) the - * game's files back as a plain folder. They are explained side by side, and the one of the - * first two that suits the game on the connected console is marked: a PS5 game on firmware - * above 13.60 installs as a package but will not play, so the image is the way; otherwise the - * package is the ordinary choice. The folder is never marked: it is a way back, not a way in. + * game's files back as a plain folder. They are explained side by side, and once a game is + * checked the package is marked as the ordinary choice (a PS5 fake package plays on every + * jailbroken firmware, up to 13.60). The folder is never marked: it is a way back, not a way in. * For a PS4 game the package is a PS4 fake package, which the engine writes from the game. */ export function MakeCard({ make, onMake, - kernel, - contentId, checked, archive = false, locked = false, @@ -41,10 +37,6 @@ export function MakeCard({ }: { make: MakeKind; onMake: (make: MakeKind) => void; - /** The connected console's kernel string, for the firmware line. */ - kernel: string | null | undefined; - /** The checked game's content id (or title id); null before a game is checked. */ - contentId: string | null | undefined; /** A game has been checked: the recommendation is about it. */ checked: boolean; /** The source is an archive: it is looked at only once a run unpacks it. */ @@ -59,16 +51,7 @@ export function MakeCard({ kraken?: boolean; }) { const tr = useTr(); - const unplayableOn = checked ? ps5FakeGameUnplayableFirmware(kernel, contentId) : null; - // With Kraken Mount a PS5 package is mounted, not installed, so it plays where an installed one - // would not, and an image would not be mounted at all. - const recommended: "pkg" | "image" | null = !checked - ? null - : kraken && !ps4 - ? "pkg" - : unplayableOn - ? "image" - : "pkg"; + const recommended: "pkg" | null = checked ? "pkg" : null; const tiles: { id: MakeKind; icon: typeof Package; title: string; body: string }[] = [ ps4 ? { @@ -156,9 +139,7 @@ export function MakeCard({ {t.title} {recommended === t.id && ( - {t.id === "image" && unplayableOn - ? tr("fpkg.make.recommended_fw", { fw: unplayableOn }, "Recommended on FW {fw}") - : tr("fpkg.make.recommended", undefined, "Recommended")} + {tr("fpkg.make.recommended", undefined, "Recommended")} )} @@ -180,12 +161,6 @@ export function MakeCard({ undefined, "Kraken Mount runs on this PS5: a package made here is mounted from a drive, not installed.", ) - : unplayableOn - ? tr( - "fpkg.make.why_image", - { fw: unplayableOn }, - "This PS5 game would install as a package but not play on FW {fw}; as an image it does.", - ) : tr("fpkg.make.why_pkg", undefined, "A package is the ordinary choice: it installs and plays like any other game.")} } diff --git a/client/src/screens/FpkgConvert/cards.test.tsx b/client/src/screens/FpkgConvert/cards.test.tsx index a5adf7221..f8ae5c638 100644 --- a/client/src/screens/FpkgConvert/cards.test.tsx +++ b/client/src/screens/FpkgConvert/cards.test.tsx @@ -70,40 +70,31 @@ describe("CompressionTiles", () => { describe("MakeCard", () => { it("does not ask to check an archive, which is looked at when it is unpacked", () => { const html = renderToStaticMarkup( - {}} kernel="11.00" contentId={null} checked={false} archive />, + {}} checked={false} archive />, ); expect(html).not.toContain("Check a game"); expect(html).toContain("after it is unpacked"); }); - it("explains both, and marks the image for a PS5 game the firmware will not play as a package", () => { - const fw = renderToStaticMarkup( - {}} kernel="r229358/releases/14.00" contentId="UP9000-PPSA03671_00-X" checked />, - ); + it("explains both, and marks the package once a game is checked", () => { + const fw = renderToStaticMarkup( {}} checked />); expect(fw).toContain("A package (.pkg)"); expect(fw).toContain("A game image"); - expect(fw).toContain("Recommended on FW 14.00"); - expect(fw).toContain("not play on FW 14.00"); - // Up to 13.60 an installed PS5 package plays (with a fake-package kstuff): the package is the - // ordinary choice, not the image. - const fw1360 = renderToStaticMarkup( - {}} kernel="r229358/releases/13.60" contentId="UP9000-PPSA03671_00-X" checked />, - ); - expect(fw1360).not.toContain("Recommended on FW"); - expect(fw1360).toContain("plays on firmware up to 13.60"); + expect(fw.match(/Recommended/g)).toHaveLength(1); + expect(fw).toContain("plays on firmware up to 13.60"); const ps4 = renderToStaticMarkup( - {}} kernel="r229358/releases/13.60" contentId="UP9000-CUSA01234_00-X" checked />, + {}} checked />, ); expect(ps4).not.toContain("Recommended on FW"); expect(ps4.match(/Recommended/g)).toHaveLength(1); - const none = renderToStaticMarkup( {}} kernel={null} contentId={null} checked={false} />); + const none = renderToStaticMarkup( {}} checked={false} />); expect(none).not.toContain("Recommended"); expect(none).toContain("Check a game under"); }); it("with Kraken Mount running, marks the package (mounted, not installed) and says images aren't mounted", () => { const k = renderToStaticMarkup( - {}} kernel="r229358/releases/13.60" contentId="UP9000-PPSA03671_00-X" checked kraken />, + {}} checked kraken />, ); expect(k).not.toContain("Recommended on FW"); expect(k.match(/Recommended/g)).toHaveLength(1); @@ -111,14 +102,14 @@ describe("MakeCard", () => { expect(k).toContain("a package made here is mounted from a drive, not installed"); expect(k).toContain("Kraken Mount, running on this PS5, mounts it"); const img = renderToStaticMarkup( - {}} kernel={null} contentId={null} checked={false} kraken />, + {}} checked={false} kraken />, ); expect(img).toContain("does not mount images"); }); it("offers a game folder as a third choice, never marked as recommended", () => { const out = renderToStaticMarkup( - {}} kernel="r229358/releases/9.60" contentId="UP9000-PPSA03671_00-X" checked />, + {}} checked />, ); expect((out.match(/role="radio"/g) ?? []).length).toBe(3); expect(out).toContain("A game folder"); @@ -158,7 +149,7 @@ describe("OptionsCard for a folder", () => { describe("A PS4 game's package", () => { it("is offered as a PS4 package under ②", () => { const out = renderToStaticMarkup( - {}} kernel="r229358/releases/13.60" contentId="UP9000-CUSA01234_00-X" checked ps4 />, + {}} checked ps4 />, ); expect(out).toContain("A PS4 package (.pkg)"); expect(out).toContain("A PS4 fake package the PS5 installs"); @@ -697,7 +688,7 @@ describe("a waiting game's own options (#669)", () => { it("while a game is being made, ② and ③ are open and say they are for the next game", () => { const make = renderToStaticMarkup( - {}} kernel={null} contentId={null} checked={false} forNext />, + {}} checked={false} forNext />, ); expect(make).toContain('data-testid="next-game-note"'); expect(make).not.toMatch(/]* disabled=""/); diff --git a/client/src/screens/FpkgConvert/index.tsx b/client/src/screens/FpkgConvert/index.tsx index a2c2b87a0..099e2c5e9 100644 --- a/client/src/screens/FpkgConvert/index.tsx +++ b/client/src/screens/FpkgConvert/index.tsx @@ -16,8 +16,7 @@ import { Folder, FolderSearch, HardDrive, Hammer, Send } from "lucide-react"; import { fpkg, type AmprLz4Options, type FpkgEstimates, type FpkgInspection, type ZstdPacks } from "../../api/fpkg"; import { appLaunch } from "../../api/ps5"; import { Button, Callout, Card, PageHeader } from "../../components"; -import { FakeGameFirmwareNotice } from "../../components/FakeGameFirmwareNotice"; -import { hostOf, transferAddr } from "../../lib/addr"; +import { transferAddr } from "../../lib/addr"; import { createLatest } from "../../lib/latest"; import { openLocalPath } from "../../lib/openLocalPath"; import { pickPath } from "../../lib/pickPath"; @@ -148,9 +147,6 @@ export default function WorkshopScreen() { const kraken = krakenIsTheMounter(mounterProbe.status === "checking" ? null : mounterProbe.status); const [mountRun, setMountRun] = useState(IDLE_MOUNT_RUN); const mountClash = useMountClashAsk(host); - const kernel = useConnectionStore((s) => - host ? (s.runtimeByHost[hostOf(host)]?.ps5Kernel ?? null) : null, - ); const outputDir = useConvertPrefs((s) => s.outputDir); const setOutputDir = useConvertPrefs((s) => s.setOutputDir); @@ -1185,12 +1181,6 @@ export default function WorkshopScreen() { } /> - {/* Building still works (it runs on this computer), but a PS5 fake GAME - installs and then can't be played on firmware above 13.60. Said - before the user spends an hour converting; silent for PS4, for - homebrew and when the firmware is unknown. */} - - {/* One column at every width (the user asked for it): the steps read top to bottom, ① to ⑤, and each card takes the window's whole width. */}
@@ -1204,8 +1194,6 @@ export default function WorkshopScreen() { if (m === "folder") setThen("keep"); }} // While a game is being made, what is checked under ① is that game, not the next. - kernel={locked ? null : kernel} - contentId={locked ? null : inspection?.content_id} checked={!locked && inspection !== null} archive={!locked && isArchiveSource(src)} forNext={locked} diff --git a/client/src/screens/InstallPackage/index.tsx b/client/src/screens/InstallPackage/index.tsx index 6eadc8838..7a9ded004 100644 --- a/client/src/screens/InstallPackage/index.tsx +++ b/client/src/screens/InstallPackage/index.tsx @@ -58,7 +58,6 @@ import { Toggle, } from "../../components"; import { BrowseButton } from "../../components/BrowseButton"; -import { FakeGameFirmwareNotice } from "../../components/FakeGameFirmwareNotice"; import { DOC_ANCHORS, faqLink, @@ -153,9 +152,6 @@ function PkgRow({ }) { const tr = useTr(); const navigate = useNavigate(); - const kernel = useConnectionStore( - (s) => s.runtimeByHost[hostOf(host)]?.ps5Kernel ?? null, - ); // After the console refused this package from its own storage, Retry with Stream is offered // beside Install when the engine says that is safe for this package. const streamOffered = !!entry.lastResult?.retryWithStream && !!onRetryStream; @@ -588,15 +584,6 @@ function PkgRow({ {!busy && !entry.lastResult?.ok && entry.lastResult?.netDiag && ( )} - {/* A fake PS5 GAME on firmware above 13.60 installs but cannot be - played. Not shown for a retail-signed package, PS4, or homebrew. */} - {!installed && entry.authenticity !== "retail" && ( - - )} ); } diff --git a/client/src/state/fpkgConversion.test.ts b/client/src/state/fpkgConversion.test.ts index ab7fb0c1a..31b75033b 100644 --- a/client/src/state/fpkgConversion.test.ts +++ b/client/src/state/fpkgConversion.test.ts @@ -1162,23 +1162,6 @@ describe("fpkg pipeline", () => { expect(second).not.toBe(first); }); - it("says after unpacking when the game inside would not play as a package here", async () => { - const { pushNotification } = await import("./notifications"); - vi.mocked(pushNotification).mockClear(); - const was = (conn as { ps5Kernel?: string | null }).ps5Kernel; - (conn as { ps5Kernel?: string | null }).ps5Kernel = "r229358/releases/14.00"; - inspect.mockResolvedValueOnce({ content_id: "UP9000-PPSA03671_00-X" }); - jobStatus - .mockResolvedValueOnce({ status: "done", dest: "/out/.ps5upload-extract-x2/G", bytes_sent: 1 }) - .mockResolvedValueOnce({ status: "failed", error: "stop here" }); - await useFpkgConversion.getState().start({ source: "/dl/g.7z", outputDir: "/out" }, { install: false, host: null }); - await tick(); - await tick(); - expect(inspect).toHaveBeenCalledWith("/out/.ps5upload-extract-x2/G", "/out"); - expect(pushNotification).toHaveBeenCalledWith("warning", expect.anything(), expect.objectContaining({ link: "/workshop" })); - (conn as { ps5Kernel?: string | null }).ps5Kernel = was; - }); - it("unpacks a local archive, builds the game inside, then removes the unpack", async () => { const game = "/out/.ps5upload-extract-x1/My Game"; jobStatus diff --git a/client/src/state/fpkgConversion.ts b/client/src/state/fpkgConversion.ts index eff3243af..d436d42fb 100644 --- a/client/src/state/fpkgConversion.ts +++ b/client/src/state/fpkgConversion.ts @@ -7,7 +7,6 @@ import { isTarArchiveName, stripTarSuffix } from "../lib/tarNames"; import { create } from "zustand"; import { t as translate } from "../i18n"; -import { ps5FakeGameUnplayableFirmware } from "../lib/ps5Firmware"; import { useLangStore } from "./lang"; import { useConvertPrefs, type AmprEmuBuild } from "./convertPrefs"; @@ -916,7 +915,6 @@ async function prepareThenStart( return; } update({ extractedSource: local, jobId: null }); - void warnIfUnplayable(local, outputDir); } enterStage("check"); try { @@ -928,22 +926,6 @@ async function prepareThenStart( } } -/** An archive can't be looked inside before it is unpacked, so the firmware note a checked game - * gets under ② comes now: a PS5 game that would install as a package but not play here. */ -async function warnIfUnplayable(local: string, outputDir: string | undefined) { - const p = running(); - if (!p || (p.mode !== "convert" && p.mode !== "convert-install")) return; - const seen = await fpkg.inspect(local, outputDir).catch(() => null); - const fw = seen && ps5FakeGameUnplayableFirmware(useConnectionStore.getState().ps5Kernel, seen.content_id); - if (fw) { - const lang = useLangStore.getState().lang; - pushNotification("warning", translate(lang, "fpkg.unpacked_unplayable_title", undefined), { - body: translate(lang, "fpkg.unpacked_unplayable", { fw }), - link: "/workshop", - }); - } -} - /** Copy a server source into the output folder; false (the run already failed) if it didn't. */ async function copyFromServer(source: string, outputDir: string | undefined): Promise { let local: string; diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index 123182a86..6cee6130b 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -3182,11 +3182,7 @@ "eta_h_min": "99422830 i3ZohyogvmUIlMOmUIhyquLyrwPmUIBpAFbUGcYmUICKmfi304W3Ip-x35v1", "eta_min": "913185ba yCJp5Xhs0kTGU-tkTGFCRHk1XwWkTGuJ7S5okTGkTGH8F804rGjfurisqN_L", "eta_sec": "2e304898 dsBbjAzVpjm3sPKjm3kD3EXXUr3jm3RnnMgMjm3jm3_6XV13-BCvRHRnnRnn", - "fakegame.fw.body_v3": "9accb442 ePdWD74ZJ7H1bt2B0peynL09hcVkzu5HbzR4nG7stpIJUlfST0LgndG2pBYV", "fakegame.fw.launch_kstuff": "6d7d6fc7 3aaqNXAUK1fEEPYvcotOFgXDbfO8m4z2gKNkYGxrMKA-Kl90AL3dj20lXPlb", - "fakegame.fw.launch_v3": "bee6f22a hx-ailtflUgs7WbWBsKqR7hoPotVmIMT8lY9bLA__RUUucDHX6by9-wGXGOS", - "fakegame.fw.more": "5d8a995a EqE7Y_DM7_lUEw53ehwGWOTgXo0d2KbJiZB2tLOAsfATMXi9QnLP2R7iFsTl", - "fakegame.fw.title_v2": "bf62ad5a h22Wlmp3gW-asxgobZf_lIOPmC3E_YzLFpcKgnpTGI6XDM2BT4NREsmu3h50", "fakelibs_action_failed": "57b25b95 qk7dLA37_hGtDBxvlLLrMZ0lLS6nxzzhTE5egUaoXoWlomzvdMYx-0G2JG2J", "fakelibs_empty": "dbb9e181 TCkrfnCC_LnUFZOZ8jb48c3v2emCYEcUI_wtU4lYItmHRG4E2oX_KW8BLgW2", "fakelibs_import_action": "6d4e30ee HZOVnaCD4f9fVdekSxtm3-ukManJti-C_zH8xBWaPSD7UTTPSP_MbGKddcIB", @@ -3472,8 +3468,6 @@ "fpkg.make.ps4_pkg_body": "f070e4f9 Orx3tKagukEgn-g-_j_OXtTfwFtFLoivTfdjRWNKw9mSHXv0Bv35PkiBqxIn", "fpkg.make.ps4_pkg_title": "7a99e310 _GfKucG0m66tLLNWSYgHwYF1GWAesZFJU2qXZ-mtDUYjZxwGmPjOmfKUWKUW", "fpkg.make.recommended": "d70604e8 z68QjxKZdX6cQTgtGuuEesjgDOIEPFs80WJGg0iX6ci3askAtf-BLrFFLBC1", - "fpkg.make.recommended_fw": "6f1113fa buztW_7A1WAvDTWZFjgZhmOsyl9mF5_AuSTcDQppSGj94vSYbloUgGlWqYRt", - "fpkg.make.why_image": "e7b73dbe YCEjEelQyVq1ylg_icIilLqoX5CfrrUO9xwD7SSTqmihE0cupPJQVu7AlXsi", "fpkg.make.why_kraken": "dc924c78 Y_Yvg70hK7vd9Y7puZcjQ7gFX8yjPHec84Xhlh_7L8ozIawEjkZhVRyBKA2q", "fpkg.make.why_pkg": "65090146 LtNd3K-2kcapBlm32kJjHVZVzcN64bZrPGcZ7_zqYvs1Y-msXnX4ppmjf-4C", "fpkg.merge.browse": "3227aa96 XJJOHXB1UgFLA-IjuJIOToeQUIbmCjrQhxTbqmBbnevTpekSRtMJy7qMgtPW", @@ -3560,8 +3554,6 @@ "fpkg.unpack_lost": "a9bd1e41 3Geme-Vsah3bDShxa7fucYTSULJ21AZe9Dv12j6Drt3o8Jn_zUSscyEViNAO", "fpkg.unpack_packs": "1d695e78 ggudtOiDZos4sgc-DkDxHu7l44kTCKodI-T4oac6i7VISyaRXISq5C6qIPot", "fpkg.unpack_packs_body": "c32fb69a dwomeXyab5QBXs1k_XX3dXSUQ-IIMNde4q71rHXWKvA9r7jm8Rxm89Ws_vLH", - "fpkg.unpacked_unplayable": "fc73d63c zxvrhN_M0aTztLf-SvGUiEhDlCkcGCcdFqFE082jYPfuFw5wp3HYxjKTp5I5", - "fpkg.unpacked_unplayable_title": "616c7e37 fVD3yxKO0IEqxXj0ZVNgLDJFQQPYjlGO2DjA9bQ-uRWqLdqzE4Me0BM6qfka", "fpkg.uploadImage": "f676f9d4 WFDNV4H_xvxXzi5Gej4VJUy0kP4mHNfIvkszyRxnMkcBPWazCXksOt7wC0WC", "fpkg.uploadImageDelete": "b47424f4 0av1E-Kh5AEzWPCRWwhxeNQs-sd_-u-q_idlLkaGJ1fDQLyhPyT9GatlVqce", "fpkg.uploadInstall": "c980e84c t_vdM8ZH0I0Rn6c7SxuxwAMInzDUC2QW8LPIMCWyaPqj89v4aasKeEEPr8P_", From 63003e11c8373226bf2d7834366f34c6d9d4710e Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:32:16 -0800 Subject: [PATCH 02/25] Files: a phone held sideways keeps the phone row layout (#931) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A phone in landscape is wider than `sm`, so Files rows got the desktop layout: every action as an inline button and the file name squeezed to nothing. New Tailwind variants in index.css, `phone:` (below `sm`, or a coarse pointer with a viewport at most 520px tall, the same test as PHONE_LANDSCAPE_QUERY) and its exact complement `roomy:`, now drive the row's name/meta block, the inline action buttons and the ⋮ trigger, so a sideways phone wraps the name (up to 3 lines) with tag and size below and keeps the actions behind ⋮. Desktop (fine pointer) is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/e2e/files-phone-long-names.spec.ts | 70 ++++++++++++++++++- client/src/index.css | 17 +++++ .../screens/FileSystem/RowActions.test.tsx | 6 +- client/src/screens/FileSystem/RowActions.tsx | 15 ++-- client/src/screens/FileSystem/index.tsx | 13 ++-- 5 files changed, 102 insertions(+), 19 deletions(-) diff --git a/client/e2e/files-phone-long-names.spec.ts b/client/e2e/files-phone-long-names.spec.ts index 4c259fcfc..2c154e867 100644 --- a/client/e2e/files-phone-long-names.spec.ts +++ b/client/e2e/files-phone-long-names.spec.ts @@ -2,13 +2,17 @@ import { expect, test, type Page, type Route } from "@playwright/test"; // #923: on a phone, long file names were cut off after a few characters because the tag, size and // buttons share the name's line. There the name now wraps and the tag and size sit below it; wider -// windows keep one line per row. +// windows keep one line per row. #931: a phone held sideways is wider than `sm`, but it keeps the +// phone layout too (wrapped name, size below, actions behind ⋮), not the desktop row of buttons. const HOST = "192.168.0.5"; const LONG = "Dead.or.Alive.5.Last.Round.CUSA01778.v1.19.All.DLC.Backport.Fixed.pkg"; const FILES = [LONG, "b-second.bin"]; +// Too long for one line even across a phone held sideways. +const HUGE = + "Marvels.Spider-Man.2.Digital.Deluxe.Edition.PPSA03016.v1.004.000.All.DLC.Backport.Fixed.By.Somebody.With.A.Very.Long.Release.Group.Name.exfat"; -async function openFiles(page: Page) { +async function openFiles(page: Page, files: string[] = FILES) { await page.addInitScript((files) => { const w = window as unknown as Record; const calls: string[] = []; @@ -38,7 +42,7 @@ async function openFiles(page: Page) { plugins: {}, }; w.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; - }, FILES); + }, files); await page.addInitScript((host) => { window.localStorage.setItem("ps5upload.host", host); }, HOST); @@ -80,6 +84,61 @@ test.describe("phone width", () => { }); }); +async function expectPhoneRow(page: Page, name: ReturnType) { + const fits = await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1); + expect(fits).toBe(true); + const nameBox = await name.boundingBox(); + const meta = name.locator("xpath=following-sibling::div[1]"); + const metaBox = await meta.boundingBox(); + if (!nameBox || !metaBox) throw new Error("no box"); + expect(nameBox.height).toBeGreaterThan(24); + expect(metaBox.y).toBeGreaterThanOrEqual(nameBox.y + nameBox.height - 1); + await expect(meta).toContainText("1000 B"); + // No inline action buttons in this row: only the ⋮, which holds them all. + const row = name.locator("xpath=ancestor::li[1]"); + await expect(row.getByTestId("fs-row-actions")).toBeHidden(); + const visibleButtons = await row + .locator("button:visible") + .evaluateAll((els) => els.map((el) => el.getAttribute("aria-label") ?? el.getAttribute("title") ?? "")); + expect(visibleButtons).toEqual([LONG, `Actions for ${LONG}`]); + const more = row.getByRole("button", { name: `Actions for ${LONG}` }); + await more.click(); + const menu = page.getByTestId("fs-row-menu"); + await expect(menu.getByRole("menuitem", { name: "Rename", exact: true })).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Delete", exact: true })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(menu).toHaveCount(0); +} + +for (const viewport of [ + { width: 915, height: 412 }, + { width: 844, height: 390 }, +]) { + test.describe(`phone held sideways ${viewport.width}x${viewport.height}`, () => { + test.use({ viewport, hasTouch: true, isMobile: true }); + + test("keeps the phone row: the name wraps, size below, actions behind ⋮ (#931)", async ({ page }) => { + const name = await openFiles(page, [...FILES, HUGE]); + expect(await page.evaluate(() => matchMedia("(pointer: coarse)").matches)).toBe(true); + await expectPhoneRow(page, name); + // A name too long for one line really wraps (the 44 px touch height alone is not proof). + const huge = page.getByRole("main").getByRole("button", { name: HUGE, exact: true }); + const lines = await huge.evaluate((el) => { + const style = getComputedStyle(el); + return { + lines: el.getBoundingClientRect().height / parseFloat(style.lineHeight), + fits: el.scrollWidth <= el.clientWidth + 1, + whiteSpace: style.whiteSpace, + }; + }); + expect(lines.fits).toBe(true); + expect(lines.whiteSpace).toBe("normal"); + expect(lines.lines).toBeGreaterThanOrEqual(1.9); + if (process.env.FS_SHOT) await page.screenshot({ path: process.env.FS_SHOT }); + }); + }); +} + test.describe("desktop width", () => { test.use({ viewport: { width: 1280, height: 800 } }); @@ -91,5 +150,10 @@ test.describe("desktop width", () => { if (!nameBox || !sizeBox) throw new Error("no box"); expect(nameBox.height).toBeLessThan(28); expect(Math.abs(sizeBox.y + sizeBox.height / 2 - (nameBox.y + nameBox.height / 2))).toBeLessThan(6); + // The actions stay buttons on the row, and there is no ⋮. + const row = name.locator("xpath=ancestor::li[1]"); + await expect(row.getByTestId("fs-row-actions")).toBeVisible(); + await expect(row.getByRole("button", { name: "Rename", exact: true })).toBeVisible(); + await expect(row.getByTestId("fs-row-more")).toBeHidden(); }); }); diff --git a/client/src/index.css b/client/src/index.css index 4fca633a1..d718a6ed1 100644 --- a/client/src/index.css +++ b/client/src/index.css @@ -1,5 +1,22 @@ @import "tailwindcss"; +/* `phone:` — the phone layout: narrower than `sm`, or a touch screen held sideways (about + * 390-430 px tall; same height test as PHONE_LANDSCAPE_QUERY in screens/Play/immersive.ts). + * `roomy:` is exactly the rest. A sideways phone is wider than `sm`, so `sm:` / `max-sm:` alone + * gave it the desktop row with every action as a button and no room for the name (#931). */ +@custom-variant phone { + @media not all and (min-width: 40rem), (pointer: coarse) and (max-height: 520px) { + @slot; + } +} +@custom-variant roomy { + @media (min-width: 40rem) { + @media not all and (pointer: coarse) and (max-height: 520px) { + @slot; + } + } +} + /* * ─── ps5upload design system — "Sense" ─────────────────────────────────── * diff --git a/client/src/screens/FileSystem/RowActions.test.tsx b/client/src/screens/FileSystem/RowActions.test.tsx index 10b07d258..092a6e3d1 100644 --- a/client/src/screens/FileSystem/RowActions.test.tsx +++ b/client/src/screens/FileSystem/RowActions.test.tsx @@ -103,13 +103,13 @@ describe("Files row: the phone ⋮ menu and the desktop buttons", () => { }); }); - it("desktop buttons hide below sm and the ⋮ shows only there", () => { + it("desktop buttons hide in the phone layout (narrow or sideways) and the ⋮ shows only there (#931)", () => { const desktop = renderToStaticMarkup(); - expect(desktop).toMatch(/class="[^"]*\bhidden\b[^"]*\bsm:flex\b/); + expect(desktop).toMatch(/class="[^"]*\bhidden\b[^"]*\broomy:flex\b/); const trigger = renderToStaticMarkup( {}} />, ); - expect(trigger).toContain("sm:hidden"); + expect(trigger).toContain("roomy:hidden"); expect(trigger).toContain('aria-haspopup="menu"'); expect(trigger).toContain('aria-expanded="false"'); expect(trigger).toContain('aria-label="Actions for a.pkg"'); diff --git a/client/src/screens/FileSystem/RowActions.tsx b/client/src/screens/FileSystem/RowActions.tsx index a19849f19..f2d0dfc5a 100644 --- a/client/src/screens/FileSystem/RowActions.tsx +++ b/client/src/screens/FileSystem/RowActions.tsx @@ -39,7 +39,7 @@ const GAME_FILE = /\.(pkg|exfat|ffpkg|ffpfs|ffpfsc)$/i; type IconType = ComponentType<{ size?: number; className?: string }>; /** One action of a Files row. The desktop layout draws it as an icon button; - * below `sm` (a phone) the same list sits behind the row's ⋮ menu, in the + * in the phone layout (below `sm`, or a phone held sideways) the same list sits behind the row's ⋮ menu, in the * same order, so both run the very same handler. */ export interface RowAction { id: string; @@ -338,7 +338,7 @@ export function buildRowActions(e: RowEntry, ctx: RowActionsContext): RowAction[ return actions; } -/** A row's desktop action buttons (hidden below `sm`). */ +/** A row's desktop action buttons (hidden in the phone layout). */ export function RowActionButtons({ entry, ctx, @@ -372,13 +372,14 @@ export function RowActionsMenu({ ); } -/** The row's actions as the desktop icon buttons. Hidden below `sm`, where - * `RowActionsTrigger` stands in for them. */ +/** The row's actions as the desktop icon buttons. Hidden in the phone layout + * (below `sm`, or a phone held sideways: the `phone:` variant in index.css), + * where `RowActionsTrigger` stands in for them. */ export function RowActionButtonList({ actions }: { actions: RowAction[] }) { return (
{actions.filter((a) => !a.menuOnly).map((a) => ( diff --git a/client/src/screens/FileSystem/index.tsx b/client/src/screens/FileSystem/index.tsx index 2432dd596..cb20e13bd 100644 --- a/client/src/screens/FileSystem/index.tsx +++ b/client/src/screens/FileSystem/index.tsx @@ -4560,7 +4560,7 @@ export default function FileSystemScreen() { className="input input-sm flex-1" /> ) : ( -
+
-
+
{(() => { const tag = gameFormatTag(e.name, isDir); if (!tag) return null; @@ -4588,7 +4589,7 @@ export default function FileSystemScreen() { className={ "shrink-0 rounded border border-[var(--glass-edge)] px-1 text-[10px] leading-4 font-medium text-[var(--color-muted)] sm:text-[11px] " + // A folder already shows its icon: the word only where there is room. - (tag === "folder" ? "hidden sm:inline" : "") + (tag === "folder" ? "hidden roomy:inline" : "") } > {gameFormatLabel(tag, tr("fs_tag_folder", undefined, "Folder"))} @@ -4599,7 +4600,7 @@ export default function FileSystemScreen() { className={ "shrink-0 text-xs text-[var(--color-muted)] tabular-nums " + // A folder's dash would be a line of its own on a phone. - (isDir ? "max-sm:hidden" : "") + (isDir ? "phone:hidden" : "") } > {isDir ? "—" : formatBytes(e.size)} From 4ccaa643c8ae80eb3b2cb90b9d2d3fb660c92045 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:32:58 -0800 Subject: [PATCH 03/25] verify-release --promote: refuse a version older than the latest `gh release edit --latest` moves GitHub's latest pointer onto any release, an older one included. The stable updater manifest, the iPhone source, the site and docker-engine's promote job all follow that pointer (the promote job's never-backwards check compares against it, so it would move :latest back too). Promoting an old pre-release after a newer release is out now stops with the command that publishes it without moving latest. A failed lookup (not a 404) stops instead of guessing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- scripts/release/verify-release.sh | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/scripts/release/verify-release.sh b/scripts/release/verify-release.sh index 2ce977300..7c39d9def 100755 --- a/scripts/release/verify-release.sh +++ b/scripts/release/verify-release.sh @@ -14,7 +14,7 @@ # continue-on-error) and only warn here. # # --promote runs `gh release edit vX.Y.Z --prerelease=false --latest` once every check -# passes. That also fires docker-engine.yml's `promote` job (:latest and :), and it +# passes, and refuses a version older than the current latest release. That also fires docker-engine.yml's `promote` job (:latest and :), and it # redeploys the website (its release snapshot and iPhone source list promoted releases only). # Promote only after the release has been tried on real hardware. @@ -110,6 +110,30 @@ fi (( warn )) || echo "verify-release: complete" if (( promote )); then + # Never backwards. `--latest` moves GitHub's "latest" pointer even onto an older version, and + # everything stable follows that pointer: the desktop updater (releases/latest/download/ + # latest.json), the iPhone source, the website, and docker-engine.yml's promote job, whose + # own never-backwards check compares against that same pointer and so would move :latest + # back too. Promoting an old pre-release after a newer one is out is a mistake to stop here. + latest_err="$(mktemp)" + if latest_tag="$(gh api "repos/{owner}/{repo}/releases/latest" --jq .tag_name 2>"$latest_err")"; then + latest="${latest_tag#v}" + if [[ "$latest" != "$version" ]] \ + && [[ "$(printf '%s\n%s\n' "$version" "$latest" | sort -V | head -n 1)" == "$version" ]]; then + rm -f "$latest_err" + echo "verify-release: NOT promoted: $tag is older than the latest release, $latest_tag." >&2 + echo " Promoting it would move the stable channel (updater, iPhone source, site, :latest) back." >&2 + echo " To publish it without moving latest: gh release edit $tag --prerelease=false --latest=false" >&2 + exit 1 + fi + elif ! grep -q 'HTTP 404' "$latest_err"; then + # No answer is not "there is no latest": do not guess. + cat "$latest_err" >&2 + rm -f "$latest_err" + echo "verify-release: NOT promoted: could not read the latest release (above)" >&2 + exit 1 + fi + rm -f "$latest_err" gh release edit "$tag" --prerelease=false --latest echo "promoted $tag to the latest release" # The website's release snapshot and the iPhone (AltStore) source list promoted releases only: From c6377ba20a7e1427074a5833940731423118a122 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:33:42 -0800 Subject: [PATCH 04/25] fast-release: watch the release-tag run this dispatch started After dispatching release-tag the script slept 8 s and watched the newest listed run. When GitHub had not registered the new run yet, that was the previous release's finished green run: "tagged vX.Y.Z" was printed even when the new run then failed (CHANGELOG check, ci verdict), and the script only failed five minutes later with "no publish run appeared". It now takes the run URL gh prints, else the first run newer than the newest one before the dispatch (run ids only grow), and fails if none appears. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- scripts/release/fast-release.sh | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/scripts/release/fast-release.sh b/scripts/release/fast-release.sh index 28b088194..c1662d65c 100755 --- a/scripts/release/fast-release.sh +++ b/scripts/release/fast-release.sh @@ -206,9 +206,23 @@ fi echo "PR #$PR merged" step "5. Tag v$V (pre-release) and publish" -gh workflow run release-tag.yml --ref main -f version="$V" -f prerelease=true -f force="$FORCE" -sleep 8 -TAG_RUN="$(gh run list --workflow release-tag.yml --limit 1 --json databaseId --jq '.[0].databaseId')" +# This dispatch's own run, never the newest run that happens to be listed: a run not registered +# yet left the previous release's (finished, green) run as the newest, and "tagged" was printed +# for a tag that a failing release-tag never made. Run ids only grow, so a run newer than the +# newest before the dispatch is this one; gh also prints the new run's URL when GitHub gives it. +BEFORE="$(gh run list --workflow release-tag.yml --limit 1 --json databaseId --jq '.[0].databaseId // 0')" +[[ "$BEFORE" =~ ^[0-9]+$ ]] || fail "could not read the release-tag runs" +DISPATCH="$(gh workflow run release-tag.yml --ref main -f version="$V" -f prerelease=true -f force="$FORCE" 2>&1)" \ + || fail "could not dispatch release-tag: $DISPATCH" +TAG_RUN="$(grep -oE '/actions/runs/[0-9]+' <<<"$DISPATCH" | head -n 1 | sed 's#.*/##' || true)" +for _ in $(seq 1 30); do + [ -n "$TAG_RUN" ] && break + sleep 5 + TAG_RUN="$(gh run list --workflow release-tag.yml --limit 5 --json databaseId \ + --jq "[.[] | select(.databaseId > $BEFORE)] | min_by(.databaseId) | .databaseId // empty" || true)" +done +[ -n "$TAG_RUN" ] || fail "no release-tag run appeared for the dispatch: gh run list --workflow release-tag.yml" +echo "release-tag run $TAG_RUN" gh run watch "$TAG_RUN" --exit-status --interval 15 >/dev/null || fail "release-tag failed: gh run view $TAG_RUN --log-failed" echo "tagged v$V" PUB="" From a7c82d626e0f1908a7d6a7277b05ea1c03a1ec2f Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:36:38 -0800 Subject: [PATCH 05/25] publish: never make an older version the latest release A dispatch with prerelease=false always passed make_latest=true, so a hand dispatch for an older tag (rebuilding an old pre-release) would move GitHub's latest back, and with it the stable updater manifest, the iPhone source and the site. release-tag.yml only asks this for a version newer than every tag, so its path is unchanged. Now an older version is published as a full release with latest left where it is (and a warning); a failed lookup of the latest release (not a 404) stops the job instead of guessing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .github/workflows/publish.yml | 49 ++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5bee242c3..f25614d09 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1449,6 +1449,53 @@ jobs: with: subject-path: release/* + # prerelease=false makes this release GitHub's "latest", which the stable updater + # (releases/latest/download/latest.json), the iPhone source and the site all follow. + # release-tag.yml only ever asks that for a version newer than every tag, but a hand + # dispatch for an older tag would move all of them back: that one is published as a full + # release and latest stays where it is. A lookup that fails is not a "no". + - name: Never move latest to an older version + id: latest + env: + GH_TOKEN: ${{ github.token }} + FULL_RELEASE: ${{ github.event.inputs.prerelease == 'false' }} + TAG_VERSION: ${{ steps.tag.outputs.version }} + run: | + set -euo pipefail + if [ "$FULL_RELEASE" != true ]; then + echo "make_latest=legacy" >> "$GITHUB_OUTPUT" + exit 0 + fi + err="$RUNNER_TEMP/latest-lookup.err" + latest_tag="" + found=0 + for attempt in 1 2 3; do + if latest_tag="$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name 2>"$err")"; then + found=1 + break + fi + if grep -q 'HTTP 404' "$err"; then + latest_tag="" + found=1 + break + fi + echo "latest release lookup failed (attempt $attempt):" >&2 + cat "$err" >&2 + sleep $((attempt * 10)) + done + if [ "$found" -ne 1 ]; then + echo "::error::could not read the latest release (GitHub API error above); not publishing over it." + exit 1 + fi + latest="${latest_tag#v}" + if [ -n "$latest" ] && [ "$latest" != "$TAG_VERSION" ] \ + && [ "$(printf '%s\n%s\n' "$TAG_VERSION" "$latest" | sort -V | head -n 1)" = "$TAG_VERSION" ]; then + echo "::warning::$TAG_VERSION is older than the latest release ($latest_tag): published as a full release, latest stays on $latest_tag" + echo "make_latest=false" >> "$GITHUB_OUTPUT" + else + echo "make_latest=true" >> "$GITHUB_OUTPUT" + fi + - name: Create GitHub release uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 with: @@ -1463,7 +1510,7 @@ jobs: # having run it on a console. Only a dispatch that says # prerelease=false (release-tag.yml, when asked) publishes it as the latest. prerelease: ${{ github.event.inputs.prerelease != 'false' }} - make_latest: ${{ github.event.inputs.prerelease == 'false' && 'true' || 'legacy' }} + make_latest: ${{ steps.latest.outputs.make_latest }} files: release/* # The site's release snapshot and iPhone source (pages.yml) are rebuilt once the release is out. From b26cfd782e7227c74af50f95bcdf8de71e7821ce Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:37:20 -0800 Subject: [PATCH 06/25] security scan: drop the picomatch allowance nothing needs any more npm audit no longer reports GHSA-fc5q-39xc-vjpf (the lock has picomatch 4.0.7), so the allowance matched nothing. It still would have failed the security scan on its expiry, 2026-12-17 (npm-audit-filter.mjs fails on any expired entry), and until then would have let the advisory back in unnoticed. Both npm audits still pass with an empty list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- scripts/npm-audit-allow.json | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/scripts/npm-audit-allow.json b/scripts/npm-audit-allow.json index 3b20f71b6..aac7c02f7 100644 --- a/scripts/npm-audit-allow.json +++ b/scripts/npm-audit-allow.json @@ -1,11 +1,4 @@ { "_doc": "npm advisories the security scan lets through: only ones with NO fixed version yet, only in development tools (never in what the app ships: `npm audit --omit=dev` must stay clean), each with a reason and an expiry. Past `until` the scan fails again so it gets looked at. scripts/npm-audit-filter.mjs reads this.", - "allow": [ - { - "id": "GHSA-fc5q-39xc-vjpf", - "package": "picomatch", - "reason": "ReDoS on crafted extglob patterns; every picomatch version, no fix released. Only via vite/vitest/eslint (dev tools, our own glob patterns); the shipped app has no picomatch.", - "until": "2026-12-17" - } - ] + "allow": [] } From 287eb347ea7192330a199635e7705e1bb75741ae Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:35:47 -0800 Subject: [PATCH 07/25] SDK Changer: a short module param is not patched past the file's end elf_find_param_sites took a PT_SCE_MODULE_PARAM of 0x14 bytes as a site (it checked only the PS4 field at 0x10), while the patcher reads and writes the SDK pair (0x10 and 0x14) of every site. A module of 0x14..0x17 bytes at the end of a game file was read 4 bytes past the file's mapping (a fault in the helper when the file ends on a page) and then written past its end, growing the file. A site must now hold both fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/include/elf_param.h | 8 +++++-- payload/tests/elf_param_selftest.c | 20 +++++++++++++++++ payload/tests/sdk_changer_file_selftest.c | 26 +++++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/payload/include/elf_param.h b/payload/include/elf_param.h index 8fb4c4c4a..174794472 100644 --- a/payload/include/elf_param.h +++ b/payload/include/elf_param.h @@ -248,8 +248,12 @@ static inline int elf_find_param_sites(const unsigned char *buf, size_t len, uint32_t sdk_off = (p_type == PT_SCE_PROCPARAM) ? SCE_PARAM_PS5_SDK_OFFSET : SCE_PARAM_PS4_SDK_OFFSET; - /* The segment must actually hold the struct we expect. */ - if (p_filesz < sdk_off + 4) continue; + /* The segment must actually hold the struct we expect: BOTH SDK fields, whatever the type, + * because the patcher reads and writes the pair (PS4 at 0x10, PS5 at 0x14) in every site. A + * module param of 0x14..0x17 bytes at the end of the file passed `sdk_off + 4` and was then + * read 4 bytes past the file's mapping (a crash when the file ends on a page) and written + * past its end (the file grew). */ + if (p_filesz < SCE_PARAM_PS5_SDK_OFFSET + 4) continue; int64_t at = elf_self_map_offset(buf, len, (uint64_t)base, elf, phoff, phentsize, phnum, i, p_offset, p_filesz); if (at < 0) continue; diff --git a/payload/tests/elf_param_selftest.c b/payload/tests/elf_param_selftest.c index 88b152802..593d557a9 100644 --- a/payload/tests/elf_param_selftest.c +++ b/payload/tests/elf_param_selftest.c @@ -415,6 +415,26 @@ int main(void) { CHECK(n == 2); } + /* A module param too short for both SDK fields (0x14..0x17 bytes) is not a site: the patcher + * reads and writes the PS5 field at 0x14 of every site, which here lies past the segment and, + * at the end of the file, past the file. */ + for (uint64_t short_sz = 0x14; short_sz < 0x18; short_sz++) { + elf_reset(1); + elf_put_segment(0, PT_SCE_MODULE_PARAM, 0x200, short_sz, + SCE_MODULE_PARAM_MAGIC, SCE_PARAM_PS4_SDK_OFFSET, 0x10000040u); + CHECK(g_len == 0x200 + short_sz); /* the segment ends the file */ + n = elf_find_param_sites(g_elf, g_len, sites, 8, &st); + CHECK(n == 0); + } + /* 0x18 holds both: still a site. */ + { + elf_reset(1); + elf_put_segment(0, PT_SCE_MODULE_PARAM, 0x200, 0x18, + SCE_MODULE_PARAM_MAGIC, SCE_PARAM_PS4_SDK_OFFSET, 0x10000040u); + n = elf_find_param_sites(g_elf, g_len, sites, 8, &st); + CHECK(n == 1); + } + printf("elf_param_selftest: %s\n", failures == 0 ? "ALL PASS" : "FAILED"); return failures == 0 ? 0 : 1; } diff --git a/payload/tests/sdk_changer_file_selftest.c b/payload/tests/sdk_changer_file_selftest.c index 728f09e1a..6d9032512 100644 --- a/payload/tests/sdk_changer_file_selftest.c +++ b/payload/tests/sdk_changer_file_selftest.c @@ -510,6 +510,32 @@ int main(void) { CHECK(saw_cut && saw_cut_with_titles); } + /* A module param of 0x14 bytes ending the file: the pair patch must neither read nor write + * past it. It used to write the PS5 field at EOF, growing the file by 4 bytes (and on a file + * that ends on a page, the read before it faulted). */ + { + char short_path[2048]; + snprintf(short_path, sizeof(short_path), "%s/short_module.prx", root); + unsigned char m[0x214]; + memset(m, 0, sizeof(m)); + memcpy(m, "\x7f" "ELF", 4); + m[4] = 2; + m[5] = 1; + wr64(m, 0x20, 0x40); + wr16(m, 0x36, 0x38); + wr16(m, 0x38, 1); + wr32(m, 0x40, PT_SCE_MODULE_PARAM); + wr64(m, 0x48, 0x200); + wr64(m, 0x60, 0x14); + wr32(m, 0x200 + SCE_PARAM_MAGIC_OFFSET, SCE_MODULE_PARAM_MAGIC); + wr32(m, 0x200 + SCE_PARAM_PS4_SDK_OFFSET, 0x09040001u); + CHECK(write_bytes(short_path, m, sizeof(m)) == 0); + CHECK(patch_binary_sdk(short_path, 0x04000031u) == 0); + struct stat sst; + CHECK(stat(short_path, &sst) == 0 && (size_t)sst.st_size == sizeof(m)); + CHECK(read_u32_at(short_path, 0x200 + SCE_PARAM_PS4_SDK_OFFSET) == 0x09040001u); + } + rm_tree(root); printf("sdk_changer_file_selftest: %s\n", failures == 0 ? "ALL PASS" : "FAILED"); From 55532d90b0b62a4e2d76b9d8dac826854f7507d2 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:37:38 -0800 Subject: [PATCH 08/25] Cheats: handle 0 is the game's module only when it is its executable phys_write_allowed took any module with dynlib handle 0 for the game's own and let a physical write go there. #920 showed handle 0 of a PS4 game's process is another module (336 KiB at 0x6988c000, not the eboot at 0x400000). A game patch XML with no AppElf took that module as its base, has no original bytes to compare, and so wrote into it; a physical write lands in every process mapping the page. Handle 0 is now trusted when its path ends in eboot.bin (or cannot be read, as before); modules under /app0 stay allowed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/include/cheats_plan.h | 7 +++++++ payload/src/cheats.c | 2 +- payload/src/cheats_plan.c | 11 +++++++++++ payload/tests/cheats_plan_selftest.c | 16 ++++++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/payload/include/cheats_plan.h b/payload/include/cheats_plan.h index d7714a897..fbb45e3d3 100644 --- a/payload/include/cheats_plan.h +++ b/payload/include/cheats_plan.h @@ -89,4 +89,11 @@ int cheat_plan_apply(cheat_loc_t *locs, int n, int turn_on, * canonical user limit, and not wrapping. */ int cheat_addr_ok(intptr_t addr, int len); +/* Whether a loaded module of the game's process may take a physical write: one of the game's + * own. A module loaded from its /app0, or dynlib handle 0 when that is its executable (a path + * ending in eboot.bin, or a path that could not be read, as handle 0 always was). Handle 0 by + * number alone is not enough: in a PS4 game's process (#920) it is another module, and a + * physical write there lands in every process that maps the page. */ +int cheat_module_is_game(uint64_t handle, const char *path); + #endif /* PS5UPLOAD_CHEATS_PLAN_H */ diff --git a/payload/src/cheats.c b/payload/src/cheats.c index 0c5df09eb..853f610dc 100644 --- a/payload/src/cheats.c +++ b/payload/src/cheats.c @@ -456,7 +456,7 @@ static int phys_write_allowed(pid_t pid, intptr_t addr, size_t len, char *why, s path[0] = '\0'; if (h.path) (void)kernel_copyout(h.path, path, sizeof(path) - 1); path[sizeof(path) - 1] = '\0'; - int game_module = (h.handle == 0) || strstr(path, "/app0/") != NULL; + int game_module = cheat_module_is_game(h.handle, path); if (!game_module) { if (why) snprintf(why, why_cap, "inside %s", path[0] ? path : "a system module"); verdict = 0; diff --git a/payload/src/cheats_plan.c b/payload/src/cheats_plan.c index 98109ef30..49d3acd78 100644 --- a/payload/src/cheats_plan.c +++ b/payload/src/cheats_plan.c @@ -6,6 +6,7 @@ #include #include #include +#include static int hex_val(char c) { if (c >= '0' && c <= '9') return c - '0'; @@ -95,6 +96,16 @@ int cheat_addr_ok(intptr_t addr, int len) { return a >= 0x10000ULL && end > a && end <= 0x800000000000ULL; } +int cheat_module_is_game(uint64_t handle, const char *path) { + if (!path) path = ""; + if (strstr(path, "/app0/") != NULL) return 1; + if (handle != 0) return 0; + if (!path[0]) return 1; + const char *leaf = strrchr(path, '/'); + leaf = leaf ? leaf + 1 : path; + return strcasecmp(leaf, "eboot.bin") == 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 86717c99a..1639a0385 100644 --- a/payload/tests/cheats_plan_selftest.c +++ b/payload/tests/cheats_plan_selftest.c @@ -152,6 +152,21 @@ static void test_order_mc4_zero_cave(void) { CHECK(locs[1].addr + locs[1].len <= 0x6324000); } +static void test_module_is_game(void) { + CHECK(cheat_module_is_game(0, "/app0/eboot.bin")); + CHECK(cheat_module_is_game(0, "/system_ex/app/PPSA01234/eboot.bin")); + CHECK(cheat_module_is_game(0, "/mnt/sandbox/pfsmnt/CUSA00284-app0/EBOOT.BIN")); + CHECK(cheat_module_is_game(0, "")); /* path unreadable: as handle 0 always was */ + CHECK(cheat_module_is_game(0, NULL)); + CHECK(cheat_module_is_game(7, "/app0/sce_module/libgame.prx")); + /* #920: handle 0 of a PS4 game's process is another module; a physical write there is + * shared with every process mapping it. */ + CHECK(!cheat_module_is_game(0, "/system/common/lib/libSceSomething.sprx")); + CHECK(!cheat_module_is_game(0, "/system_ex/common_ex/lib/libc.prx")); + CHECK(!cheat_module_is_game(3, "/system/common/lib/libkernel.sprx")); + CHECK(!cheat_module_is_game(3, "")); +} + static void test_addr_ok(void) { CHECK(cheat_addr_ok(0x1FAD908, 9)); CHECK(!cheat_addr_ok(0, 4)); @@ -368,6 +383,7 @@ int main(void) { test_order_max_resources(); test_order_mc4_zero_cave(); test_addr_ok(); + test_module_is_game(); test_apply_mock(); if (failures) { fprintf(stderr, "cheats_plan_selftest: %d failure(s)\n", failures); From 76358dd3c5613b0fdb5dd04760850b93b414ba18 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:40:05 -0800 Subject: [PATCH 09/25] Cheats: an indented SHN value too long to hold is refused, not cut xml_text cut a // text at its buffer and trimmed the whitespace after. A pretty-printed SHN or MC4 line with an indented value of more than 255 bytes came out shorter than a full buffer, passed resolve_mod_locs' "value too long" check, and both sides parsed to the same shortened length, so a cheat cut short (a code cave without its jump back) was written into the game. The text is now measured without its whitespace (cheats_xml_text, host-tested); one that does not fit fills the buffer, and an offset that does not fit becomes one that does not parse. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/include/cheats_xml_attr.h | 39 ++++++++++++++++++++++++++ payload/src/cheats.c | 39 ++++++-------------------- payload/tests/cheats_reply_selftest.c | 40 +++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 31 deletions(-) diff --git a/payload/include/cheats_xml_attr.h b/payload/include/cheats_xml_attr.h index 0bd727211..d68290d0b 100644 --- a/payload/include/cheats_xml_attr.h +++ b/payload/include/cheats_xml_attr.h @@ -3,7 +3,9 @@ #ifndef PS5UPLOAD_CHEATS_XML_ATTR_H #define PS5UPLOAD_CHEATS_XML_ATTR_H +#include #include +#include #include /* Finds attr="value" in the NUL-terminated `tag` and copies the value (cut at cap). 0 when found. @@ -37,4 +39,41 @@ static inline int cheats_xml_attr(const char *tag, const char *attr, char *out, return -1; } +/* The text of the first text at or after `start`, without the whitespace around it. + * 0 when found; 1 when it was found but does not fit (out then holds its first cap - 1 bytes, a full + * buffer, which the callers' "value too long" check refuses); -1 when there is none. + * + * The whitespace is left out BEFORE the text is measured. It used to be cut at cap - 1 first and + * trimmed after: an indented value (a pretty-printed SHN, "" then a newline and spaces) of + * more than cap - 1 bytes came out shorter than a full buffer, passed the check, and a cheat cut + * short (a code cave without its jump back) was written. */ +static inline int cheats_xml_text(const char *start, const char *tag_name, char *out, size_t cap) { + char open_tag[64], close_tag[64]; + const char *p, *end, *s; + size_t len; + int cut = 0; + if (!start || !tag_name || !out || cap == 0) return -1; + out[0] = '\0'; + snprintf(open_tag, sizeof(open_tag), "<%s", tag_name); + snprintf(close_tag, sizeof(close_tag), "", tag_name); + p = strstr(start, open_tag); + if (!p) return -1; + p += strlen(open_tag); + while (*p && *p != '>') p++; /* skip attrs */ + if (*p == '>') p++; + end = strstr(p, close_tag); + if (!end) return -1; + s = p; + while (s < end && isspace((unsigned char)*s)) s++; + while (end > s && isspace((unsigned char)end[-1])) end--; + len = (size_t)(end - s); + if (len >= cap) { + len = cap - 1; + cut = 1; + } + memcpy(out, s, len); + out[len] = '\0'; + return cut; +} + #endif /* PS5UPLOAD_CHEATS_XML_ATTR_H */ diff --git a/payload/src/cheats.c b/payload/src/cheats.c index 853f610dc..3686774a7 100644 --- a/payload/src/cheats.c +++ b/payload/src/cheats.c @@ -794,35 +794,9 @@ static void xml_open_tag_copy(const char *start, const char *end, char *buf, siz buf[n] = '\0'; } -/* Extract text between .... */ -static int xml_text(const char *start, const char *tag_name, - char *out, size_t cap) { - if (!start || !tag_name || !out || cap == 0) return -1; - out[0] = '\0'; - char open_tag[64]; - char close_tag[64]; - snprintf(open_tag, sizeof(open_tag), "<%s", tag_name); - snprintf(close_tag, sizeof(close_tag), "", tag_name); - - const char *p = strstr(start, open_tag); - if (!p) return -1; - p += strlen(open_tag); - while (*p && *p != '>') p++; /* skip attrs */ - if (*p == '>') p++; - - const char *end = strstr(p, close_tag); - if (!end) return -1; - - size_t len = (size_t)(end - p); - if (len >= cap) len = cap - 1; - memcpy(out, p, len); - out[len] = '\0'; - - /* Trim whitespace */ - while (len > 0 && isspace((unsigned char)out[len-1])) out[--len] = '\0'; - while (isspace((unsigned char)out[0])) memmove(out, out+1, strlen(out)); - - return 0; +/* Extract text between ... (include/cheats_xml_attr.h): 1 when it did not fit. */ +static int xml_text(const char *start, const char *tag_name, char *out, size_t cap) { + return cheats_xml_text(start, tag_name, out, cap); } /* Find next occurrence of section = atoi(sec_str); /* Try child tags (paired form) */ - if (!e->offset_str[0]) - xml_text(cl_full, "Offset", e->offset_str, sizeof(e->offset_str)); + /* An offset too long to hold is not cut into another address: it becomes one that does + * not parse, so the cheat is refused (resolve_mod_locs). */ + if (!e->offset_str[0] && + xml_text(cl_full, "Offset", e->offset_str, sizeof(e->offset_str)) == 1) + snprintf(e->offset_str, sizeof(e->offset_str), "too long"); if (!e->on_str[0]) xml_text(cl_full, "ValueOn", e->on_str, sizeof(e->on_str)); if (!e->off_str[0]) diff --git a/payload/tests/cheats_reply_selftest.c b/payload/tests/cheats_reply_selftest.c index 770b3b906..ede95b7ff 100644 --- a/payload/tests/cheats_reply_selftest.c +++ b/payload/tests/cheats_reply_selftest.c @@ -189,9 +189,49 @@ static void flags_what_was_cut(void) { CHECK(jb.over && strcmp(buf, "0123456789ab") == 0); } +/* A paired-form value in a pretty-printed SHN: the whitespace around it is not part of it, and one + * too long for the buffer is reported cut and fills it (cheats.c then refuses "value too long"). It + * used to be cut first and trimmed after, so a cut value passed for a whole one. */ +static void xml_text_measures_without_whitespace(void) { + char out[256], small[32]; + CHECK(cheats_xml_text("\n 90 90 \n ", "ValueOn", out, + sizeof out) == 0); + CHECK(strcmp(out, "90 90") == 0); + CHECK(cheats_xml_text("0x10", "Offset", small, sizeof small) == 0); + CHECK(strcmp(small, "0x10") == 0); + CHECK(cheats_xml_text("90", "ValueOn", out, sizeof out) == -1); + CHECK(out[0] == '\0'); + CHECK(cheats_xml_text("", "ValueOn", out, sizeof out) == -1); + + /* 20 spaces of indentation, then 300 hex digits. */ + char *xml = malloc(512); + CHECK(xml != NULL); + if (!xml) return; + size_t at = (size_t)snprintf(xml, 512, "\n"); + memset(xml + at, ' ', 20); + at += 20; + memset(xml + at, 'A', 300); + at += 300; + snprintf(xml + at, 512 - at, "\n"); + CHECK(cheats_xml_text(xml, "ValueOn", out, sizeof out) == 1); + CHECK(strlen(out) + 1 == sizeof out); /* full: the caller's "too long" check trips */ + CHECK(out[0] == 'A'); + /* Exactly what fits, indented: whole. */ + at = (size_t)snprintf(xml, 512, "\n"); + memset(xml + at, ' ', 20); + at += 20; + memset(xml + at, 'B', 254); + at += 254; + snprintf(xml + at, 512 - at, "\n"); + CHECK(cheats_xml_text(xml, "ValueOn", out, sizeof out) == 0); + CHECK(strlen(out) == 254 && out[0] == 'B' && out[253] == 'B'); + free(xml); +} + int main(void) { xml_attr_finds_whole_names(); xml_attr_stops_at_the_end(); + xml_text_measures_without_whitespace(); list_ends_whole_at_any_size(); type_is_escaped(); flags_what_was_cut(); From 33eaedffd6025950a3e3f9b527d2a95e52e989be Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:40:43 -0800 Subject: [PATCH 10/25] Install from the console page: no unlink of an uninitialised path when memory runs out op_pkg_install cleared staged[0] and job[0] only after the check that every buffer was allocated. When one of the others failed, the exit path read both uninitialised and could hand the garbage in staged to unlink(). They are cleared as soon as they exist. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/src/webui_pkg.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/payload/src/webui_pkg.c b/payload/src/webui_pkg.c index 3322714bf..4bde7c0d8 100644 --- a/payload/src/webui_pkg.c +++ b/payload/src/webui_pkg.c @@ -606,13 +606,15 @@ static int op_pkg_install(void *arg, ava1_op_ctx_t *c, const uint8_t *args, size size_t at = 0; (void)arg; (void)n; + /* Before the check: `out` reads both, and with another buffer not allocated they were read + * (and `staged` handed to unlink) uninitialised. */ + if (staged) staged[0] = '\0'; + if (job) job[0] = '\0'; if (!src || !norm || !staged || !job) { ava1_op_message(c, "pkg_install_internal"); status = AVA1_ERR_INTERNAL; goto out; } - staged[0] = '\0'; - job[0] = '\0'; if (!fsj_json_str((const char *)args, "path", src, 1024) || !src[0]) { ava1_op_message(c, "pkg_install_missing_path"); status = AVA1_ERR_PROTOCOL; From b5a2e9347c0734a357dee033656b294ebeeb9886 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:41:49 -0800 Subject: [PATCH 11/25] SDK Changer: the folder walks stop 32 levels down walk_and_patch and walk_and_restore recursed with no depth limit. Each level keeps one to three 1 KiB path buffers on the handler's 512 KiB stack and an open folder, and a game folder of 1-character names fits about 500 levels in the 1024-byte path limit: deep enough to overflow the stack and take the helper down. Every other walker in the payload has a cap; these now stop at 32 (a deeper folder counts as an error). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/src/sdk_changer.c | 24 +++++++++++----- payload/tests/sdk_changer_file_selftest.c | 34 +++++++++++++++++++++++ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/payload/src/sdk_changer.c b/payload/src/sdk_changer.c index c590ff07f..89a789dad 100644 --- a/payload/src/sdk_changer.c +++ b/payload/src/sdk_changer.c @@ -34,6 +34,11 @@ #define LEGACY_BACKUP_SUFFIX ".bak" #define SDK_PATH_MAX 1024 #define SDK_COPY_BUF (64u * 1024u) +/* How deep the patch and restore walks go below the game's folder. Each level holds a few KiB of + * path buffers on the handler's 512 KiB stack and an open folder: a folder of 1-character names + * fits about 500 levels in SDK_PATH_MAX, which overflowed that stack. No game is nearly this deep; + * the walk counts a deeper folder as an error and goes no further. */ +#define SDK_WALK_DEPTH_MAX 32 static void json_escape(const char *in, char *out, size_t cap) { @@ -434,7 +439,11 @@ static int patch_libc_prx(const char *game_path) { static void walk_and_patch(const char *dir_path, uint32_t target_sdk, int *patched_count, int *signed_count, - int *error_count) { + int *error_count, int depth) { + if (depth > SDK_WALK_DEPTH_MAX) { + if (error_count) (*error_count)++; + return; + } DIR *dir = opendir(dir_path); if (!dir) return; struct dirent *de; @@ -462,7 +471,7 @@ static void walk_and_patch(const char *dir_path, uint32_t target_sdk, * a working one. */ if (strcmp(de->d_name, "fakelib") == 0) continue; walk_and_patch(full, target_sdk, patched_count, signed_count, - error_count); + error_count, depth + 1); continue; } if (!S_ISREG(st.st_mode)) continue; @@ -494,7 +503,8 @@ static int name_ends_with(const char *name, const char *suffix) { * the files beside them are still as the patch left them: a `.bak` with one of * our own backups next to it is not ours (make_backup() never makes both), and * that has to be read before the second pass renames our own backup away. */ -static void walk_and_restore(const char *dir_path, int *restored_count) { +static void walk_and_restore(const char *dir_path, int *restored_count, int depth) { + if (depth > SDK_WALK_DEPTH_MAX) return; /* the patch never went there either */ for (int pass = 0; pass < 2; pass++) { const int legacy = pass == 0; const char *suffix = legacy ? LEGACY_BACKUP_SUFFIX : BACKUP_SUFFIX; @@ -512,7 +522,7 @@ static void walk_and_restore(const char *dir_path, int *restored_count) { if (lstat(full, &st) != 0) continue; if (S_ISDIR(st.st_mode)) { - if (!legacy) walk_and_restore(full, restored_count); + if (!legacy) walk_and_restore(full, restored_count, depth + 1); continue; } if (!S_ISREG(st.st_mode)) continue; @@ -797,7 +807,7 @@ int sdk_changer_patch(const char *title_id, const char *target_sdk, int game_json_changed = patch_game_params(game_path, target, &errors); int patched = 0; int signed_skipped = 0; - walk_and_patch(game_path, target, &patched, &signed_skipped, &errors); + walk_and_patch(game_path, target, &patched, &signed_skipped, &errors, 0); /* Opt-in only — see sdk_changer.h. */ int libc_sites = patch_libc ? patch_libc_prx(game_path) : 0; @@ -862,7 +872,7 @@ int sdk_changer_restore(const char *title_id, int *restored_count, int count = 0; char game_path[SDK_PATH_MAX] = ""; if (resolve_game_path(title_id, game_path, sizeof(game_path))) { - walk_and_restore(game_path, &count); + walk_and_restore(game_path, &count, 0); } /* Also restore appmeta backups so the list reverts too. */ char meta[SDK_PATH_MAX]; @@ -870,7 +880,7 @@ int sdk_changer_restore(const char *title_id, int *restored_count, struct stat st; if (mn >= 0 && (size_t)mn < sizeof(meta) && stat(meta, &st) == 0 && S_ISDIR(st.st_mode)) { - walk_and_restore(meta, &count); + walk_and_restore(meta, &count, 0); } if (restored_count) *restored_count = count; diff --git a/payload/tests/sdk_changer_file_selftest.c b/payload/tests/sdk_changer_file_selftest.c index 6d9032512..59531de1a 100644 --- a/payload/tests/sdk_changer_file_selftest.c +++ b/payload/tests/sdk_changer_file_selftest.c @@ -536,6 +536,40 @@ int main(void) { CHECK(read_u32_at(short_path, 0x200 + SCE_PARAM_PS4_SDK_OFFSET) == 0x09040001u); } + /* The walks stop SDK_WALK_DEPTH_MAX folders down (each level is a few KiB of the handler's + * stack): an executable below that is counted as an error and left alone, one above is + * patched. */ + { + char deep[2048], elf_at[2048]; + unsigned char e[0x240]; + int depth_patched = 0, depth_signed = 0, depth_errors = 0; + size_t at = (size_t)snprintf(deep, sizeof(deep), "%s/deep", root); + CHECK(mkdir_tree(deep) == 0); + for (int lvl = 0; lvl < SDK_WALK_DEPTH_MAX + 8; lvl++) { + at += (size_t)snprintf(deep + at, sizeof(deep) - at, "/d"); + CHECK(mkdir(deep, 0755) == 0); + if (lvl == 3) { + snprintf(elf_at, sizeof(elf_at), "%s/shallow.elf", deep); + make_patchable_elf(e, sizeof(e), 0x10000000u); + CHECK(write_bytes(elf_at, e, sizeof(e)) == 0); + } + } + char deep_elf[2048]; + snprintf(deep_elf, sizeof(deep_elf), "%s/deep.elf", deep); + make_patchable_elf(e, sizeof(e), 0x10000000u); + CHECK(write_bytes(deep_elf, e, sizeof(e)) == 0); + snprintf(deep, sizeof(deep), "%s/deep", root); + walk_and_patch(deep, 0x04000031u, &depth_patched, &depth_signed, &depth_errors, 0); + CHECK(depth_patched >= 1); + CHECK(depth_errors == 1); + CHECK(read_u32_at(elf_at, 0x200 + SCE_PARAM_PS5_SDK_OFFSET) == 0x04000031u); + CHECK(read_u32_at(deep_elf, 0x200 + SCE_PARAM_PS5_SDK_OFFSET) == 0x10000000u); + int depth_restored = 0; + walk_and_restore(deep, &depth_restored, 0); + CHECK(depth_restored == 1); + CHECK(read_u32_at(elf_at, 0x200 + SCE_PARAM_PS5_SDK_OFFSET) == 0x10000000u); + } + rm_tree(root); printf("sdk_changer_file_selftest: %s\n", failures == 0 ? "ALL PASS" : "FAILED"); From 4bfe09d5359d0c3378954f228f0c9a22a7af8740 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:43:32 -0800 Subject: [PATCH 12/25] Cheats: a game patch that cannot be recorded is not left written An applied XML game patch entry is kept in one of 64 records; turning it off puts back what its record holds. With all 64 in use (or no memory for one), the entry was written anyway and only logged "applied but not recorded": turning it off then found no record, reported it off and left its bytes in the game. A free record is now checked for before anything is written (an earlier game session's records are let go first), and a record that still cannot be made takes the patch out again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/src/cheats.c | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/payload/src/cheats.c b/payload/src/cheats.c index 3686774a7..99dbced4c 100644 --- a/payload/src/cheats.c +++ b/payload/src/cheats.c @@ -1514,6 +1514,18 @@ static void xml_applied_forget(pid_t pid) { if (g_xml_applied[i].rec && g_xml_applied[i].pid == pid) xml_applied_free(&g_xml_applied[i]); } +/* 1 when one more entry applied to `pid` can be recorded (an earlier game session's records are + * let go first, as xml_applied_find does). */ +static int xml_applied_room(pid_t pid) { + int room = 0; + for (int i = 0; i < XML_APPLIED_MAX; i++) { + xml_applied_t *a = &g_xml_applied[i]; + if (a->rec && a->pid != pid) xml_applied_free(a); + if (!a->rec) room = 1; + } + return room; +} + static int xml_applied_add(pid_t pid, const char *path, int entry, const cheat_loc_t *locs, int n, uint32_t handle, uint64_t mbase, uint64_t msize) { xml_applied_t *a = NULL; @@ -1985,13 +1997,27 @@ static int xml_apply_on(pid_t pid, const char *title, cheat_mod_t *mod, const xm if (err) snprintf(err, err_cap, "patch has no lines"); rc = -1; } + /* Only what can be recorded is written: without its record, turning it off finds nothing to + * put back, says it is off and leaves the bytes in the game. */ + if (rc == 0 && !xml_applied_room(pid)) { + if (err) snprintf(err, err_cap, "%d game patches are on already; turn one off first; nothing was written", + XML_APPLIED_MAX); + rc = -1; + } if (rc == 0) { hook_before_write(hk); rc = cheat_plan_apply(locs, n, 1, NULL, 0, &ops, err, err_cap); } - if (rc == 0 && xml_applied_add(pid, mod->xml_path, mod->xml_entry, locs, n, handle, mbase, msize) != 0) - fprintf(stderr, "[cheats] %s #%d applied but not recorded; restart the game to remove it\n", - mod->xml_path, mod->xml_entry); + if (rc == 0 && xml_applied_add(pid, mod->xml_path, mod->xml_entry, locs, n, handle, mbase, msize) != 0) { + /* Out of memory for the record: take the patch out again (what is there now is its bytes). */ + for (int i = 0; i < n; i++) memcpy(locs[i].cur, locs[i].on, (size_t)locs[i].len); + char undo_err[160] = ""; + int undo = cheat_plan_apply(locs, n, 0, NULL, 0, &ops, undo_err, sizeof undo_err); + fprintf(stderr, "[cheats] %s #%d applied but not recorded; %s\n", mod->xml_path, mod->xml_entry, + undo == 0 ? "taken out again" : "restart the game to remove it"); + if (err) snprintf(err, err_cap, "out of memory; %s", undo == 0 ? "nothing was left written" : undo_err); + rc = -1; + } free(locs); return rc; } From 75a3043c4e1276b7f7d01710b3fdb4938da0326a Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:47:15 -0800 Subject: [PATCH 13/25] Backups: a restore reads only files inside the snapshot (a manifest name with / or .. is skipped) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- payload/src/backup.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/payload/src/backup.c b/payload/src/backup.c index c97864ffe..60641fcb2 100644 --- a/payload/src/backup.c +++ b/payload/src/backup.c @@ -472,6 +472,11 @@ static int restore_from_manifest(const char *snap_dir, int *restored) { * is_path_allowed checks both the lexical form and the realpath() * resolved form (symlink-escape). */ if (!is_path_allowed(original)) 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) + continue; char src[1024]; snprintf(src, sizeof(src), "%s/%s", snap_dir, snap_basename); int c = copy_file(src, original); From 709a78677990ce7e5b267fcf418bd212a0d75f13 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:37:53 -0800 Subject: [PATCH 14/25] Save backups: finalize and clean-up only work inside our own scratch dirs save_archive_backup_finalize joined the console's title ID onto the scratch dir unchecked and then deleted every subfolder but sce_sys. A saves-list reply with a title ID of ".." or an absolute path pointed that at the temp root or a home folder. The title ID must now be one plain folder name and src_dir one of our ps5upload-save- scratch dirs. save_archive_cleanup_temp also refuses a path with .. in it, which Path::starts_with let through. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/save_archive.rs | 84 +++++++++++++++++-- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/client/src-tauri/src/commands/save_archive.rs b/client/src-tauri/src/commands/save_archive.rs index fd0420a8a..51096ea93 100644 --- a/client/src-tauri/src/commands/save_archive.rs +++ b/client/src-tauri/src/commands/save_archive.rs @@ -18,7 +18,41 @@ use ps5upload_core::save_archive::{ backup_finalize, cleanup_temp_dir, make_temp_dir, zip_folder_noted, }; use serde::Deserialize; -use std::path::Path; +use std::path::{Component, Path}; + +/// `src_dir` as a scratch dir `save_archive_make_temp` made: under the system temp root, named +/// `ps5upload-save-…`, with no `.`/`..` in it (`Path::starts_with` compares components as +/// written, so `/../../home/ps5upload-save-x` would otherwise count as under the temp root). +fn scratch_dir(src_dir: &str) -> Result<&Path, String> { + let p = Path::new(src_dir); + let tmp = std::env::temp_dir(); + let ours = p + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("ps5upload-save-")); + let dots = p + .components() + .any(|c| matches!(c, Component::ParentDir | Component::CurDir)); + if !ours || dots || !p.starts_with(&tmp) || p == tmp.as_path() { + return Err(format!("not one of our scratch dirs: {}", p.display())); + } + Ok(p) +} + +/// `name` as one folder under a scratch dir. A title ID comes from the console's saves list, so +/// `..`, an absolute path or a name with a separator would point finalize (which deletes every +/// subfolder but `sce_sys`) at some other folder of this computer. +fn one_folder(name: &str) -> Result<&str, String> { + let mut parts = Path::new(name).components(); + let single = matches!( + (parts.next(), parts.next()), + (Some(Component::Normal(_)), None) + ); + if !single || name.contains(['/', '\\']) { + return Err(format!("not a save folder name: {name:?}")); + } + Ok(name) +} #[tauri::command] pub async fn save_archive_make_temp(prefix: String) -> Result { @@ -32,6 +66,9 @@ pub async fn save_archive_make_temp(prefix: String) -> Result { #[tauri::command] pub async fn save_archive_cleanup_temp(path: String) -> Result<(), String> { + if !path.is_empty() { + scratch_dir(&path)?; + } // remove_dir_all walks every entry under the scratch dir: off the UI thread. tokio::task::spawn_blocking(move || cleanup_temp_dir(&path)) .await @@ -108,12 +145,45 @@ pub struct SaveArchiveBackupFinalizeReq { pub async fn save_archive_backup_finalize( req: SaveArchiveBackupFinalizeReq, ) -> Result { - tokio::task::spawn_blocking(move || { - backup_finalize(&Path::new(&req.src_dir).join(&req.title_id)) - }) - .await - .map_err(|e| format!("backup finalize task: {e}"))? - .map_err(|e| format!("backup finalize: {e:#}")) + let title_dir = scratch_dir(&req.src_dir)?.join(one_folder(&req.title_id)?); + tokio::task::spawn_blocking(move || backup_finalize(&title_dir)) + .await + .map_err(|e| format!("backup finalize task: {e}"))? + .map_err(|e| format!("backup finalize: {e:#}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finalize_takes_only_one_plain_folder_name() { + assert_eq!(one_folder("CUSA12345"), Ok("CUSA12345")); + for bad in [ + "", + ".", + "..", + "/Users/me", + "a/b", + "a\\b", + "C:\\Users\\me", + "../x", + ] { + assert!(one_folder(bad).is_err(), "{bad:?} passed"); + } + } + + #[test] + fn only_our_scratch_dirs_are_worked_on() { + let tmp = std::env::temp_dir(); + let ours = tmp.join("ps5upload-save-CUSA12345-1-2-3"); + assert!(scratch_dir(ours.to_str().unwrap()).is_ok()); + let up = tmp.join("..").join("..").join("ps5upload-save-x"); + assert!(scratch_dir(up.to_str().unwrap()).is_err()); + assert!(scratch_dir(tmp.to_str().unwrap()).is_err()); + assert!(scratch_dir(tmp.join("other").to_str().unwrap()).is_err()); + assert!(scratch_dir("/ps5upload-save-x").is_err()); + } } // ─── Automatic save backups ──────────────────────────────────────────────── From 5b6cad8eebe77a2303a2c5d104a6bfaef1537916 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:40:08 -0800 Subject: [PATCH 15/25] Save backups: a failed zip no longer deletes the file the user picked to replace save_archive_zip truncated the picked .zip with File::create and, on any error, removed it. Picking an existing backup of the same save (the dialog's default name) and then running out of disk, or getting no / folder from the download, lost that older backup. The zip now goes to a temporary file beside it (ReplacingFile, as save_text_file and crash_reports_zip already do) and is renamed over the picked file only once whole. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src-tauri/src/commands/save_archive.rs | 114 ++++++++++++++++-- .../src-tauri/src/commands/save_text_file.rs | 5 + 2 files changed, 108 insertions(+), 11 deletions(-) diff --git a/client/src-tauri/src/commands/save_archive.rs b/client/src-tauri/src/commands/save_archive.rs index 51096ea93..20978368a 100644 --- a/client/src-tauri/src/commands/save_archive.rs +++ b/client/src-tauri/src/commands/save_archive.rs @@ -111,8 +111,8 @@ pub async fn save_archive_zip(req: SaveArchiveZipReq) -> Result .unwrap_or("ps5upload-save-archive.zip"); let dest_buf = super::save_dest::resolve_save_dest(&req.dest_zip, fallback)?; let dest = dest_buf.to_string_lossy().into_owned(); - let result = tokio::task::spawn_blocking(move || { - zip_folder_noted( + tokio::task::spawn_blocking(move || { + zip_replacing( Path::new(&req.src_dir), &req.inner_root, dest_buf.as_path(), @@ -120,18 +120,31 @@ pub async fn save_archive_zip(req: SaveArchiveZipReq) -> Result ) }) .await - .map_err(|e| format!("zip task: {e}"))?; - if let Err(e) = result { - // On failure (typically ENOSPC mid-write), remove the - // half-written .zip so the user doesn't see a corrupt file - // at their picked path. Best-effort — if the unlink itself - // fails, the original error is still what surfaces. - let _ = std::fs::remove_file(&dest); - return Err(format!("zip: {e:#}")); - } + .map_err(|e| format!("zip task: {e}"))??; Ok(dest) } +/// The zip written beside `dest` and renamed over it only once it is whole. A failed zip (a full +/// disk, or no `/` downloaded) used to truncate and then delete the file the user +/// picked to replace, often an older backup of the same save; now that file stays as it was, and +/// a failed new file leaves nothing behind. +fn zip_replacing(src_dir: &Path, inner_root: &str, dest: &Path, note: &str) -> Result<(), String> { + if !src_dir.join(inner_root).is_dir() { + return Err(format!( + "zip: expected `{inner_root}/` under {}", + src_dir.display() + )); + } + let (replacing, file) = super::save_text_file::ReplacingFile::create(dest) + .map_err(|e| format!("create {}: {e}", dest.display()))?; + drop(file); + zip_folder_noted(src_dir, inner_root, replacing.path(), note) + .map_err(|e| format!("zip: {e:#}"))?; + replacing + .commit() + .map_err(|e| format!("save {}: {e}", dest.display())) +} + #[derive(Debug, Deserialize)] pub struct SaveArchiveBackupFinalizeReq { /// Scratch dir that contains `/` from a fresh @@ -184,6 +197,85 @@ mod tests { assert!(scratch_dir(tmp.join("other").to_str().unwrap()).is_err()); assert!(scratch_dir("/ps5upload-save-x").is_err()); } + + fn scratch(tag: &str) -> std::path::PathBuf { + let d = + std::env::temp_dir().join(format!("ps5upload-zip-test-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn names_in(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + v.sort(); + v + } + + #[test] + fn a_failed_zip_leaves_the_picked_file_as_it_was() { + let dir = scratch("nofolder"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let dest = out.join("CUSA12345.zip"); + std::fs::write(&dest, b"older backup").unwrap(); + // Nothing was downloaded as /: the old backup used to be deleted. + assert!(zip_replacing(&src, "CUSA12345", &dest, "").is_err()); + assert_eq!(std::fs::read(&dest).unwrap(), b"older backup"); + assert_eq!(names_in(&out), ["CUSA12345.zip"]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn a_zip_that_fails_part_way_leaves_the_picked_file_as_it_was() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("partway"); + let save = dir.join("src").join("CUSA12345"); + std::fs::create_dir_all(&save).unwrap(); + std::fs::write(save.join("a.bin"), b"a").unwrap(); + let locked = save.join("b.bin"); + std::fs::write(&locked, b"b").unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + if std::fs::File::open(&locked).is_ok() { + // Running as root: nothing can fail to open here. + let _ = std::fs::remove_dir_all(&dir); + return; + } + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let dest = out.join("CUSA12345.zip"); + std::fs::write(&dest, b"older backup").unwrap(); + assert!(zip_replacing(&dir.join("src"), "CUSA12345", &dest, "").is_err()); + assert_eq!(std::fs::read(&dest).unwrap(), b"older backup"); + assert_eq!(names_in(&out), ["CUSA12345.zip"]); + let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_whole_zip_replaces_the_picked_file() { + let dir = scratch("whole"); + let save = dir.join("src").join("CUSA12345"); + std::fs::create_dir_all(&save).unwrap(); + std::fs::write(save.join("a.bin"), b"a").unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let dest = out.join("CUSA12345.zip"); + std::fs::write(&dest, b"older backup").unwrap(); + zip_replacing(&dir.join("src"), "CUSA12345", &dest, "note").unwrap(); + assert_eq!( + ps5upload_core::save_archive::zip_comment(&dest).unwrap(), + "note" + ); + assert_eq!(names_in(&out), ["CUSA12345.zip"]); + let _ = std::fs::remove_dir_all(&dir); + } } // ─── Automatic save backups ──────────────────────────────────────────────── diff --git a/client/src-tauri/src/commands/save_text_file.rs b/client/src-tauri/src/commands/save_text_file.rs index bdd2d1aad..c43fb15a9 100644 --- a/client/src-tauri/src/commands/save_text_file.rs +++ b/client/src-tauri/src/commands/save_text_file.rs @@ -85,6 +85,11 @@ impl ReplacingFile { } } + /// Where the bytes go until `commit`, for a writer that opens the file by its path. + pub(super) fn path(&self) -> &Path { + &self.path + } + /// All written: this is now the destination. pub(super) fn commit(mut self) -> std::io::Result<()> { if let Some(dest) = self.dest.take() { From 9e853e38db0126cc7d171ee1fd506b83b9073ada Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:36:06 -0800 Subject: [PATCH 16/25] Save backups: a console deleted while the first list was on its way is taken off the engine's list startSaveBackupSync worked out the consoles to remove from `told`, which changed only when a request landed. Deleting a console while the first list was still on its way removed nothing, and the engine kept backing that console up. One list is now sent at a time, and the latest roster goes after it lands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/state/autoSaveBackup.test.ts | 16 ++++++++++++++++ client/src/state/autoSaveBackup.ts | 19 ++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/client/src/state/autoSaveBackup.test.ts b/client/src/state/autoSaveBackup.test.ts index 00bb62b92..9795c8bdd 100644 --- a/client/src/state/autoSaveBackup.test.ts +++ b/client/src/state/autoSaveBackup.test.ts @@ -72,6 +72,22 @@ describe("giving the engine the console list", () => { stop(); }); + it("a console removed while the first list is on its way is still taken off", async () => { + useRosterStore.setState({ profiles: [{ host: "10.0.0.2" }, { host: "10.0.0.3" }] as never }); + let land: (v: unknown) => void = () => {}; + set.mockImplementationOnce(() => new Promise((r) => (land = r))).mockResolvedValue({}); + const stop = startSaveBackupSync(); + await vi.advanceTimersByTimeAsync(0); + expect(set).toHaveBeenCalledTimes(1); + // Deleted before the engine answered the first list. + useRosterStore.setState({ profiles: [{ host: "10.0.0.2" }] as never }); + await vi.advanceTimersByTimeAsync(0); + land({}); + await vi.advanceTimersByTimeAsync(0); + expect(set).toHaveBeenLastCalledWith({ add_hosts: ["10.0.0.2"], remove_hosts: ["10.0.0.3"] }); + stop(); + }); + it("stops trying when stopped", async () => { set.mockRejectedValue(new Error("engine not up")); const stop = startSaveBackupSync(); diff --git a/client/src/state/autoSaveBackup.ts b/client/src/state/autoSaveBackup.ts index 2cf068591..4bcf71280 100644 --- a/client/src/state/autoSaveBackup.ts +++ b/client/src/state/autoSaveBackup.ts @@ -156,14 +156,31 @@ export function startSaveBackupSync(): () => void { // What this client has told the engine about: only that can be taken off again. Several clients // can share one engine, and each has its own roster. let told: string[] = []; + // One list on its way at a time: `told` changes only when one lands, so a console deleted while + // the first list was on its way was worked out against the old `told` and never taken off (and + // two lists landing out of order could leave the older one as what the engine has). + let inFlight = false; + let again = false; const push = (profiles: readonly { host: string }[]) => { const hosts = backupHosts(profiles); const key = hosts.join(","); if (key === sent) return; + if (inFlight) { + again = true; + return; + } sent = key; if (retry) clearTimeout(retry); retry = null; const removed = told.filter((h) => !hosts.includes(h)); + inFlight = true; + const landed = () => { + inFlight = false; + if (again && !stopped) { + again = false; + push(useRosterStore.getState().profiles); + } + }; void saveBackupApi.set({ add_hosts: hosts, remove_hosts: removed }).then( () => { told = hosts; @@ -181,7 +198,7 @@ export function startSaveBackupSync(): () => void { push(useRosterStore.getState().profiles); }, Math.min(RETRY_MAX_MS, RETRY_FIRST_MS * 2 ** Math.min(failures, 8))); }, - ); + ).finally(landed); }; void (async () => { try { From a88f3d236307be6cd01bd8cd0a31a6c7af9e547b Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:38:56 -0800 Subject: [PATCH 17/25] Play Together: a friend's player opens no decoder after it was stopped WatchPlayer.stop() closed the decoder it had, but a message already on its way, a rebuild for the closed decoder, or an H.265 codec lookup still running made a new configured VideoDecoder that nothing closed. A phone has few hardware decoders, so the next join could fail to decode. A stopped player now ignores messages and opens nothing. Embedded join/pad pages rebuilt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/pad/watchPlayer.recover.test.ts | 33 +++++++++++++++++++ client/src/pad/watchPlayer.ts | 13 +++++--- .../ps5upload-engine/src/join_page.html | 2 +- .../crates/ps5upload-engine/src/pad_page.html | 2 +- site/join/index.html | 2 +- site/pad/index.html | 2 +- 6 files changed, 46 insertions(+), 8 deletions(-) diff --git a/client/src/pad/watchPlayer.recover.test.ts b/client/src/pad/watchPlayer.recover.test.ts index e94120e1c..e94381299 100644 --- a/client/src/pad/watchPlayer.recover.test.ts +++ b/client/src/pad/watchPlayer.recover.test.ts @@ -87,4 +87,37 @@ describe("a guest's decoder", () => { made[0].init.error(new Error("late")); expect(problems).toEqual(["decode"]); }); + + it("makes no new one once stopped: a late picture or header leaves nothing open", async () => { + const { p } = await setUp(); + p.stop(); + expect(made[0].state).toBe("closed"); + // Messages already on their way when the guest left. + p.onMessage(KEY); + p.onMessage(HEADER); + await flush(); + expect(made).toHaveLength(1); + }); + + it("makes no H.265 decoder when stopped while its codec was looked up", async () => { + let answer: (v: { supported: boolean }) => void = () => {}; + vi.stubGlobal( + "VideoDecoder", + class extends FakeDecoder { + static isConfigSupported = () => new Promise<{ supported: boolean }>((r) => (answer = r)); + }, + ); + const p = new WatchPlayer(() => {}, "player"); + p.setHevc(true); + // An H.265 VPS/SPS/PPS header. + p.onMessage( + new Uint8Array([0, 0, 0, 0, 1, 0x40, 0x01, 0x0c, 0, 0, 0, 1, 0x42, 0x01, 0x01, 0x01, 0x60, 0, 0, 0, 1, 0x44, 0x01, 0xc0]) + .buffer, + ); + await flush(); + p.stop(); + answer({ supported: true }); + await flush(); + expect(made).toHaveLength(0); + }); }); diff --git a/client/src/pad/watchPlayer.ts b/client/src/pad/watchPlayer.ts index fdcbcfa92..e02dfcc9a 100644 --- a/client/src/pad/watchPlayer.ts +++ b/client/src/pad/watchPlayer.ts @@ -351,6 +351,10 @@ export class WatchPlayer { private software = false; private video: VideoDecoder | null = null; private opening = false; + /** `stop` ran: nothing new is opened. A message already on its way, a rebuild for a closed + * decoder, or an H.265 codec lookup still running made a decoder that nothing closed, and a + * phone has few hardware decoders to spare for the next join. */ + private stopped = false; private sawKey = false; private keyAsk: KeyAsker; private readonly ownStats = new PictureStats("webcodecs"); @@ -526,7 +530,7 @@ export class WatchPlayer { /** One binary message from the engine. */ onMessage(buf: ArrayBuffer): void { const b = new Uint8Array(buf); - if (b.length < 1) return; + if (b.length < 1 || this.stopped) return; const kind = b[0]; const payload = b.subarray(1); // The media player took the picture over: the video is its, the sound stays here. @@ -547,8 +551,8 @@ export class WatchPlayer { this.opening = true; try { const codec = this.hevc ? await hevcFor(header) : avcCodecString(header); - // The media player took over while this was looked up. - if (this.mse) return; + // The media player took over, or the player was stopped, while this was looked up. + if (this.mse || this.stopped) return; if (!codec) { this.problemShown = true; this.onProblem("no_hevc"); @@ -643,7 +647,7 @@ export class WatchPlayer { /** The decoder failed, or the browser took it back (a hidden page's hardware decoder): a new one * from the header, and the next keyframe. Without this the picture stays frozen for good. */ private rebuild(): void { - if (this.mse) return; + if (this.mse || this.stopped) return; this.video = null; this.sawKey = false; if (!this.header) return; @@ -769,6 +773,7 @@ export class WatchPlayer { } stop(): void { + this.stopped = true; try { this.video?.close(); } catch { diff --git a/engine/crates/ps5upload-engine/src/join_page.html b/engine/crates/ps5upload-engine/src/join_page.html index 90639f109..b260f68a4 100644 --- a/engine/crates/ps5upload-engine/src/join_page.html +++ b/engine/crates/ps5upload-engine/src/join_page.html @@ -268,7 +268,7 @@ ã/¸Ä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 T={a:v};this.setModule=t=>{e.setModule(yi,t)},this.getModule=()=>e.getModule(yi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,T)).then(e=>{let t=e.exports;y(t),a=t.g,o(),te(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 bi=o((()=>{}));function xi(e={}){xi.errors||Object.defineProperties(xi,{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+` `+(xi.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 Si=o((()=>{vi(),bi()})),Ci,wi=o((()=>{vi(),bi(),Si(),Ci=class extends mi{constructor(e){super(e,`opus-decoder`,xi,yi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ti=c({OpusDecoder:()=>xi,OpusDecoderWebWorker:()=>Ci}),Ei=o((()=>{Si(),wi(),vi(),gi(xi,`OpusDecoder`),gi(Ci,`OpusDecoderWebWorker`)})),Di=[8e3,12e3,16e3,24e3,48e3],Oi=null;function ki(){return Oi??=Yn(()=>Promise.resolve().then(()=>(Ei(),Ti)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw Oi=null,e}),Oi}function Ai(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function ji(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 Mi=class{constructor(e,t=ki){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(!Ai())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Di.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(ji(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{}}},Ni={makeDecoder:e=>new Mi(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Pi(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 Fi(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 Ii=[`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 Li(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Ii)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function Ri(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 zi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Bi(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 I(...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 Vi=(e,t,n,...r)=>Bi(e,I([t,1],[n,3]),...r),Hi=I([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Ui(e){let t=e.handler===`vide`,n=Bi(`ftyp`,new TextEncoder().encode(`isom`),I([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Bi(`moov`,Vi(`mvhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Hi,new Uint8Array(24),I([2,4])),Bi(`trak`,Vi(`tkhd`,0,3,I([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Hi,I([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Bi(`mdia`,Vi(`mdhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Vi(`hdlr`,0,0,I([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),I([0,1])),Bi(`minf`,t?Vi(`vmhd`,0,1,new Uint8Array(8)):Vi(`smhd`,0,0,I([0,4])),Bi(`dinf`,Vi(`dref`,0,0,I([1,4]),Vi(`url `,0,1))),Bi(`stbl`,Vi(`stsd`,0,0,I([1,4]),e.sampleEntry),Vi(`stts`,0,0,I([0,4])),Vi(`stsc`,0,0,I([0,4])),Vi(`stsz`,0,0,I([0,4],[0,4])),Vi(`stco`,0,0,I([0,4])))))),Bi(`mvex`,Vi(`trex`,0,0,I([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 Wi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Vi(`trun`,0,1793,I([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Bi(`traf`,Vi(`tfhd`,0,131072,I([1,4])),Vi(`tfdt`,1,0,I([t,8])),o(e)),c=Vi(`mfhd`,0,0,I([e,4])),l=Bi(`moof`,c,s(0)).length,u=Bi(`moof`,c,s(l+8)),d=Bi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Gi(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=Ri(e).filter(e=>!r.includes(zi(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 Ki=e=>e.toString(16).padStart(2,`0`),qi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Ji=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 Yi(e){let t=Ri(e),n=t.filter(e=>zi(e,!1)===7),r=t.filter(e=>zi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Ji([I([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(qi),I([r.length,1]),...r.map(qi)])}function Xi(e,t,n){let r=Ri(e),i=e=>r.filter(n=>zi(n,t)===e),a=(e,t)=>Bi(e,new Uint8Array(6),I([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),I([24,2],[65535,2]),t);if(!t){let t=i(7),r=Yi(e);return r?{init:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Bi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ki(t[0][1])}${Ki(t[0][2])}${Ki(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=Yr(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)=>Ji([I([128|e,1],[t.length,2]),...t.map(qi)]),m=Bi(`hvcC`,I([1,1]),u,I([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:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Zi(e,t,n,r,i,a){return Wi(e,t,n,Gi(r,i),a)}function Qi(e,t){let n=Bi(`dOps`,I([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Ui({handler:`soun`,timescale:48e3,sampleEntry:Bi(`Opus`,new Uint8Array(6),I([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function $i(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 ea(e,t,n){return Wi(e,t,$i(n),n,!0)}var ta={watch:30,player:4},na={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ra={seek:.8,speed:.25,target:.12};function ia(e,t,n){let r=typeof n==`string`?na[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 aa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ma(e,t,n):new Oa(e,t,n)}var oa=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 L(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var R=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 sa(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 ca(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var la=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+ua;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}},ua=.02;async function da(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var fa=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}},pa=[`pointerup`,`touchend`,`click`,`keydown`],ma=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():ca(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.sawKey=!1,this.ownStats=new fa(`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 oa(n),this.clock=new la(t===`player`?.05:.08),typeof AudioDecoder>`u`&&_a()&&(this.mseSound=new va(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=ti(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!ba())return!1;let e=new Oa(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,ha(),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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1)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=ti(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await ka(e):Fi(e);if(this.mse)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Yi(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=ni(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.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=Pi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>ta[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=Gi(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];da(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return _a()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new oi((e,t)=>this.play(e,t,r.sampleRate));try{r.header(sa(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new va(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new oi((e,n)=>this.play(e,n,t.sampleRate),Ni,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(sa(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(){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 ha(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ga(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function _a(){let e=typeof window>`u`?null:ba();return!!e&&(ga(e,`audio/mp4; codecs="Opus"`)||ga(e,`audio/mp4; codecs="opus"`))}var va=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 R,this.el=n,this.track=new wa(n,()=>this.fail(),e===`player`?ra: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=L(e);if(!t||!this.order.take(t.index))return;let n=ea(this.track.nextSeq(),this.time,t.packet);this.time+=$i(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=Qi(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())}},ya=class{constructor(e,t,n=Ni){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 la(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,ha();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 oi((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(sa(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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function ba(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var xa=10,Sa=3;function Ca(e,t,n,r=Sa){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var wa=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=ba();if(!n||!ga(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=Ta(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=ia(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>xa&&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-Sa;if(this.keys){if(r=Ca(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Sa&&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 Ta(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Ea=1e4,Da=class{constructor(e=3,t=Ea,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=[]}},Oa=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 fa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new oa(n),this.fails=new Da(3,Ea,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 va(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new wa(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(!_a())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ya(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?ca(`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=ti(e,this.hevc)??{w:1920,h:1080},r=Xi(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=Pi(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>ta[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(Zi(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 ka(e){let t=ri(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Li(1920,1080)}var z={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},Aa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function ja(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Ma={ArrowUp:{button:z.UP},ArrowDown:{button:z.DOWN},ArrowLeft:{button:z.LEFT},ArrowRight:{button:z.RIGHT},Enter:{button:z.CROSS},Space:{button:z.CROSS},Backspace:{button:z.CIRCLE},Escape:{button:z.CIRCLE},KeyQ:{button:z.SQUARE},KeyE:{button:z.TRIANGLE},KeyZ:{button:z.L1},KeyC:{button:z.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:z.L3},KeyG:{button:z.R3},Tab:{button:z.OPTIONS},Backquote:{button:z.SHARE},KeyH:{button:z.PS},KeyT:{button:z.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}};z.UP,z.DOWN,z.LEFT,z.RIGHT,z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD;var Na=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Pa(e,t=Ma){let n={...Aa};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Na(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Fa=[z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,0,0,z.SHARE,z.OPTIONS,z.L3,z.R3,z.UP,z.DOWN,z.LEFT,z.RIGHT,z.PS,z.TOUCHPAD];function Ia(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var La=[0,1,1,1,0,-1,-1,-1],Ra=[-1,-1,0,1,1,1,0,-1];function za(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ia(n);return e===null?0:(t.hat===`x`?La:Ra)[e]}return t.inv?-n:n}var Ba={buttons:Fa.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 Va(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=Ia(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 Ha(e){if(e.mapping===`standard`)return Ba;let t=Ua.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Ba;let r={...Ba,buttons:[...Ba.buttons,[z.UP,{h:n,at:0}],[z.RIGHT,{h:n,at:2}],[z.DOWN,{h:n,at:4}],[z.LEFT,{h:n,at:6}]]};return Ua.set(e.id,r),r}var Ua=new Map;function Wa(e,t=Ha){let n={...Aa},r=e=>Math.abs(e)<.08?0:Na(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(za(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Va(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Va(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Va(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 Ga(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Na(e.lx+t.lx),ly:Na(e.ly+t.ly),rx:Na(e.rx+t.rx),ry:Na(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function Ka(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 qa=new Map;function Ja(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 Ya(e){let t=e?.getGamepads?.()??[];return qa.size===0||t.some(e=>!!e?.connected)?[...t]:[...qa.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ja(e))}var Xa=`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(`(`),Za={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},Qa=e=>e.toLowerCase().padStart(4,`0`);function $a(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:Qa(t[2]),product:Qa(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:Qa(n[1]),product:Qa(n[2]),name:n[3].trim()}:null}function eo(e){return($a(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function to(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 no(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Za[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Xa[n]??null}return null}function ro(e){return e.mapping!==`standard`&&$a(e.id)?.vendor===`2dc8`}var io={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 ao(e){let t=$a(e);return t&&io[t.product]||`manual`}var oo={1:0,2:2,4:4,8:6};function so(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 co(e,t,n){let{n:r,hat:i}=so(t),a=Fa.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 lo(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=oo[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 uo(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 fo(e,t,n){let r=e.split(`,`),i=co(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`&&go(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(go)}function vo(){try{let e=It(ho),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>_o(e[1])))}catch{return{}}}function yo(e,t){let n=vo();return t?n[e]=t:delete n[e],Ft(ho,JSON.stringify(n)),bo=n,n}var bo=null;function xo(e){return bo??=vo(),bo[e.id]??wo(bo,e.id)??mo(e)??Ha(e)}function So(e){return bo??=vo(),bo[e.id]?`saved`:e.mapping===`standard`?`standard`:mo(e)?`known`:`guess`}function Co(e){return mo(e)??Ha(e)}function wo(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?(bo=yo(t,e[i]),e[i]):null}function To(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Eo(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?Ia(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 Do(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 Oo=[{kind:`button`,bit:z.CROSS,name:`✕`},{kind:`button`,bit:z.CIRCLE,name:`○`},{kind:`button`,bit:z.SQUARE,name:`□`},{kind:`button`,bit:z.TRIANGLE,name:`△`},{kind:`button`,bit:z.UP,name:`↑`},{kind:`button`,bit:z.DOWN,name:`↓`},{kind:`button`,bit:z.LEFT,name:`←`},{kind:`button`,bit:z.RIGHT,name:`→`},{kind:`button`,bit:z.L1,name:`L1`},{kind:`button`,bit:z.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:z.L3,name:`L3`},{kind:`button`,bit:z.R3,name:`R3`},{kind:`button`,bit:z.OPTIONS,name:`Options`},{kind:`button`,bit:z.SHARE,name:`Create`},{kind:`button`,bit:z.PS,name:`PS`},{kind:`button`,bit:z.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 ko(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function Ao(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 jo(e,t=Ba){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 Mo=Oo.filter(e=>e.kind!==`button`||![z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD].includes(e.bit));function No(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 Po=class{constructor(e=Oo){this.steps=e,this.step=0,this.prof=ko(),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 No(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Do(this.rest,e):Eo(this.rest,e);return n?(this.prof=Ao(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=Ba){return jo(this.prof,e)}};function Fo(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 Io(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Lo=e=>`ps5upload.join.token.${e??`app`}`,Ro=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...Aa},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?Io():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 Lo(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=He(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=qe(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()+$e),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()+$e,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()+Qe),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Ze(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?{...Aa,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Fo(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Xe(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(Xe(this.seq,Aa))),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(Xe(this.seq,Aa))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},zo=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})),B=s(((e,t)=>{t.exports=zo()}))(),Bo=`ps5upload.openIn`,Vo=`ps5upload.openIn.tab`;function Ho(){try{return sessionStorage.getItem(Vo)===`browser`}catch{return!1}}function V(){try{sessionStorage.setItem(Vo,`browser`)}catch{}}function H(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Uo({appLink:e,children:t}){let n=Fe(),[r,i]=(0,E.useState)(()=>Ho()?`browser`:H(It(Bo))),[a,o]=(0,E.useState)(!1);if((0,E.useEffect)(()=>{r===`opening`&&It(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,B.jsx)(B.Fragment,{children:t});let s=()=>{a&&Ft(Bo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?Ft(Bo,`browser`):r===`opening`&&It(`ps5upload.openIn`)===`app`&&Lt(Bo),V(),i(`browser`)};return(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,B.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,B.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,B.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,B.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,B.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,B.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,B.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 Wo({id:e,className:t}){let n=Fe(),r=ao(e);if(r===`none`)return(0,B.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,B.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 Go=new Set,Ko={held:new Set,touch:null,touchPad:Aa,mapping:!1,get paused(){return Go.size>0},motion:null},qo={s:.85,m:1,l:1.15},Jo=.25;function Yo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(Jo,e))}var Xo={overlay:{width:844,height:390},deck:{width:390,height:480}},Zo=.7,Qo=1.4;function $o(e,t,n,r){let i=qo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?Xo.deck:Xo.overlay,o=Math.min(Qo,Math.max(Zo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var es=34;function ts(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+es>t}function ns(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 rs=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,is=32767,as=12;function os({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Fe(),s=(0,E.useRef)(new Map),c=(0,E.useRef)({...Aa}),[l,u]=(0,E.useState)({...Aa}),[d,f]=(0,E.useState)({l:!1,r:!1,touchpad:!1}),p=(0,E.useRef)(null),[m,h]=(0,E.useState)({width:0,height:0});(0,E.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,E.useEffect)(()=>()=>{Ko.touchPad={...Aa}},[]);let g=()=>{let t={...Aa,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|=z.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,Ko.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*is),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*is)},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=ja((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=ja((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)>as&&(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)]`,te={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},T=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),ne=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,re={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ie=(e,t,n,r)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${ne} ${n}`,style:re,children:r}),ae=(e,t,n,r)=>(0,B.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}),oe=(e,t,n,r)=>ie(e,t,`h-[44px] w-[84px]`,ae(e,ee(t),n,r)),se=(e,t,n)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${ne} h-[44px] w-[84px]`,style:re,children:ae(e,l[t]>0,n,!0)}),D=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:(0,B.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...T(ee(t)),children:[(0,B.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,B.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),O=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:[(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...T(ee(t))}),(0,B.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),ce=(e,t)=>ie(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,B.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})),le=(e,t)=>ie(e,t,`h-[44px] w-[44px]`,(0,B.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),ue=e=>{let{dx:t,dy:n}=ns(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,B.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,B.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))`}})})},k=t===`deck`,de=$o(r,m.width,m.height,k),fe=e=>`${e}px * var(--k)`,pe=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=k?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${fe(t)}, ${n}px))`:`calc(${e} + ${fe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=k&&ts(de,m.height),A=k?void 0:`58%`,j=e=>k?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?pe:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?pe:me},xe=e=>({bottom:be?he:_e(he,k?56:0,44),[e]:be?`calc(${e===`left`?pe:me} + 8px + max(${fe(80)}, 44px))`:_e(e===`left`?pe:me,k?40:168)}),Se=!!a&&!k;return(0,B.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${k?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:k?i:void 0,"--k":de},"data-testid":`rp-touch`,"data-layout":t,"data-scale":de,onContextMenu:e=>e.preventDefault(),children:[(0,B.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:Yo(n)},children:[(0,B.jsx)(`div`,{style:ye(`top left`,{top:ge,left:pe}),children:(0,B.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:k?void 0:`6deg`,transformOrigin:`top left`},children:[se(`L2`,`l2`,`l`),oe(`L1`,z.L1,`l`,!1)]})}),(0,B.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,B.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:k?void 0:`-6deg`,transformOrigin:`top right`},children:[se(`R2`,`r2`,`r`),oe(`R1`,z.R1,`r`,!1)]})}),(0,B.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:k?{top:_e(ge,6),left:_e(pe,104),right:_e(me,104),height:`max(44px, calc(${fe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${fe(250)}), 34vw)`,height:`max(44px, calc(${fe(56)}))`}}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top left`:`left center`,j(`left`)),children:[(0,B.jsx)(`span`,{}),D(`↑`,z.UP,0),(0,B.jsx)(`span`,{}),D(`←`,z.LEFT,-90),(0,B.jsx)(`span`,{}),D(`→`,z.RIGHT,90),(0,B.jsx)(`span`,{}),D(`↓`,z.DOWN,180),(0,B.jsx)(`span`,{})]}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top right`:`right center`,j(`right`)),children:[(0,B.jsx)(`span`,{}),O(`△`,z.TRIANGLE,(0,B.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,B.jsx)(`span`,{}),O(`□`,z.SQUARE,(0,B.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,B.jsx)(`span`,{}),O(`○`,z.CIRCLE,(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,B.jsx)(`span`,{}),O(`✕`,z.CROSS,(0,B.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,B.jsx)(`span`,{})]}),(0,B.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:ue(`l`)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:ue(`r`)}),(0,B.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:pe}),children:ce(`Create`,z.SHARE)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:ce(`Options`,z.OPTIONS)}),(0,B.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:rs,translate:`-50% 0`}),children:le(`PS`,z.PS)})]}),Se&&(0,B.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,Yo(n))},children:(0,B.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:`${ne} h-[44px] w-[56px]`,style:re,"data-testid":`rp-menu-handle`,children:(0,B.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,B.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var ss=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,cs=null,ls=null;function us(e){e.play().catch(()=>{if(ls||cs!==e)return;let t=()=>{ds(),cs===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),ls=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function ds(){ls?.(),ls=null}function fs(){if(typeof document<`u`){if(!cs){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=ss,document.body.appendChild(e),cs=e}us(cs)}}function ps(){ds(),cs&&=(cs.pause(),cs.removeAttribute(`src`),cs.remove(),null)}function ms(){return typeof navigator>`u`?null:navigator.wakeLock??null}function hs(){return ut()||!Nn()}var gs=new Set,_s=null,vs=Promise.resolve(),ys=!1;async function bs(){if(gs.size===0||_s&&!_s.released)return;let e=ms();if(!e)ut()&&fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{_s===t&&(_s=null)}),_s=t}catch{}}async function xs(){ps();let e=_s;if(_s=null,e&&!e.released)try{await e.release()}catch{}}function Ss(){ys||typeof document>`u`||(ys=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&gs.size>0&&(vs=vs.then(bs))}))}function Cs(e,t){if(!hs())return;Ss();let n=gs.size>0;t?gs.add(e):gs.delete(e);let r=gs.size>0;n!==r&&(vs=vs.then(r?bs:xs))}var ws=new Set;function Ts(){if(typeof window<`u`)return window.PS5UploadPad}function Es(e,t){let n=ws.size>0;t?ws.add(e):ws.delete(e);let r=ws.size>0;if(n!==r)try{Ts()?.setActive(r)}catch{}}var Ds=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}},Os=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 Ds(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}},ks=`ps5upload.join.muted`,As=5e3,js=Object.fromEntries(Object.entries(Ma).filter(([e])=>e!==`Escape`)),Ms=new Set;function Ns(e){if(!(e.code in js)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||Ps(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||Ps(t))}function Ps(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 Fs=!1;function Is(e){Fs=e}function Ls(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function Rs(){if(Fs)return{...Aa};let e=Wa(Ya(typeof navigator>`u`?void 0:navigator),xo),t=Ko.touchPad;return{...Ga(Ga(e,Pa(Ms,js)),t),touch:t.touch??null,motion:Ko.motion??null}}var zs=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:Vs(),path:null},this.client=new Ro({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:Rs,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:()=>Ls(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Os&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Ya(typeof navigator>`u`?void 0:navigator);Ka(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=aa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Os(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`?Ms.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{Ms.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&Ns(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),Ms.add(e.code))},r=e=>{Ms.delete(e.code)&&Ns(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()},As);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),Ms.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(ks,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();Ko.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 Bs(e){return(0,E.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function Vs(){try{return typeof localStorage<`u`&&localStorage.getItem(ks)===`1`}catch{return!1}}function Hs(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Cs(`play-together`,n),Es(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Cs(`play-together`,!1),Es(`play-together`,!1)}}var Us=3e3,Ws=class{constructor(e,t=Us){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 Gs(e,t,n=!1){let[r,i]=(0,E.useState)(!0),a=(0,E.useRef)(null);(0,E.useEffect)(()=>{let e=new Ws(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,E.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,E.useCallback)(()=>a.current?.poke(),[]),s=(0,E.useCallback)(()=>a.current?.hide(),[]),c=(0,E.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var Ks=3e4,qs=class{constructor(e,t=Ks){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 Js(e){let[,t]=(0,E.useState)(0),[n]=(0,E.useState)(()=>new qs(()=>t(e=>e+1)));return(0,E.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,E.useEffect)(()=>()=>n.reset(),[n]),n.shown}var Ys=()=>Ya(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function Xs(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===z.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===z.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===z.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===z.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 Zs(e,t){let n=(0,E.useRef)(t);(0,E.useEffect)(()=>{n.current=t}),(0,E.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(Ys().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var Qs=[[z.CROSS,`✕`],[z.CIRCLE,`○`],[z.SQUARE,`□`],[z.TRIANGLE,`△`],[z.UP,`↑`],[z.DOWN,`↓`],[z.LEFT,`←`],[z.RIGHT,`→`],[z.L1,`L1`],[z.R1,`R1`],[z.L3,`L3`],[z.R3,`R3`],[z.SHARE,`Create`],[z.OPTIONS,`Options`],[z.PS,`PS`],[z.TOUCHPAD,`Touchpad`]];function $s({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,B.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,B.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,B.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[Qs.map(([n,r])=>(0,B.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,B.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,B.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,B.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function ec({onClose:e}){let t=Fe(),[n,r]=(0,E.useState)(()=>Ys().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,E.useState)(()=>Ys()[0]?.index??null),[o,s]=(0,E.useState)(Aa),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(0),[f,p]=(0,E.useState)(vo),[m,h]=(0,E.useState)(null),[g,_]=(0,E.useState)(null);(0,E.useEffect)(()=>(Is(!0),()=>Is(!1)),[]),(0,E.useEffect)(()=>{let e=()=>{let e=Ys();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)}},[]),Zs(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(To(e))&&v(c,e);return}let t=Wa([e],xo);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 v=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(yo(r,e.profile(n?Co(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},y=()=>{h(null),d(0),l(new Po(Mo))},b=g,x=b?So(b):null,S=!!(b&&f[b.id]);return(0,B.jsx)(`div`,{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,B.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,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(me,{size:16,className:`text-white/70`}),(0,B.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,B.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,B.jsx)(Ee,{size:15})})]}),b?(0,B.jsxs)(B.Fragment,{children:[n.length>1&&(0,B.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,B.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:eo(e.id)},`${e.index}-${e.id}`))}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:eo(b.id)}),(0,B.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":x??``,children:x===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):x===`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`)}),ro(b)&&(0,B.jsx)(Wo,{id:b.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,B.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,B.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,B.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?Xs(t,c.current):``}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),v(c,b)},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,B.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,B.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,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)($s,{pad:o}),m&&(0,B.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:y,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:S?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),S&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>{p(yo(b.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,B.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,B.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 tc(e,t){let[n,r]=(0,E.useState)(!1);return(0,E.useEffect)(()=>{if(!e||!t)return;let n=!0;return ze(e,Ie).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function nc({href:e}){let t=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,B.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,B.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 rc(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var ic=`ps5upload.join.guided`,ac=1;function oc(e){return e.player!==ac&&(!e.guided||e.movedOff)&&!e.reconnecting}function sc(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 cc(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 lc(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 cc(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 cc(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 uc(e){let[t,n]=(0,E.useState)(()=>Date.now());return(0,E.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function dc(){let[e,t]=(0,E.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,E.useEffect)(()=>{let e=()=>{let e=Ya(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?Rs():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?So(e):null,s=!!e&&ro(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 pc=14,mc=()=>typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,hc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function gc({text:e,body:t,onCancel:n}){let r=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,B.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,B.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,B.jsx)(Se,{size:26})})]}),(0,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,B.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,B.jsx)(`button`,{type:`button`,onClick:n,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 _c({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Fe(),c=Bs(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,E.useRef)(null),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(()=>It(ic)===`1`),[_,v]=(0,E.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),y=dc(),[b,x]=(0,E.useState)(!1),S=l.kind===`reconnecting`,ee=uc(S),C=l.kind===`joined`||S,w=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[T,ne]=(0,E.useState)(!1),re=(0,E.useRef)(te);(0,E.useEffect)(()=>{re.current===ac&&te>ac&&ne(!0),te&&(re.current=te)},[te]);let[ie,ae]=(0,E.useState)(!1),[oe,se]=(0,E.useState)(!1),D=C&&(p||!t),O=mc(),ce=Js(w),ue=Gs(D,S||ce&&!O||ie||oe,O),{poke:de}=ue,pe=(0,E.useRef)(null),he=()=>{pe.current&&clearTimeout(pe.current.timer),pe.current=null};(0,E.useEffect)(()=>he,[]);let[_e,ve]=(0,E.useState)(!1),ye=(0,E.useRef)(!1);(0,E.useEffect)(()=>{if(!D||!O||ue.shown||!h||ye.current)return;ye.current=!0,ve(!0);let e=setTimeout(()=>ve(!1),6e3);return()=>clearTimeout(e)},[D,O,ue.shown,h]),(0,E.useEffect)(()=>{if(!C)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[C,e]),(0,E.useEffect)(()=>{if(!C||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)}},[C,c.sound,e]),(0,E.useEffect)(()=>{let e=()=>v(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,E.useEffect)(()=>{if(p)return()=>void i?.(!1)},[p,i]);let A=(0,E.useRef)(p);(0,E.useEffect)(()=>{A.current=p},[p]),(0,E.useEffect)(()=>{if(!t||!C||!mc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!A.current&&(m(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,C,i]),(0,E.useEffect)(()=>{if(!C)return;let e=e=>{e.key===`Escape`&&(de(),p&&m(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[C,p,de]),(0,E.useEffect)(()=>{if(!p||!mc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,m(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[p]),(0,E.useEffect)(()=>{if(!p||typeof document>`u`)return;let e=()=>{document.fullscreenElement||mc()||m(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[p]);let xe=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,B.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`,children:[l.kind===`connecting`&&o&&a&&(0,B.jsx)(nc,{href:a}),(0,B.jsx)(gc,{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:xe})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,B.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,children:[(0,B.jsx)(Se,{size:28,className:`text-white/60`}),(0,B.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:lc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,B.jsx)(nc,{href:a}),(0,B.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,B.jsx)(`button`,{type:`button`,onClick:r,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,B.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let Ce=l.player,M=c.light??it(Ce),Te=c.rttMs??u?.rttMs??null,Ee=rt(Te),De=mc(),Oe=C&&!S&&!y.ready&&De&&(!t||p),ke=oc({player:Ce,guided:h,movedOff:T,reconnecting:S}),Ae=Ce===ac,je=u?.playsAs??null,Me=S?(l.deadline-ee)/1e3:0,Ne=async()=>{let e=!p;m(e),await i?.(e)},Pe=t&&!p&&De&&C,Ie=(0,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${M[0]},${M[1]},${M[2]})`}}),t&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:Ce},`You are Player ${Ce}`)]}),Te!=null&&(0,B.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:hc[Ee]},"data-testid":`join-delay`,"data-tone":Ee,"data-path":c.path??void 0,children:[c.path&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[sc(s,c.path),` · `]}),Math.round(Te),` ms`]}),Ae&&(0,B.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.`)}),je&&!Ae&&(0,B.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:je},`You're playing as ${je}. No need to pick one.`)}),w&&!Ae&&u?.seatNote&&(0,B.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.`)}),w&&!Ae&&(0,B.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`)})]}),Le=(0,B.jsxs)(B.Fragment,{children:[D&&O&&ue.shown&&!S&&(0,B.jsxs)(`button`,{type:`button`,onClick:ue.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,B.jsx)(fe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,B.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,B.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,B.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,B.jsx)(N,{size:13}):(0,B.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,B.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,B.jsx)(N,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>void Ne(),"aria-label":p?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:p?(0,B.jsx)(be,{size:13}):(0,B.jsx)(k,{size:13})}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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,B.jsx)(me,{size:13})}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),Re=ue.shown?`opacity-100`:`pointer-events-none opacity-0`,ze={"data-testid":`join-bar`,"data-shown":ue.shown?`1`:`0`,onFocus:e=>{e.target.matches?.(`:focus-visible`)&&se(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||se(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&ae(!0)},onPointerLeave:()=>ae(!1)};return(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`${p||!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)]`} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},onPointerMove:e=>{if(e.pointerType===`mouse`)return de();let t=pe.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>pc&&he()},onPointerDown:e=>{if(fc(e.target))return;if(e.pointerType===`mouse`||!O)return de();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;he();let{pointerId:t,clientX:n,clientY:r}=e;pe.current={id:t,x:n,y:r,timer:setTimeout(()=>{pe.current=null,navigator.vibrate?.(15),ue.toggle()},450)}},onPointerUp:he,onPointerCancel:he,onPointerLeave:he,"data-testid":`join-stage-view`,children:[(0,B.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),D&&!ue.shown&&!S&&Te!=null&&(0,B.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:hc[Ee],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(Te),` ms`]}),Oe?(0,B.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 ${Re}`,...ze,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Ie}),(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Le})]}):Pe?null:(0,B.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 ${Re}`,...ze,children:[Ie,(0,B.jsx)(`span`,{className:`flex-1`}),Le]}),!ue.shown&&!Oe&&(0,B.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),de()},"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,B.jsx)(le,{size:16,"aria-hidden":!0})}),_e&&!ue.shown&&(0,B.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,B.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.`)}),b&&(0,B.jsx)(ec,{onClose:()=>x(!1)}),Oe&&(0,B.jsx)(os,{stream:e,layout:`overlay`,onMenu:()=>ue.shown?ue.hide():de()}),!Oe&&!S&&(0,B.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 ${Re}`,"data-testid":`join-pad`,children:[(0,B.jsx)(me,{size:14,style:{color:y.pressed?`rgb(${M[0]},${M[1]},${M[2]})`:void 0}}),y.ready?(0,B.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),y.weak8BitDo&&y.id&&(0,B.jsx)(Wo,{id:y.id,className:`text-amber-200/90`}),y.kind===`guess`&&to()&&(0,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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`)})]})]}):De&&t&&!p?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,B.jsxs)(`span`,{className:`flex flex-col`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,B.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.`)})]})]}),u?.blockSystem&&u.state===`playing`&&!Oe&&(0,B.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 ${Re}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),ce&&!Ae&&O&&!ue.shown&&!S&&(0,B.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`)}),ke&&!je&&(0,B.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,B.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,B.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,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>{Ft(ic,`1`),g(!0),ne(!1)},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`)})]}),S&&(0,B.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,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,B.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,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:rc(Me)},`The host stopped playing — waiting for them to start again (${rc(Me)})`)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:rc(Me)},`Your place is kept for ${rc(Me)}.`)})]})]}),!t&&C&&_&&De&&(0,B.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,B.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,B.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})})]}),Pe&&(0,B.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,B.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:Ie}),(0,B.jsxs)(`button`,{type:`button`,onClick:()=>void Ne(),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,B.jsx)(k,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,B.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,B.jsx)(N,{size:16}):(0,B.jsx)(we,{size:16})}):c.sound?null:(0,B.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,B.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var vc=`ps5upload.join.name`;function yc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function bc(e){return e.trim().slice(0,32)}function xc(e=``){return bc(It(`ps5upload.join.name`)??``)||e}function Sc(e){let t=bc(e);return t&&Ft(vc,t),t}function Cc(e){try{return!!sessionStorage.getItem(Lo(e))}catch{return!1}}async function wc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Tc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Fe(),c=tc(r&&o!==!1?e:null,i),[l,u]=(0,E.useState)(()=>xc(yc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(0),h=i=>{let s=Sc(i);if(!s)return;let c=new zs({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,E.useEffect)(()=>{!d&&Cc(t)&&l.trim()&&h(l)},[]),(0,E.useEffect)(()=>d?Hs(d):void 0,[d]),(0,E.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,B.jsx)(_c,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),h(l)},onFullscreen:wc},p);let g=n??s(`join_host_fallback`,void 0,`your friend`),_=(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,children:(0,B.jsxs)(`form`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),h(l)},children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,B.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,B.jsx)(Se,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:g},`Play on ${g}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,B.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,B.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,B.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,B.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,B.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,B.jsx)(nc,{href:i})]})});return t?(0,B.jsx)(Uo,{appLink:nt(location.href),children:_}):_}function Ec(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 Dc(e,t){let n=Ec(e),r=Ec(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Oc(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Ec(t);return n===0?`lan`:n===1?`tailscale`:null}function kc(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 Dc(a(i.localCandidateId),a(i.remoteCandidateId))}function Ac(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function jc(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 Mc(e,t){let n=jc(e);return n!==null&&n===t.toUpperCase()}var Nc=16777216;function Pc(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 Ic(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Lc=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Rc=1500,zc=2e4;function Bc(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 Vc=null;function Hc(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 Uc(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||Vc)return;let r=Ac(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};Vc=a;let o=()=>{Vc===a&&(Vc=null,a.timer&&clearTimeout(a.timer),Hc(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 Wc(e,t){let n=Vc;return n?(Vc=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`)?(Hc(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Gc(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 Fc,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??Ac(e.hub),a=t.signalUrl||t.lan?null:Wc(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:Lc}]})}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=Bc(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?!Mc(t.sdp,e.fp):jc(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(Ic(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 kc(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 Pc(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+zc,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()},Rc),!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(Ve,`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 Kc=3e3;function qc(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var Jc=e=>qc(e,`api/join/signal`);function Yc(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?Jc(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?qc(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var Xc=new Map;function Zc(e,t,n=300,r=Kc){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 Qc(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(He(e.e)??``));return t&&(He(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function $c(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=Zc(n.map(e=>e.via),Xc.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)&&He(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(Qc(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,Xc.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}var el=new URLSearchParams(location.hash.slice(1)),tl=el.get(`n`)?.trim()||null,nl=tt(location.hash);nl&&Uc(nl);var rl=(0,x.createRoot)(document.getElementById(`root`));if(nl){let e=Gc(nl,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Le(location.hash,`join`);rl.render((0,B.jsx)(Tc,{url:Ac(nl.hub),invite:nl.key,host:tl,transport:e,lanUrl:t?Re(t,{key:nl.key}):null}))}else{let e=el.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:$c(()=>Yc({net:null,lan:i,ts:null,fp:et(el.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>Gc(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});rl.render((0,B.jsx)(Tc,{url:n,invite:e,host:tl,path:Oc(location.hostname),transport:a,internet:!1}))} +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var T={a:v};this.setModule=t=>{e.setModule(yi,t)},this.getModule=()=>e.getModule(yi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,T)).then(e=>{let t=e.exports;y(t),a=t.g,o(),te(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 bi=o((()=>{}));function xi(e={}){xi.errors||Object.defineProperties(xi,{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+` `+(xi.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 Si=o((()=>{vi(),bi()})),Ci,wi=o((()=>{vi(),bi(),Si(),Ci=class extends mi{constructor(e){super(e,`opus-decoder`,xi,yi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ti=c({OpusDecoder:()=>xi,OpusDecoderWebWorker:()=>Ci}),Ei=o((()=>{Si(),wi(),vi(),gi(xi,`OpusDecoder`),gi(Ci,`OpusDecoderWebWorker`)})),Di=[8e3,12e3,16e3,24e3,48e3],Oi=null;function ki(){return Oi??=Yn(()=>Promise.resolve().then(()=>(Ei(),Ti)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw Oi=null,e}),Oi}function Ai(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function ji(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 Mi=class{constructor(e,t=ki){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(!Ai())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Di.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(ji(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{}}},Ni={makeDecoder:e=>new Mi(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Pi(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 Fi(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 Ii=[`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 Li(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Ii)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function Ri(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 zi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Bi(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 I(...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 Vi=(e,t,n,...r)=>Bi(e,I([t,1],[n,3]),...r),Hi=I([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Ui(e){let t=e.handler===`vide`,n=Bi(`ftyp`,new TextEncoder().encode(`isom`),I([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Bi(`moov`,Vi(`mvhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Hi,new Uint8Array(24),I([2,4])),Bi(`trak`,Vi(`tkhd`,0,3,I([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Hi,I([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Bi(`mdia`,Vi(`mdhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Vi(`hdlr`,0,0,I([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),I([0,1])),Bi(`minf`,t?Vi(`vmhd`,0,1,new Uint8Array(8)):Vi(`smhd`,0,0,I([0,4])),Bi(`dinf`,Vi(`dref`,0,0,I([1,4]),Vi(`url `,0,1))),Bi(`stbl`,Vi(`stsd`,0,0,I([1,4]),e.sampleEntry),Vi(`stts`,0,0,I([0,4])),Vi(`stsc`,0,0,I([0,4])),Vi(`stsz`,0,0,I([0,4],[0,4])),Vi(`stco`,0,0,I([0,4])))))),Bi(`mvex`,Vi(`trex`,0,0,I([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 Wi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Vi(`trun`,0,1793,I([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Bi(`traf`,Vi(`tfhd`,0,131072,I([1,4])),Vi(`tfdt`,1,0,I([t,8])),o(e)),c=Vi(`mfhd`,0,0,I([e,4])),l=Bi(`moof`,c,s(0)).length,u=Bi(`moof`,c,s(l+8)),d=Bi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Gi(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=Ri(e).filter(e=>!r.includes(zi(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 Ki=e=>e.toString(16).padStart(2,`0`),qi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Ji=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 Yi(e){let t=Ri(e),n=t.filter(e=>zi(e,!1)===7),r=t.filter(e=>zi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Ji([I([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(qi),I([r.length,1]),...r.map(qi)])}function Xi(e,t,n){let r=Ri(e),i=e=>r.filter(n=>zi(n,t)===e),a=(e,t)=>Bi(e,new Uint8Array(6),I([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),I([24,2],[65535,2]),t);if(!t){let t=i(7),r=Yi(e);return r?{init:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Bi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ki(t[0][1])}${Ki(t[0][2])}${Ki(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=Yr(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)=>Ji([I([128|e,1],[t.length,2]),...t.map(qi)]),m=Bi(`hvcC`,I([1,1]),u,I([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:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Zi(e,t,n,r,i,a){return Wi(e,t,n,Gi(r,i),a)}function Qi(e,t){let n=Bi(`dOps`,I([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Ui({handler:`soun`,timescale:48e3,sampleEntry:Bi(`Opus`,new Uint8Array(6),I([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function $i(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 ea(e,t,n){return Wi(e,t,$i(n),n,!0)}var ta={watch:30,player:4},na={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ra={seek:.8,speed:.25,target:.12};function ia(e,t,n){let r=typeof n==`string`?na[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 aa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ma(e,t,n):new Oa(e,t,n)}var oa=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 L(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var R=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 sa(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 ca(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var la=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+ua;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}},ua=.02;async function da(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var fa=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}},pa=[`pointerup`,`touchend`,`click`,`keydown`],ma=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():ca(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 fa(`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 oa(n),this.clock=new la(t===`player`?.05:.08),typeof AudioDecoder>`u`&&_a()&&(this.mseSound=new va(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=ti(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!ba())return!1;let e=new Oa(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,ha(),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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)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=ti(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await ka(e):Fi(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:Yi(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=ni(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=Pi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>ta[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=Gi(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];da(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return _a()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new oi((e,t)=>this.play(e,t,r.sampleRate));try{r.header(sa(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new va(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new oi((e,n)=>this.play(e,n,t.sampleRate),Ni,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(sa(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 ha(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ga(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function _a(){let e=typeof window>`u`?null:ba();return!!e&&(ga(e,`audio/mp4; codecs="Opus"`)||ga(e,`audio/mp4; codecs="opus"`))}var va=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 R,this.el=n,this.track=new wa(n,()=>this.fail(),e===`player`?ra: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=L(e);if(!t||!this.order.take(t.index))return;let n=ea(this.track.nextSeq(),this.time,t.packet);this.time+=$i(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=Qi(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())}},ya=class{constructor(e,t,n=Ni){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 la(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,ha();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 oi((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(sa(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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function ba(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var xa=10,Sa=3;function Ca(e,t,n,r=Sa){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var wa=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=ba();if(!n||!ga(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=Ta(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=ia(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>xa&&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-Sa;if(this.keys){if(r=Ca(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Sa&&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 Ta(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Ea=1e4,Da=class{constructor(e=3,t=Ea,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=[]}},Oa=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 fa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new oa(n),this.fails=new Da(3,Ea,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 va(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new wa(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(!_a())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ya(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?ca(`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=ti(e,this.hevc)??{w:1920,h:1080},r=Xi(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=Pi(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>ta[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(Zi(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 ka(e){let t=ri(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Li(1920,1080)}var z={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},Aa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function ja(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Ma={ArrowUp:{button:z.UP},ArrowDown:{button:z.DOWN},ArrowLeft:{button:z.LEFT},ArrowRight:{button:z.RIGHT},Enter:{button:z.CROSS},Space:{button:z.CROSS},Backspace:{button:z.CIRCLE},Escape:{button:z.CIRCLE},KeyQ:{button:z.SQUARE},KeyE:{button:z.TRIANGLE},KeyZ:{button:z.L1},KeyC:{button:z.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:z.L3},KeyG:{button:z.R3},Tab:{button:z.OPTIONS},Backquote:{button:z.SHARE},KeyH:{button:z.PS},KeyT:{button:z.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}};z.UP,z.DOWN,z.LEFT,z.RIGHT,z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD;var Na=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Pa(e,t=Ma){let n={...Aa};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Na(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Fa=[z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,0,0,z.SHARE,z.OPTIONS,z.L3,z.R3,z.UP,z.DOWN,z.LEFT,z.RIGHT,z.PS,z.TOUCHPAD];function Ia(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var La=[0,1,1,1,0,-1,-1,-1],Ra=[-1,-1,0,1,1,1,0,-1];function za(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ia(n);return e===null?0:(t.hat===`x`?La:Ra)[e]}return t.inv?-n:n}var Ba={buttons:Fa.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 Va(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=Ia(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 Ha(e){if(e.mapping===`standard`)return Ba;let t=Ua.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Ba;let r={...Ba,buttons:[...Ba.buttons,[z.UP,{h:n,at:0}],[z.RIGHT,{h:n,at:2}],[z.DOWN,{h:n,at:4}],[z.LEFT,{h:n,at:6}]]};return Ua.set(e.id,r),r}var Ua=new Map;function Wa(e,t=Ha){let n={...Aa},r=e=>Math.abs(e)<.08?0:Na(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(za(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Va(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Va(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Va(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 Ga(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Na(e.lx+t.lx),ly:Na(e.ly+t.ly),rx:Na(e.rx+t.rx),ry:Na(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function Ka(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 qa=new Map;function Ja(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 Ya(e){let t=e?.getGamepads?.()??[];return qa.size===0||t.some(e=>!!e?.connected)?[...t]:[...qa.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ja(e))}var Xa=`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(`(`),Za={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},Qa=e=>e.toLowerCase().padStart(4,`0`);function $a(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:Qa(t[2]),product:Qa(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:Qa(n[1]),product:Qa(n[2]),name:n[3].trim()}:null}function eo(e){return($a(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function to(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 no(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Za[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Xa[n]??null}return null}function ro(e){return e.mapping!==`standard`&&$a(e.id)?.vendor===`2dc8`}var io={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 ao(e){let t=$a(e);return t&&io[t.product]||`manual`}var oo={1:0,2:2,4:4,8:6};function so(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 co(e,t,n){let{n:r,hat:i}=so(t),a=Fa.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 lo(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=oo[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 uo(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 fo(e,t,n){let r=e.split(`,`),i=co(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`&&go(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(go)}function vo(){try{let e=It(ho),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>_o(e[1])))}catch{return{}}}function yo(e,t){let n=vo();return t?n[e]=t:delete n[e],Ft(ho,JSON.stringify(n)),bo=n,n}var bo=null;function xo(e){return bo??=vo(),bo[e.id]??wo(bo,e.id)??mo(e)??Ha(e)}function So(e){return bo??=vo(),bo[e.id]?`saved`:e.mapping===`standard`?`standard`:mo(e)?`known`:`guess`}function Co(e){return mo(e)??Ha(e)}function wo(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?(bo=yo(t,e[i]),e[i]):null}function To(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Eo(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?Ia(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 Do(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 Oo=[{kind:`button`,bit:z.CROSS,name:`✕`},{kind:`button`,bit:z.CIRCLE,name:`○`},{kind:`button`,bit:z.SQUARE,name:`□`},{kind:`button`,bit:z.TRIANGLE,name:`△`},{kind:`button`,bit:z.UP,name:`↑`},{kind:`button`,bit:z.DOWN,name:`↓`},{kind:`button`,bit:z.LEFT,name:`←`},{kind:`button`,bit:z.RIGHT,name:`→`},{kind:`button`,bit:z.L1,name:`L1`},{kind:`button`,bit:z.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:z.L3,name:`L3`},{kind:`button`,bit:z.R3,name:`R3`},{kind:`button`,bit:z.OPTIONS,name:`Options`},{kind:`button`,bit:z.SHARE,name:`Create`},{kind:`button`,bit:z.PS,name:`PS`},{kind:`button`,bit:z.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 ko(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function Ao(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 jo(e,t=Ba){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 Mo=Oo.filter(e=>e.kind!==`button`||![z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD].includes(e.bit));function No(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 Po=class{constructor(e=Oo){this.steps=e,this.step=0,this.prof=ko(),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 No(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Do(this.rest,e):Eo(this.rest,e);return n?(this.prof=Ao(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=Ba){return jo(this.prof,e)}};function Fo(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 Io(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Lo=e=>`ps5upload.join.token.${e??`app`}`,Ro=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...Aa},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?Io():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 Lo(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=He(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=qe(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()+$e),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()+$e,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()+Qe),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Ze(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?{...Aa,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Fo(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Xe(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(Xe(this.seq,Aa))),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(Xe(this.seq,Aa))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},zo=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})),B=s(((e,t)=>{t.exports=zo()}))(),Bo=`ps5upload.openIn`,Vo=`ps5upload.openIn.tab`;function Ho(){try{return sessionStorage.getItem(Vo)===`browser`}catch{return!1}}function V(){try{sessionStorage.setItem(Vo,`browser`)}catch{}}function H(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Uo({appLink:e,children:t}){let n=Fe(),[r,i]=(0,E.useState)(()=>Ho()?`browser`:H(It(Bo))),[a,o]=(0,E.useState)(!1);if((0,E.useEffect)(()=>{r===`opening`&&It(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,B.jsx)(B.Fragment,{children:t});let s=()=>{a&&Ft(Bo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?Ft(Bo,`browser`):r===`opening`&&It(`ps5upload.openIn`)===`app`&&Lt(Bo),V(),i(`browser`)};return(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,B.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,B.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,B.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,B.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,B.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,B.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,B.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 Wo({id:e,className:t}){let n=Fe(),r=ao(e);if(r===`none`)return(0,B.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,B.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 Go=new Set,Ko={held:new Set,touch:null,touchPad:Aa,mapping:!1,get paused(){return Go.size>0},motion:null},qo={s:.85,m:1,l:1.15},Jo=.25;function Yo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(Jo,e))}var Xo={overlay:{width:844,height:390},deck:{width:390,height:480}},Zo=.7,Qo=1.4;function $o(e,t,n,r){let i=qo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?Xo.deck:Xo.overlay,o=Math.min(Qo,Math.max(Zo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var es=34;function ts(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+es>t}function ns(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 rs=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,is=32767,as=12;function os({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Fe(),s=(0,E.useRef)(new Map),c=(0,E.useRef)({...Aa}),[l,u]=(0,E.useState)({...Aa}),[d,f]=(0,E.useState)({l:!1,r:!1,touchpad:!1}),p=(0,E.useRef)(null),[m,h]=(0,E.useState)({width:0,height:0});(0,E.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,E.useEffect)(()=>()=>{Ko.touchPad={...Aa}},[]);let g=()=>{let t={...Aa,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|=z.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,Ko.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*is),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*is)},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=ja((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=ja((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)>as&&(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)]`,te={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},T=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),ne=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,re={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ie=(e,t,n,r)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${ne} ${n}`,style:re,children:r}),ae=(e,t,n,r)=>(0,B.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}),oe=(e,t,n,r)=>ie(e,t,`h-[44px] w-[84px]`,ae(e,ee(t),n,r)),se=(e,t,n)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${ne} h-[44px] w-[84px]`,style:re,children:ae(e,l[t]>0,n,!0)}),D=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:(0,B.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...T(ee(t)),children:[(0,B.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,B.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),O=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:[(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...T(ee(t))}),(0,B.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),ce=(e,t)=>ie(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,B.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})),le=(e,t)=>ie(e,t,`h-[44px] w-[44px]`,(0,B.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),ue=e=>{let{dx:t,dy:n}=ns(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,B.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,B.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))`}})})},k=t===`deck`,de=$o(r,m.width,m.height,k),fe=e=>`${e}px * var(--k)`,pe=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=k?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${fe(t)}, ${n}px))`:`calc(${e} + ${fe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=k&&ts(de,m.height),A=k?void 0:`58%`,j=e=>k?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?pe:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?pe:me},xe=e=>({bottom:be?he:_e(he,k?56:0,44),[e]:be?`calc(${e===`left`?pe:me} + 8px + max(${fe(80)}, 44px))`:_e(e===`left`?pe:me,k?40:168)}),Se=!!a&&!k;return(0,B.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${k?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:k?i:void 0,"--k":de},"data-testid":`rp-touch`,"data-layout":t,"data-scale":de,onContextMenu:e=>e.preventDefault(),children:[(0,B.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:Yo(n)},children:[(0,B.jsx)(`div`,{style:ye(`top left`,{top:ge,left:pe}),children:(0,B.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:k?void 0:`6deg`,transformOrigin:`top left`},children:[se(`L2`,`l2`,`l`),oe(`L1`,z.L1,`l`,!1)]})}),(0,B.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,B.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:k?void 0:`-6deg`,transformOrigin:`top right`},children:[se(`R2`,`r2`,`r`),oe(`R1`,z.R1,`r`,!1)]})}),(0,B.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:k?{top:_e(ge,6),left:_e(pe,104),right:_e(me,104),height:`max(44px, calc(${fe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${fe(250)}), 34vw)`,height:`max(44px, calc(${fe(56)}))`}}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top left`:`left center`,j(`left`)),children:[(0,B.jsx)(`span`,{}),D(`↑`,z.UP,0),(0,B.jsx)(`span`,{}),D(`←`,z.LEFT,-90),(0,B.jsx)(`span`,{}),D(`→`,z.RIGHT,90),(0,B.jsx)(`span`,{}),D(`↓`,z.DOWN,180),(0,B.jsx)(`span`,{})]}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top right`:`right center`,j(`right`)),children:[(0,B.jsx)(`span`,{}),O(`△`,z.TRIANGLE,(0,B.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,B.jsx)(`span`,{}),O(`□`,z.SQUARE,(0,B.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,B.jsx)(`span`,{}),O(`○`,z.CIRCLE,(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,B.jsx)(`span`,{}),O(`✕`,z.CROSS,(0,B.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,B.jsx)(`span`,{})]}),(0,B.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:ue(`l`)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:ue(`r`)}),(0,B.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:pe}),children:ce(`Create`,z.SHARE)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:ce(`Options`,z.OPTIONS)}),(0,B.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:rs,translate:`-50% 0`}),children:le(`PS`,z.PS)})]}),Se&&(0,B.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,Yo(n))},children:(0,B.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:`${ne} h-[44px] w-[56px]`,style:re,"data-testid":`rp-menu-handle`,children:(0,B.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,B.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var ss=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,cs=null,ls=null;function us(e){e.play().catch(()=>{if(ls||cs!==e)return;let t=()=>{ds(),cs===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),ls=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function ds(){ls?.(),ls=null}function fs(){if(typeof document<`u`){if(!cs){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=ss,document.body.appendChild(e),cs=e}us(cs)}}function ps(){ds(),cs&&=(cs.pause(),cs.removeAttribute(`src`),cs.remove(),null)}function ms(){return typeof navigator>`u`?null:navigator.wakeLock??null}function hs(){return ut()||!Nn()}var gs=new Set,_s=null,vs=Promise.resolve(),ys=!1;async function bs(){if(gs.size===0||_s&&!_s.released)return;let e=ms();if(!e)ut()&&fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{_s===t&&(_s=null)}),_s=t}catch{}}async function xs(){ps();let e=_s;if(_s=null,e&&!e.released)try{await e.release()}catch{}}function Ss(){ys||typeof document>`u`||(ys=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&gs.size>0&&(vs=vs.then(bs))}))}function Cs(e,t){if(!hs())return;Ss();let n=gs.size>0;t?gs.add(e):gs.delete(e);let r=gs.size>0;n!==r&&(vs=vs.then(r?bs:xs))}var ws=new Set;function Ts(){if(typeof window<`u`)return window.PS5UploadPad}function Es(e,t){let n=ws.size>0;t?ws.add(e):ws.delete(e);let r=ws.size>0;if(n!==r)try{Ts()?.setActive(r)}catch{}}var Ds=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}},Os=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 Ds(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}},ks=`ps5upload.join.muted`,As=5e3,js=Object.fromEntries(Object.entries(Ma).filter(([e])=>e!==`Escape`)),Ms=new Set;function Ns(e){if(!(e.code in js)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||Ps(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||Ps(t))}function Ps(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 Fs=!1;function Is(e){Fs=e}function Ls(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function Rs(){if(Fs)return{...Aa};let e=Wa(Ya(typeof navigator>`u`?void 0:navigator),xo),t=Ko.touchPad;return{...Ga(Ga(e,Pa(Ms,js)),t),touch:t.touch??null,motion:Ko.motion??null}}var zs=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:Vs(),path:null},this.client=new Ro({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:Rs,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:()=>Ls(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Os&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Ya(typeof navigator>`u`?void 0:navigator);Ka(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=aa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Os(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`?Ms.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{Ms.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&Ns(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),Ms.add(e.code))},r=e=>{Ms.delete(e.code)&&Ns(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()},As);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),Ms.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(ks,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();Ko.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 Bs(e){return(0,E.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function Vs(){try{return typeof localStorage<`u`&&localStorage.getItem(ks)===`1`}catch{return!1}}function Hs(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Cs(`play-together`,n),Es(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Cs(`play-together`,!1),Es(`play-together`,!1)}}var Us=3e3,Ws=class{constructor(e,t=Us){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 Gs(e,t,n=!1){let[r,i]=(0,E.useState)(!0),a=(0,E.useRef)(null);(0,E.useEffect)(()=>{let e=new Ws(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,E.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,E.useCallback)(()=>a.current?.poke(),[]),s=(0,E.useCallback)(()=>a.current?.hide(),[]),c=(0,E.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var Ks=3e4,qs=class{constructor(e,t=Ks){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 Js(e){let[,t]=(0,E.useState)(0),[n]=(0,E.useState)(()=>new qs(()=>t(e=>e+1)));return(0,E.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,E.useEffect)(()=>()=>n.reset(),[n]),n.shown}var Ys=()=>Ya(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function Xs(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===z.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===z.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===z.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===z.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 Zs(e,t){let n=(0,E.useRef)(t);(0,E.useEffect)(()=>{n.current=t}),(0,E.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(Ys().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var Qs=[[z.CROSS,`✕`],[z.CIRCLE,`○`],[z.SQUARE,`□`],[z.TRIANGLE,`△`],[z.UP,`↑`],[z.DOWN,`↓`],[z.LEFT,`←`],[z.RIGHT,`→`],[z.L1,`L1`],[z.R1,`R1`],[z.L3,`L3`],[z.R3,`R3`],[z.SHARE,`Create`],[z.OPTIONS,`Options`],[z.PS,`PS`],[z.TOUCHPAD,`Touchpad`]];function $s({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,B.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,B.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,B.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[Qs.map(([n,r])=>(0,B.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,B.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,B.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,B.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function ec({onClose:e}){let t=Fe(),[n,r]=(0,E.useState)(()=>Ys().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,E.useState)(()=>Ys()[0]?.index??null),[o,s]=(0,E.useState)(Aa),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(0),[f,p]=(0,E.useState)(vo),[m,h]=(0,E.useState)(null),[g,_]=(0,E.useState)(null);(0,E.useEffect)(()=>(Is(!0),()=>Is(!1)),[]),(0,E.useEffect)(()=>{let e=()=>{let e=Ys();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)}},[]),Zs(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(To(e))&&v(c,e);return}let t=Wa([e],xo);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 v=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(yo(r,e.profile(n?Co(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},y=()=>{h(null),d(0),l(new Po(Mo))},b=g,x=b?So(b):null,S=!!(b&&f[b.id]);return(0,B.jsx)(`div`,{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,B.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,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(me,{size:16,className:`text-white/70`}),(0,B.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,B.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,B.jsx)(Ee,{size:15})})]}),b?(0,B.jsxs)(B.Fragment,{children:[n.length>1&&(0,B.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,B.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:eo(e.id)},`${e.index}-${e.id}`))}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:eo(b.id)}),(0,B.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":x??``,children:x===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):x===`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`)}),ro(b)&&(0,B.jsx)(Wo,{id:b.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,B.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,B.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,B.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?Xs(t,c.current):``}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),v(c,b)},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,B.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,B.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,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)($s,{pad:o}),m&&(0,B.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:y,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:S?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),S&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>{p(yo(b.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,B.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,B.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 tc(e,t){let[n,r]=(0,E.useState)(!1);return(0,E.useEffect)(()=>{if(!e||!t)return;let n=!0;return ze(e,Ie).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function nc({href:e}){let t=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,B.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,B.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 rc(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var ic=`ps5upload.join.guided`,ac=1;function oc(e){return e.player!==ac&&(!e.guided||e.movedOff)&&!e.reconnecting}function sc(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 cc(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 lc(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 cc(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 cc(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 uc(e){let[t,n]=(0,E.useState)(()=>Date.now());return(0,E.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function dc(){let[e,t]=(0,E.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,E.useEffect)(()=>{let e=()=>{let e=Ya(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?Rs():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?So(e):null,s=!!e&&ro(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 pc=14,mc=()=>typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,hc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function gc({text:e,body:t,onCancel:n}){let r=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,B.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,B.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,B.jsx)(Se,{size:26})})]}),(0,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,B.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,B.jsx)(`button`,{type:`button`,onClick:n,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 _c({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Fe(),c=Bs(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,E.useRef)(null),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(()=>It(ic)===`1`),[_,v]=(0,E.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),y=dc(),[b,x]=(0,E.useState)(!1),S=l.kind===`reconnecting`,ee=uc(S),C=l.kind===`joined`||S,w=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[T,ne]=(0,E.useState)(!1),re=(0,E.useRef)(te);(0,E.useEffect)(()=>{re.current===ac&&te>ac&&ne(!0),te&&(re.current=te)},[te]);let[ie,ae]=(0,E.useState)(!1),[oe,se]=(0,E.useState)(!1),D=C&&(p||!t),O=mc(),ce=Js(w),ue=Gs(D,S||ce&&!O||ie||oe,O),{poke:de}=ue,pe=(0,E.useRef)(null),he=()=>{pe.current&&clearTimeout(pe.current.timer),pe.current=null};(0,E.useEffect)(()=>he,[]);let[_e,ve]=(0,E.useState)(!1),ye=(0,E.useRef)(!1);(0,E.useEffect)(()=>{if(!D||!O||ue.shown||!h||ye.current)return;ye.current=!0,ve(!0);let e=setTimeout(()=>ve(!1),6e3);return()=>clearTimeout(e)},[D,O,ue.shown,h]),(0,E.useEffect)(()=>{if(!C)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[C,e]),(0,E.useEffect)(()=>{if(!C||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)}},[C,c.sound,e]),(0,E.useEffect)(()=>{let e=()=>v(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,E.useEffect)(()=>{if(p)return()=>void i?.(!1)},[p,i]);let A=(0,E.useRef)(p);(0,E.useEffect)(()=>{A.current=p},[p]),(0,E.useEffect)(()=>{if(!t||!C||!mc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!A.current&&(m(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,C,i]),(0,E.useEffect)(()=>{if(!C)return;let e=e=>{e.key===`Escape`&&(de(),p&&m(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[C,p,de]),(0,E.useEffect)(()=>{if(!p||!mc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,m(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[p]),(0,E.useEffect)(()=>{if(!p||typeof document>`u`)return;let e=()=>{document.fullscreenElement||mc()||m(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[p]);let xe=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,B.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`,children:[l.kind===`connecting`&&o&&a&&(0,B.jsx)(nc,{href:a}),(0,B.jsx)(gc,{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:xe})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,B.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,children:[(0,B.jsx)(Se,{size:28,className:`text-white/60`}),(0,B.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:lc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,B.jsx)(nc,{href:a}),(0,B.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,B.jsx)(`button`,{type:`button`,onClick:r,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,B.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let Ce=l.player,M=c.light??it(Ce),Te=c.rttMs??u?.rttMs??null,Ee=rt(Te),De=mc(),Oe=C&&!S&&!y.ready&&De&&(!t||p),ke=oc({player:Ce,guided:h,movedOff:T,reconnecting:S}),Ae=Ce===ac,je=u?.playsAs??null,Me=S?(l.deadline-ee)/1e3:0,Ne=async()=>{let e=!p;m(e),await i?.(e)},Pe=t&&!p&&De&&C,Ie=(0,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${M[0]},${M[1]},${M[2]})`}}),t&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:Ce},`You are Player ${Ce}`)]}),Te!=null&&(0,B.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:hc[Ee]},"data-testid":`join-delay`,"data-tone":Ee,"data-path":c.path??void 0,children:[c.path&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[sc(s,c.path),` · `]}),Math.round(Te),` ms`]}),Ae&&(0,B.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.`)}),je&&!Ae&&(0,B.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:je},`You're playing as ${je}. No need to pick one.`)}),w&&!Ae&&u?.seatNote&&(0,B.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.`)}),w&&!Ae&&(0,B.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`)})]}),Le=(0,B.jsxs)(B.Fragment,{children:[D&&O&&ue.shown&&!S&&(0,B.jsxs)(`button`,{type:`button`,onClick:ue.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,B.jsx)(fe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,B.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,B.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,B.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,B.jsx)(N,{size:13}):(0,B.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,B.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,B.jsx)(N,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>void Ne(),"aria-label":p?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:p?(0,B.jsx)(be,{size:13}):(0,B.jsx)(k,{size:13})}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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,B.jsx)(me,{size:13})}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),Re=ue.shown?`opacity-100`:`pointer-events-none opacity-0`,ze={"data-testid":`join-bar`,"data-shown":ue.shown?`1`:`0`,onFocus:e=>{e.target.matches?.(`:focus-visible`)&&se(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||se(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&ae(!0)},onPointerLeave:()=>ae(!1)};return(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`${p||!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)]`} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},onPointerMove:e=>{if(e.pointerType===`mouse`)return de();let t=pe.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>pc&&he()},onPointerDown:e=>{if(fc(e.target))return;if(e.pointerType===`mouse`||!O)return de();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;he();let{pointerId:t,clientX:n,clientY:r}=e;pe.current={id:t,x:n,y:r,timer:setTimeout(()=>{pe.current=null,navigator.vibrate?.(15),ue.toggle()},450)}},onPointerUp:he,onPointerCancel:he,onPointerLeave:he,"data-testid":`join-stage-view`,children:[(0,B.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),D&&!ue.shown&&!S&&Te!=null&&(0,B.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:hc[Ee],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(Te),` ms`]}),Oe?(0,B.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 ${Re}`,...ze,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Ie}),(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Le})]}):Pe?null:(0,B.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 ${Re}`,...ze,children:[Ie,(0,B.jsx)(`span`,{className:`flex-1`}),Le]}),!ue.shown&&!Oe&&(0,B.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),de()},"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,B.jsx)(le,{size:16,"aria-hidden":!0})}),_e&&!ue.shown&&(0,B.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,B.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.`)}),b&&(0,B.jsx)(ec,{onClose:()=>x(!1)}),Oe&&(0,B.jsx)(os,{stream:e,layout:`overlay`,onMenu:()=>ue.shown?ue.hide():de()}),!Oe&&!S&&(0,B.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 ${Re}`,"data-testid":`join-pad`,children:[(0,B.jsx)(me,{size:14,style:{color:y.pressed?`rgb(${M[0]},${M[1]},${M[2]})`:void 0}}),y.ready?(0,B.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),y.weak8BitDo&&y.id&&(0,B.jsx)(Wo,{id:y.id,className:`text-amber-200/90`}),y.kind===`guess`&&to()&&(0,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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`)})]})]}):De&&t&&!p?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,B.jsxs)(`span`,{className:`flex flex-col`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,B.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.`)})]})]}),u?.blockSystem&&u.state===`playing`&&!Oe&&(0,B.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 ${Re}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),ce&&!Ae&&O&&!ue.shown&&!S&&(0,B.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`)}),ke&&!je&&(0,B.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,B.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,B.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,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>{Ft(ic,`1`),g(!0),ne(!1)},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`)})]}),S&&(0,B.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,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,B.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,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:rc(Me)},`The host stopped playing — waiting for them to start again (${rc(Me)})`)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:rc(Me)},`Your place is kept for ${rc(Me)}.`)})]})]}),!t&&C&&_&&De&&(0,B.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,B.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,B.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})})]}),Pe&&(0,B.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,B.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:Ie}),(0,B.jsxs)(`button`,{type:`button`,onClick:()=>void Ne(),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,B.jsx)(k,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,B.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,B.jsx)(N,{size:16}):(0,B.jsx)(we,{size:16})}):c.sound?null:(0,B.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,B.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var vc=`ps5upload.join.name`;function yc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function bc(e){return e.trim().slice(0,32)}function xc(e=``){return bc(It(`ps5upload.join.name`)??``)||e}function Sc(e){let t=bc(e);return t&&Ft(vc,t),t}function Cc(e){try{return!!sessionStorage.getItem(Lo(e))}catch{return!1}}async function wc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Tc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Fe(),c=tc(r&&o!==!1?e:null,i),[l,u]=(0,E.useState)(()=>xc(yc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(0),h=i=>{let s=Sc(i);if(!s)return;let c=new zs({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,E.useEffect)(()=>{!d&&Cc(t)&&l.trim()&&h(l)},[]),(0,E.useEffect)(()=>d?Hs(d):void 0,[d]),(0,E.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,B.jsx)(_c,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),h(l)},onFullscreen:wc},p);let g=n??s(`join_host_fallback`,void 0,`your friend`),_=(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,children:(0,B.jsxs)(`form`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),h(l)},children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,B.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,B.jsx)(Se,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:g},`Play on ${g}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,B.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,B.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,B.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,B.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,B.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,B.jsx)(nc,{href:i})]})});return t?(0,B.jsx)(Uo,{appLink:nt(location.href),children:_}):_}function Ec(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 Dc(e,t){let n=Ec(e),r=Ec(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Oc(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Ec(t);return n===0?`lan`:n===1?`tailscale`:null}function kc(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 Dc(a(i.localCandidateId),a(i.remoteCandidateId))}function Ac(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function jc(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 Mc(e,t){let n=jc(e);return n!==null&&n===t.toUpperCase()}var Nc=16777216;function Pc(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 Ic(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Lc=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Rc=1500,zc=2e4;function Bc(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 Vc=null;function Hc(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 Uc(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||Vc)return;let r=Ac(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};Vc=a;let o=()=>{Vc===a&&(Vc=null,a.timer&&clearTimeout(a.timer),Hc(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 Wc(e,t){let n=Vc;return n?(Vc=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`)?(Hc(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Gc(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 Fc,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??Ac(e.hub),a=t.signalUrl||t.lan?null:Wc(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:Lc}]})}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=Bc(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?!Mc(t.sdp,e.fp):jc(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(Ic(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 kc(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 Pc(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+zc,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()},Rc),!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(Ve,`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 Kc=3e3;function qc(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var Jc=e=>qc(e,`api/join/signal`);function Yc(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?Jc(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?qc(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var Xc=new Map;function Zc(e,t,n=300,r=Kc){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 Qc(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(He(e.e)??``));return t&&(He(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function $c(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=Zc(n.map(e=>e.via),Xc.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)&&He(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(Qc(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,Xc.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}var el=new URLSearchParams(location.hash.slice(1)),tl=el.get(`n`)?.trim()||null,nl=tt(location.hash);nl&&Uc(nl);var rl=(0,x.createRoot)(document.getElementById(`root`));if(nl){let e=Gc(nl,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Le(location.hash,`join`);rl.render((0,B.jsx)(Tc,{url:Ac(nl.hub),invite:nl.key,host:tl,transport:e,lanUrl:t?Re(t,{key:nl.key}):null}))}else{let e=el.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:$c(()=>Yc({net:null,lan:i,ts:null,fp:et(el.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>Gc(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});rl.render((0,B.jsx)(Tc,{url:n,invite:e,host:tl,path:Oc(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 d9893367e..c35b03638 100644 --- a/engine/crates/ps5upload-engine/src/pad_page.html +++ b/engine/crates/ps5upload-engine/src/pad_page.html @@ -268,7 +268,7 @@ ã/¸Ä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.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)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)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.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(){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`,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})}))} diff --git a/site/join/index.html b/site/join/index.html index 90639f109..b260f68a4 100644 --- a/site/join/index.html +++ b/site/join/index.html @@ -268,7 +268,7 @@ ã/¸Ä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 T={a:v};this.setModule=t=>{e.setModule(yi,t)},this.getModule=()=>e.getModule(yi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,T)).then(e=>{let t=e.exports;y(t),a=t.g,o(),te(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 bi=o((()=>{}));function xi(e={}){xi.errors||Object.defineProperties(xi,{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+` `+(xi.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 Si=o((()=>{vi(),bi()})),Ci,wi=o((()=>{vi(),bi(),Si(),Ci=class extends mi{constructor(e){super(e,`opus-decoder`,xi,yi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ti=c({OpusDecoder:()=>xi,OpusDecoderWebWorker:()=>Ci}),Ei=o((()=>{Si(),wi(),vi(),gi(xi,`OpusDecoder`),gi(Ci,`OpusDecoderWebWorker`)})),Di=[8e3,12e3,16e3,24e3,48e3],Oi=null;function ki(){return Oi??=Yn(()=>Promise.resolve().then(()=>(Ei(),Ti)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw Oi=null,e}),Oi}function Ai(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function ji(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 Mi=class{constructor(e,t=ki){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(!Ai())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Di.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(ji(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{}}},Ni={makeDecoder:e=>new Mi(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Pi(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 Fi(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 Ii=[`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 Li(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Ii)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function Ri(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 zi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Bi(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 I(...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 Vi=(e,t,n,...r)=>Bi(e,I([t,1],[n,3]),...r),Hi=I([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Ui(e){let t=e.handler===`vide`,n=Bi(`ftyp`,new TextEncoder().encode(`isom`),I([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Bi(`moov`,Vi(`mvhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Hi,new Uint8Array(24),I([2,4])),Bi(`trak`,Vi(`tkhd`,0,3,I([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Hi,I([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Bi(`mdia`,Vi(`mdhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Vi(`hdlr`,0,0,I([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),I([0,1])),Bi(`minf`,t?Vi(`vmhd`,0,1,new Uint8Array(8)):Vi(`smhd`,0,0,I([0,4])),Bi(`dinf`,Vi(`dref`,0,0,I([1,4]),Vi(`url `,0,1))),Bi(`stbl`,Vi(`stsd`,0,0,I([1,4]),e.sampleEntry),Vi(`stts`,0,0,I([0,4])),Vi(`stsc`,0,0,I([0,4])),Vi(`stsz`,0,0,I([0,4],[0,4])),Vi(`stco`,0,0,I([0,4])))))),Bi(`mvex`,Vi(`trex`,0,0,I([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 Wi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Vi(`trun`,0,1793,I([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Bi(`traf`,Vi(`tfhd`,0,131072,I([1,4])),Vi(`tfdt`,1,0,I([t,8])),o(e)),c=Vi(`mfhd`,0,0,I([e,4])),l=Bi(`moof`,c,s(0)).length,u=Bi(`moof`,c,s(l+8)),d=Bi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Gi(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=Ri(e).filter(e=>!r.includes(zi(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 Ki=e=>e.toString(16).padStart(2,`0`),qi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Ji=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 Yi(e){let t=Ri(e),n=t.filter(e=>zi(e,!1)===7),r=t.filter(e=>zi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Ji([I([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(qi),I([r.length,1]),...r.map(qi)])}function Xi(e,t,n){let r=Ri(e),i=e=>r.filter(n=>zi(n,t)===e),a=(e,t)=>Bi(e,new Uint8Array(6),I([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),I([24,2],[65535,2]),t);if(!t){let t=i(7),r=Yi(e);return r?{init:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Bi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ki(t[0][1])}${Ki(t[0][2])}${Ki(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=Yr(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)=>Ji([I([128|e,1],[t.length,2]),...t.map(qi)]),m=Bi(`hvcC`,I([1,1]),u,I([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:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Zi(e,t,n,r,i,a){return Wi(e,t,n,Gi(r,i),a)}function Qi(e,t){let n=Bi(`dOps`,I([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Ui({handler:`soun`,timescale:48e3,sampleEntry:Bi(`Opus`,new Uint8Array(6),I([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function $i(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 ea(e,t,n){return Wi(e,t,$i(n),n,!0)}var ta={watch:30,player:4},na={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ra={seek:.8,speed:.25,target:.12};function ia(e,t,n){let r=typeof n==`string`?na[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 aa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ma(e,t,n):new Oa(e,t,n)}var oa=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 L(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var R=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 sa(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 ca(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var la=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+ua;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}},ua=.02;async function da(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var fa=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}},pa=[`pointerup`,`touchend`,`click`,`keydown`],ma=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():ca(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.sawKey=!1,this.ownStats=new fa(`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 oa(n),this.clock=new la(t===`player`?.05:.08),typeof AudioDecoder>`u`&&_a()&&(this.mseSound=new va(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=ti(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!ba())return!1;let e=new Oa(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,ha(),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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}onMessage(e){let t=new Uint8Array(e);if(t.length<1)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=ti(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await ka(e):Fi(e);if(this.mse)return;if(!t){this.problemShown=!0,this.onProblem(`no_hevc`);return}this.ownStats.codec=t;let n=this.hevc?void 0:Yi(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=ni(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.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=Pi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>ta[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=Gi(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];da(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return _a()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new oi((e,t)=>this.play(e,t,r.sampleRate));try{r.header(sa(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new va(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new oi((e,n)=>this.play(e,n,t.sampleRate),Ni,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(sa(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(){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 ha(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ga(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function _a(){let e=typeof window>`u`?null:ba();return!!e&&(ga(e,`audio/mp4; codecs="Opus"`)||ga(e,`audio/mp4; codecs="opus"`))}var va=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 R,this.el=n,this.track=new wa(n,()=>this.fail(),e===`player`?ra: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=L(e);if(!t||!this.order.take(t.index))return;let n=ea(this.track.nextSeq(),this.time,t.packet);this.time+=$i(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=Qi(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())}},ya=class{constructor(e,t,n=Ni){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 la(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,ha();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 oi((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(sa(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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function ba(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var xa=10,Sa=3;function Ca(e,t,n,r=Sa){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var wa=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=ba();if(!n||!ga(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=Ta(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=ia(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>xa&&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-Sa;if(this.keys){if(r=Ca(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Sa&&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 Ta(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Ea=1e4,Da=class{constructor(e=3,t=Ea,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=[]}},Oa=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 fa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new oa(n),this.fails=new Da(3,Ea,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 va(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new wa(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(!_a())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ya(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?ca(`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=ti(e,this.hevc)??{w:1920,h:1080},r=Xi(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=Pi(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>ta[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(Zi(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 ka(e){let t=ri(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Li(1920,1080)}var z={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},Aa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function ja(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Ma={ArrowUp:{button:z.UP},ArrowDown:{button:z.DOWN},ArrowLeft:{button:z.LEFT},ArrowRight:{button:z.RIGHT},Enter:{button:z.CROSS},Space:{button:z.CROSS},Backspace:{button:z.CIRCLE},Escape:{button:z.CIRCLE},KeyQ:{button:z.SQUARE},KeyE:{button:z.TRIANGLE},KeyZ:{button:z.L1},KeyC:{button:z.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:z.L3},KeyG:{button:z.R3},Tab:{button:z.OPTIONS},Backquote:{button:z.SHARE},KeyH:{button:z.PS},KeyT:{button:z.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}};z.UP,z.DOWN,z.LEFT,z.RIGHT,z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD;var Na=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Pa(e,t=Ma){let n={...Aa};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Na(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Fa=[z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,0,0,z.SHARE,z.OPTIONS,z.L3,z.R3,z.UP,z.DOWN,z.LEFT,z.RIGHT,z.PS,z.TOUCHPAD];function Ia(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var La=[0,1,1,1,0,-1,-1,-1],Ra=[-1,-1,0,1,1,1,0,-1];function za(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ia(n);return e===null?0:(t.hat===`x`?La:Ra)[e]}return t.inv?-n:n}var Ba={buttons:Fa.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 Va(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=Ia(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 Ha(e){if(e.mapping===`standard`)return Ba;let t=Ua.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Ba;let r={...Ba,buttons:[...Ba.buttons,[z.UP,{h:n,at:0}],[z.RIGHT,{h:n,at:2}],[z.DOWN,{h:n,at:4}],[z.LEFT,{h:n,at:6}]]};return Ua.set(e.id,r),r}var Ua=new Map;function Wa(e,t=Ha){let n={...Aa},r=e=>Math.abs(e)<.08?0:Na(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(za(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Va(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Va(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Va(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 Ga(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Na(e.lx+t.lx),ly:Na(e.ly+t.ly),rx:Na(e.rx+t.rx),ry:Na(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function Ka(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 qa=new Map;function Ja(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 Ya(e){let t=e?.getGamepads?.()??[];return qa.size===0||t.some(e=>!!e?.connected)?[...t]:[...qa.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ja(e))}var Xa=`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(`(`),Za={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},Qa=e=>e.toLowerCase().padStart(4,`0`);function $a(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:Qa(t[2]),product:Qa(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:Qa(n[1]),product:Qa(n[2]),name:n[3].trim()}:null}function eo(e){return($a(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function to(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 no(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Za[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Xa[n]??null}return null}function ro(e){return e.mapping!==`standard`&&$a(e.id)?.vendor===`2dc8`}var io={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 ao(e){let t=$a(e);return t&&io[t.product]||`manual`}var oo={1:0,2:2,4:4,8:6};function so(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 co(e,t,n){let{n:r,hat:i}=so(t),a=Fa.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 lo(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=oo[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 uo(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 fo(e,t,n){let r=e.split(`,`),i=co(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`&&go(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(go)}function vo(){try{let e=It(ho),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>_o(e[1])))}catch{return{}}}function yo(e,t){let n=vo();return t?n[e]=t:delete n[e],Ft(ho,JSON.stringify(n)),bo=n,n}var bo=null;function xo(e){return bo??=vo(),bo[e.id]??wo(bo,e.id)??mo(e)??Ha(e)}function So(e){return bo??=vo(),bo[e.id]?`saved`:e.mapping===`standard`?`standard`:mo(e)?`known`:`guess`}function Co(e){return mo(e)??Ha(e)}function wo(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?(bo=yo(t,e[i]),e[i]):null}function To(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Eo(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?Ia(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 Do(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 Oo=[{kind:`button`,bit:z.CROSS,name:`✕`},{kind:`button`,bit:z.CIRCLE,name:`○`},{kind:`button`,bit:z.SQUARE,name:`□`},{kind:`button`,bit:z.TRIANGLE,name:`△`},{kind:`button`,bit:z.UP,name:`↑`},{kind:`button`,bit:z.DOWN,name:`↓`},{kind:`button`,bit:z.LEFT,name:`←`},{kind:`button`,bit:z.RIGHT,name:`→`},{kind:`button`,bit:z.L1,name:`L1`},{kind:`button`,bit:z.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:z.L3,name:`L3`},{kind:`button`,bit:z.R3,name:`R3`},{kind:`button`,bit:z.OPTIONS,name:`Options`},{kind:`button`,bit:z.SHARE,name:`Create`},{kind:`button`,bit:z.PS,name:`PS`},{kind:`button`,bit:z.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 ko(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function Ao(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 jo(e,t=Ba){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 Mo=Oo.filter(e=>e.kind!==`button`||![z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD].includes(e.bit));function No(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 Po=class{constructor(e=Oo){this.steps=e,this.step=0,this.prof=ko(),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 No(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Do(this.rest,e):Eo(this.rest,e);return n?(this.prof=Ao(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=Ba){return jo(this.prof,e)}};function Fo(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 Io(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Lo=e=>`ps5upload.join.token.${e??`app`}`,Ro=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...Aa},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?Io():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 Lo(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=He(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=qe(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()+$e),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()+$e,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()+Qe),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Ze(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?{...Aa,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Fo(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Xe(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(Xe(this.seq,Aa))),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(Xe(this.seq,Aa))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},zo=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})),B=s(((e,t)=>{t.exports=zo()}))(),Bo=`ps5upload.openIn`,Vo=`ps5upload.openIn.tab`;function Ho(){try{return sessionStorage.getItem(Vo)===`browser`}catch{return!1}}function V(){try{sessionStorage.setItem(Vo,`browser`)}catch{}}function H(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Uo({appLink:e,children:t}){let n=Fe(),[r,i]=(0,E.useState)(()=>Ho()?`browser`:H(It(Bo))),[a,o]=(0,E.useState)(!1);if((0,E.useEffect)(()=>{r===`opening`&&It(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,B.jsx)(B.Fragment,{children:t});let s=()=>{a&&Ft(Bo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?Ft(Bo,`browser`):r===`opening`&&It(`ps5upload.openIn`)===`app`&&Lt(Bo),V(),i(`browser`)};return(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,B.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,B.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,B.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,B.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,B.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,B.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,B.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 Wo({id:e,className:t}){let n=Fe(),r=ao(e);if(r===`none`)return(0,B.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,B.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 Go=new Set,Ko={held:new Set,touch:null,touchPad:Aa,mapping:!1,get paused(){return Go.size>0},motion:null},qo={s:.85,m:1,l:1.15},Jo=.25;function Yo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(Jo,e))}var Xo={overlay:{width:844,height:390},deck:{width:390,height:480}},Zo=.7,Qo=1.4;function $o(e,t,n,r){let i=qo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?Xo.deck:Xo.overlay,o=Math.min(Qo,Math.max(Zo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var es=34;function ts(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+es>t}function ns(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 rs=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,is=32767,as=12;function os({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Fe(),s=(0,E.useRef)(new Map),c=(0,E.useRef)({...Aa}),[l,u]=(0,E.useState)({...Aa}),[d,f]=(0,E.useState)({l:!1,r:!1,touchpad:!1}),p=(0,E.useRef)(null),[m,h]=(0,E.useState)({width:0,height:0});(0,E.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,E.useEffect)(()=>()=>{Ko.touchPad={...Aa}},[]);let g=()=>{let t={...Aa,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|=z.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,Ko.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*is),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*is)},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=ja((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=ja((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)>as&&(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)]`,te={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},T=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),ne=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,re={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ie=(e,t,n,r)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${ne} ${n}`,style:re,children:r}),ae=(e,t,n,r)=>(0,B.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}),oe=(e,t,n,r)=>ie(e,t,`h-[44px] w-[84px]`,ae(e,ee(t),n,r)),se=(e,t,n)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${ne} h-[44px] w-[84px]`,style:re,children:ae(e,l[t]>0,n,!0)}),D=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:(0,B.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...T(ee(t)),children:[(0,B.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,B.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),O=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:[(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...T(ee(t))}),(0,B.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),ce=(e,t)=>ie(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,B.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})),le=(e,t)=>ie(e,t,`h-[44px] w-[44px]`,(0,B.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),ue=e=>{let{dx:t,dy:n}=ns(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,B.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,B.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))`}})})},k=t===`deck`,de=$o(r,m.width,m.height,k),fe=e=>`${e}px * var(--k)`,pe=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=k?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${fe(t)}, ${n}px))`:`calc(${e} + ${fe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=k&&ts(de,m.height),A=k?void 0:`58%`,j=e=>k?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?pe:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?pe:me},xe=e=>({bottom:be?he:_e(he,k?56:0,44),[e]:be?`calc(${e===`left`?pe:me} + 8px + max(${fe(80)}, 44px))`:_e(e===`left`?pe:me,k?40:168)}),Se=!!a&&!k;return(0,B.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${k?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:k?i:void 0,"--k":de},"data-testid":`rp-touch`,"data-layout":t,"data-scale":de,onContextMenu:e=>e.preventDefault(),children:[(0,B.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:Yo(n)},children:[(0,B.jsx)(`div`,{style:ye(`top left`,{top:ge,left:pe}),children:(0,B.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:k?void 0:`6deg`,transformOrigin:`top left`},children:[se(`L2`,`l2`,`l`),oe(`L1`,z.L1,`l`,!1)]})}),(0,B.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,B.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:k?void 0:`-6deg`,transformOrigin:`top right`},children:[se(`R2`,`r2`,`r`),oe(`R1`,z.R1,`r`,!1)]})}),(0,B.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:k?{top:_e(ge,6),left:_e(pe,104),right:_e(me,104),height:`max(44px, calc(${fe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${fe(250)}), 34vw)`,height:`max(44px, calc(${fe(56)}))`}}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top left`:`left center`,j(`left`)),children:[(0,B.jsx)(`span`,{}),D(`↑`,z.UP,0),(0,B.jsx)(`span`,{}),D(`←`,z.LEFT,-90),(0,B.jsx)(`span`,{}),D(`→`,z.RIGHT,90),(0,B.jsx)(`span`,{}),D(`↓`,z.DOWN,180),(0,B.jsx)(`span`,{})]}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top right`:`right center`,j(`right`)),children:[(0,B.jsx)(`span`,{}),O(`△`,z.TRIANGLE,(0,B.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,B.jsx)(`span`,{}),O(`□`,z.SQUARE,(0,B.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,B.jsx)(`span`,{}),O(`○`,z.CIRCLE,(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,B.jsx)(`span`,{}),O(`✕`,z.CROSS,(0,B.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,B.jsx)(`span`,{})]}),(0,B.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:ue(`l`)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:ue(`r`)}),(0,B.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:pe}),children:ce(`Create`,z.SHARE)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:ce(`Options`,z.OPTIONS)}),(0,B.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:rs,translate:`-50% 0`}),children:le(`PS`,z.PS)})]}),Se&&(0,B.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,Yo(n))},children:(0,B.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:`${ne} h-[44px] w-[56px]`,style:re,"data-testid":`rp-menu-handle`,children:(0,B.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,B.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var ss=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,cs=null,ls=null;function us(e){e.play().catch(()=>{if(ls||cs!==e)return;let t=()=>{ds(),cs===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),ls=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function ds(){ls?.(),ls=null}function fs(){if(typeof document<`u`){if(!cs){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=ss,document.body.appendChild(e),cs=e}us(cs)}}function ps(){ds(),cs&&=(cs.pause(),cs.removeAttribute(`src`),cs.remove(),null)}function ms(){return typeof navigator>`u`?null:navigator.wakeLock??null}function hs(){return ut()||!Nn()}var gs=new Set,_s=null,vs=Promise.resolve(),ys=!1;async function bs(){if(gs.size===0||_s&&!_s.released)return;let e=ms();if(!e)ut()&&fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{_s===t&&(_s=null)}),_s=t}catch{}}async function xs(){ps();let e=_s;if(_s=null,e&&!e.released)try{await e.release()}catch{}}function Ss(){ys||typeof document>`u`||(ys=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&gs.size>0&&(vs=vs.then(bs))}))}function Cs(e,t){if(!hs())return;Ss();let n=gs.size>0;t?gs.add(e):gs.delete(e);let r=gs.size>0;n!==r&&(vs=vs.then(r?bs:xs))}var ws=new Set;function Ts(){if(typeof window<`u`)return window.PS5UploadPad}function Es(e,t){let n=ws.size>0;t?ws.add(e):ws.delete(e);let r=ws.size>0;if(n!==r)try{Ts()?.setActive(r)}catch{}}var Ds=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}},Os=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 Ds(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}},ks=`ps5upload.join.muted`,As=5e3,js=Object.fromEntries(Object.entries(Ma).filter(([e])=>e!==`Escape`)),Ms=new Set;function Ns(e){if(!(e.code in js)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||Ps(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||Ps(t))}function Ps(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 Fs=!1;function Is(e){Fs=e}function Ls(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function Rs(){if(Fs)return{...Aa};let e=Wa(Ya(typeof navigator>`u`?void 0:navigator),xo),t=Ko.touchPad;return{...Ga(Ga(e,Pa(Ms,js)),t),touch:t.touch??null,motion:Ko.motion??null}}var zs=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:Vs(),path:null},this.client=new Ro({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:Rs,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:()=>Ls(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Os&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Ya(typeof navigator>`u`?void 0:navigator);Ka(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=aa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Os(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`?Ms.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{Ms.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&Ns(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),Ms.add(e.code))},r=e=>{Ms.delete(e.code)&&Ns(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()},As);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),Ms.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(ks,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();Ko.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 Bs(e){return(0,E.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function Vs(){try{return typeof localStorage<`u`&&localStorage.getItem(ks)===`1`}catch{return!1}}function Hs(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Cs(`play-together`,n),Es(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Cs(`play-together`,!1),Es(`play-together`,!1)}}var Us=3e3,Ws=class{constructor(e,t=Us){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 Gs(e,t,n=!1){let[r,i]=(0,E.useState)(!0),a=(0,E.useRef)(null);(0,E.useEffect)(()=>{let e=new Ws(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,E.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,E.useCallback)(()=>a.current?.poke(),[]),s=(0,E.useCallback)(()=>a.current?.hide(),[]),c=(0,E.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var Ks=3e4,qs=class{constructor(e,t=Ks){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 Js(e){let[,t]=(0,E.useState)(0),[n]=(0,E.useState)(()=>new qs(()=>t(e=>e+1)));return(0,E.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,E.useEffect)(()=>()=>n.reset(),[n]),n.shown}var Ys=()=>Ya(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function Xs(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===z.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===z.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===z.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===z.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 Zs(e,t){let n=(0,E.useRef)(t);(0,E.useEffect)(()=>{n.current=t}),(0,E.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(Ys().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var Qs=[[z.CROSS,`✕`],[z.CIRCLE,`○`],[z.SQUARE,`□`],[z.TRIANGLE,`△`],[z.UP,`↑`],[z.DOWN,`↓`],[z.LEFT,`←`],[z.RIGHT,`→`],[z.L1,`L1`],[z.R1,`R1`],[z.L3,`L3`],[z.R3,`R3`],[z.SHARE,`Create`],[z.OPTIONS,`Options`],[z.PS,`PS`],[z.TOUCHPAD,`Touchpad`]];function $s({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,B.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,B.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,B.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[Qs.map(([n,r])=>(0,B.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,B.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,B.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,B.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function ec({onClose:e}){let t=Fe(),[n,r]=(0,E.useState)(()=>Ys().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,E.useState)(()=>Ys()[0]?.index??null),[o,s]=(0,E.useState)(Aa),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(0),[f,p]=(0,E.useState)(vo),[m,h]=(0,E.useState)(null),[g,_]=(0,E.useState)(null);(0,E.useEffect)(()=>(Is(!0),()=>Is(!1)),[]),(0,E.useEffect)(()=>{let e=()=>{let e=Ys();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)}},[]),Zs(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(To(e))&&v(c,e);return}let t=Wa([e],xo);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 v=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(yo(r,e.profile(n?Co(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},y=()=>{h(null),d(0),l(new Po(Mo))},b=g,x=b?So(b):null,S=!!(b&&f[b.id]);return(0,B.jsx)(`div`,{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,B.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,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(me,{size:16,className:`text-white/70`}),(0,B.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,B.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,B.jsx)(Ee,{size:15})})]}),b?(0,B.jsxs)(B.Fragment,{children:[n.length>1&&(0,B.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,B.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:eo(e.id)},`${e.index}-${e.id}`))}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:eo(b.id)}),(0,B.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":x??``,children:x===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):x===`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`)}),ro(b)&&(0,B.jsx)(Wo,{id:b.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,B.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,B.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,B.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?Xs(t,c.current):``}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),v(c,b)},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,B.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,B.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,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)($s,{pad:o}),m&&(0,B.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:y,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:S?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),S&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>{p(yo(b.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,B.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,B.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 tc(e,t){let[n,r]=(0,E.useState)(!1);return(0,E.useEffect)(()=>{if(!e||!t)return;let n=!0;return ze(e,Ie).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function nc({href:e}){let t=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,B.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,B.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 rc(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var ic=`ps5upload.join.guided`,ac=1;function oc(e){return e.player!==ac&&(!e.guided||e.movedOff)&&!e.reconnecting}function sc(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 cc(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 lc(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 cc(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 cc(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 uc(e){let[t,n]=(0,E.useState)(()=>Date.now());return(0,E.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function dc(){let[e,t]=(0,E.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,E.useEffect)(()=>{let e=()=>{let e=Ya(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?Rs():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?So(e):null,s=!!e&&ro(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 pc=14,mc=()=>typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,hc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function gc({text:e,body:t,onCancel:n}){let r=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,B.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,B.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,B.jsx)(Se,{size:26})})]}),(0,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,B.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,B.jsx)(`button`,{type:`button`,onClick:n,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 _c({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Fe(),c=Bs(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,E.useRef)(null),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(()=>It(ic)===`1`),[_,v]=(0,E.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),y=dc(),[b,x]=(0,E.useState)(!1),S=l.kind===`reconnecting`,ee=uc(S),C=l.kind===`joined`||S,w=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[T,ne]=(0,E.useState)(!1),re=(0,E.useRef)(te);(0,E.useEffect)(()=>{re.current===ac&&te>ac&&ne(!0),te&&(re.current=te)},[te]);let[ie,ae]=(0,E.useState)(!1),[oe,se]=(0,E.useState)(!1),D=C&&(p||!t),O=mc(),ce=Js(w),ue=Gs(D,S||ce&&!O||ie||oe,O),{poke:de}=ue,pe=(0,E.useRef)(null),he=()=>{pe.current&&clearTimeout(pe.current.timer),pe.current=null};(0,E.useEffect)(()=>he,[]);let[_e,ve]=(0,E.useState)(!1),ye=(0,E.useRef)(!1);(0,E.useEffect)(()=>{if(!D||!O||ue.shown||!h||ye.current)return;ye.current=!0,ve(!0);let e=setTimeout(()=>ve(!1),6e3);return()=>clearTimeout(e)},[D,O,ue.shown,h]),(0,E.useEffect)(()=>{if(!C)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[C,e]),(0,E.useEffect)(()=>{if(!C||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)}},[C,c.sound,e]),(0,E.useEffect)(()=>{let e=()=>v(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,E.useEffect)(()=>{if(p)return()=>void i?.(!1)},[p,i]);let A=(0,E.useRef)(p);(0,E.useEffect)(()=>{A.current=p},[p]),(0,E.useEffect)(()=>{if(!t||!C||!mc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!A.current&&(m(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,C,i]),(0,E.useEffect)(()=>{if(!C)return;let e=e=>{e.key===`Escape`&&(de(),p&&m(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[C,p,de]),(0,E.useEffect)(()=>{if(!p||!mc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,m(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[p]),(0,E.useEffect)(()=>{if(!p||typeof document>`u`)return;let e=()=>{document.fullscreenElement||mc()||m(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[p]);let xe=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,B.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`,children:[l.kind===`connecting`&&o&&a&&(0,B.jsx)(nc,{href:a}),(0,B.jsx)(gc,{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:xe})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,B.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,children:[(0,B.jsx)(Se,{size:28,className:`text-white/60`}),(0,B.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:lc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,B.jsx)(nc,{href:a}),(0,B.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,B.jsx)(`button`,{type:`button`,onClick:r,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,B.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let Ce=l.player,M=c.light??it(Ce),Te=c.rttMs??u?.rttMs??null,Ee=rt(Te),De=mc(),Oe=C&&!S&&!y.ready&&De&&(!t||p),ke=oc({player:Ce,guided:h,movedOff:T,reconnecting:S}),Ae=Ce===ac,je=u?.playsAs??null,Me=S?(l.deadline-ee)/1e3:0,Ne=async()=>{let e=!p;m(e),await i?.(e)},Pe=t&&!p&&De&&C,Ie=(0,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${M[0]},${M[1]},${M[2]})`}}),t&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:Ce},`You are Player ${Ce}`)]}),Te!=null&&(0,B.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:hc[Ee]},"data-testid":`join-delay`,"data-tone":Ee,"data-path":c.path??void 0,children:[c.path&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[sc(s,c.path),` · `]}),Math.round(Te),` ms`]}),Ae&&(0,B.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.`)}),je&&!Ae&&(0,B.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:je},`You're playing as ${je}. No need to pick one.`)}),w&&!Ae&&u?.seatNote&&(0,B.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.`)}),w&&!Ae&&(0,B.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`)})]}),Le=(0,B.jsxs)(B.Fragment,{children:[D&&O&&ue.shown&&!S&&(0,B.jsxs)(`button`,{type:`button`,onClick:ue.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,B.jsx)(fe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,B.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,B.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,B.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,B.jsx)(N,{size:13}):(0,B.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,B.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,B.jsx)(N,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>void Ne(),"aria-label":p?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:p?(0,B.jsx)(be,{size:13}):(0,B.jsx)(k,{size:13})}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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,B.jsx)(me,{size:13})}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),Re=ue.shown?`opacity-100`:`pointer-events-none opacity-0`,ze={"data-testid":`join-bar`,"data-shown":ue.shown?`1`:`0`,onFocus:e=>{e.target.matches?.(`:focus-visible`)&&se(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||se(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&ae(!0)},onPointerLeave:()=>ae(!1)};return(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`${p||!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)]`} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},onPointerMove:e=>{if(e.pointerType===`mouse`)return de();let t=pe.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>pc&&he()},onPointerDown:e=>{if(fc(e.target))return;if(e.pointerType===`mouse`||!O)return de();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;he();let{pointerId:t,clientX:n,clientY:r}=e;pe.current={id:t,x:n,y:r,timer:setTimeout(()=>{pe.current=null,navigator.vibrate?.(15),ue.toggle()},450)}},onPointerUp:he,onPointerCancel:he,onPointerLeave:he,"data-testid":`join-stage-view`,children:[(0,B.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),D&&!ue.shown&&!S&&Te!=null&&(0,B.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:hc[Ee],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(Te),` ms`]}),Oe?(0,B.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 ${Re}`,...ze,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Ie}),(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Le})]}):Pe?null:(0,B.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 ${Re}`,...ze,children:[Ie,(0,B.jsx)(`span`,{className:`flex-1`}),Le]}),!ue.shown&&!Oe&&(0,B.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),de()},"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,B.jsx)(le,{size:16,"aria-hidden":!0})}),_e&&!ue.shown&&(0,B.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,B.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.`)}),b&&(0,B.jsx)(ec,{onClose:()=>x(!1)}),Oe&&(0,B.jsx)(os,{stream:e,layout:`overlay`,onMenu:()=>ue.shown?ue.hide():de()}),!Oe&&!S&&(0,B.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 ${Re}`,"data-testid":`join-pad`,children:[(0,B.jsx)(me,{size:14,style:{color:y.pressed?`rgb(${M[0]},${M[1]},${M[2]})`:void 0}}),y.ready?(0,B.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),y.weak8BitDo&&y.id&&(0,B.jsx)(Wo,{id:y.id,className:`text-amber-200/90`}),y.kind===`guess`&&to()&&(0,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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`)})]})]}):De&&t&&!p?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,B.jsxs)(`span`,{className:`flex flex-col`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,B.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.`)})]})]}),u?.blockSystem&&u.state===`playing`&&!Oe&&(0,B.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 ${Re}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),ce&&!Ae&&O&&!ue.shown&&!S&&(0,B.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`)}),ke&&!je&&(0,B.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,B.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,B.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,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>{Ft(ic,`1`),g(!0),ne(!1)},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`)})]}),S&&(0,B.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,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,B.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,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:rc(Me)},`The host stopped playing — waiting for them to start again (${rc(Me)})`)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:rc(Me)},`Your place is kept for ${rc(Me)}.`)})]})]}),!t&&C&&_&&De&&(0,B.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,B.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,B.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})})]}),Pe&&(0,B.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,B.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:Ie}),(0,B.jsxs)(`button`,{type:`button`,onClick:()=>void Ne(),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,B.jsx)(k,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,B.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,B.jsx)(N,{size:16}):(0,B.jsx)(we,{size:16})}):c.sound?null:(0,B.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,B.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var vc=`ps5upload.join.name`;function yc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function bc(e){return e.trim().slice(0,32)}function xc(e=``){return bc(It(`ps5upload.join.name`)??``)||e}function Sc(e){let t=bc(e);return t&&Ft(vc,t),t}function Cc(e){try{return!!sessionStorage.getItem(Lo(e))}catch{return!1}}async function wc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Tc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Fe(),c=tc(r&&o!==!1?e:null,i),[l,u]=(0,E.useState)(()=>xc(yc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(0),h=i=>{let s=Sc(i);if(!s)return;let c=new zs({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,E.useEffect)(()=>{!d&&Cc(t)&&l.trim()&&h(l)},[]),(0,E.useEffect)(()=>d?Hs(d):void 0,[d]),(0,E.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,B.jsx)(_c,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),h(l)},onFullscreen:wc},p);let g=n??s(`join_host_fallback`,void 0,`your friend`),_=(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,children:(0,B.jsxs)(`form`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),h(l)},children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,B.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,B.jsx)(Se,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:g},`Play on ${g}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,B.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,B.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,B.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,B.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,B.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,B.jsx)(nc,{href:i})]})});return t?(0,B.jsx)(Uo,{appLink:nt(location.href),children:_}):_}function Ec(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 Dc(e,t){let n=Ec(e),r=Ec(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Oc(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Ec(t);return n===0?`lan`:n===1?`tailscale`:null}function kc(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 Dc(a(i.localCandidateId),a(i.remoteCandidateId))}function Ac(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function jc(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 Mc(e,t){let n=jc(e);return n!==null&&n===t.toUpperCase()}var Nc=16777216;function Pc(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 Ic(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Lc=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Rc=1500,zc=2e4;function Bc(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 Vc=null;function Hc(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 Uc(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||Vc)return;let r=Ac(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};Vc=a;let o=()=>{Vc===a&&(Vc=null,a.timer&&clearTimeout(a.timer),Hc(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 Wc(e,t){let n=Vc;return n?(Vc=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`)?(Hc(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Gc(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 Fc,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??Ac(e.hub),a=t.signalUrl||t.lan?null:Wc(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:Lc}]})}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=Bc(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?!Mc(t.sdp,e.fp):jc(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(Ic(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 kc(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 Pc(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+zc,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()},Rc),!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(Ve,`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 Kc=3e3;function qc(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var Jc=e=>qc(e,`api/join/signal`);function Yc(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?Jc(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?qc(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var Xc=new Map;function Zc(e,t,n=300,r=Kc){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 Qc(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(He(e.e)??``));return t&&(He(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function $c(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=Zc(n.map(e=>e.via),Xc.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)&&He(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(Qc(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,Xc.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}var el=new URLSearchParams(location.hash.slice(1)),tl=el.get(`n`)?.trim()||null,nl=tt(location.hash);nl&&Uc(nl);var rl=(0,x.createRoot)(document.getElementById(`root`));if(nl){let e=Gc(nl,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Le(location.hash,`join`);rl.render((0,B.jsx)(Tc,{url:Ac(nl.hub),invite:nl.key,host:tl,transport:e,lanUrl:t?Re(t,{key:nl.key}):null}))}else{let e=el.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:$c(()=>Yc({net:null,lan:i,ts:null,fp:et(el.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>Gc(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});rl.render((0,B.jsx)(Tc,{url:n,invite:e,host:tl,path:Oc(location.hostname),transport:a,internet:!1}))} +I€wu¸öôú!3å6³‹âVq£³¹´RN£%y10º:pŠ#\:J:b9Hµ7h_Ž:¢I9 _¼™µV,þ <`});var T={a:v};this.setModule=t=>{e.setModule(yi,t)},this.getModule=()=>e.getModule(yi),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,T)).then(e=>{let t=e.exports;y(t),a=t.g,o(),te(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 bi=o((()=>{}));function xi(e={}){xi.errors||Object.defineProperties(xi,{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+` `+(xi.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 Si=o((()=>{vi(),bi()})),Ci,wi=o((()=>{vi(),bi(),Si(),Ci=class extends mi{constructor(e){super(e,`opus-decoder`,xi,yi)}async decodeFrame(e){return this.postToDecoder(`decodeFrame`,e)}async decodeFrames(e){return this.postToDecoder(`decodeFrames`,e)}}})),Ti=c({OpusDecoder:()=>xi,OpusDecoderWebWorker:()=>Ci}),Ei=o((()=>{Si(),wi(),vi(),gi(xi,`OpusDecoder`),gi(Ci,`OpusDecoderWebWorker`)})),Di=[8e3,12e3,16e3,24e3,48e3],Oi=null;function ki(){return Oi??=Yn(()=>Promise.resolve().then(()=>(Ei(),Ti)),__VITE_PRELOAD__,import.meta.url).catch(e=>{throw Oi=null,e}),Oi}function Ai(){return typeof WebAssembly==`object`&&typeof WebAssembly.instantiate==`function`}function ji(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 Mi=class{constructor(e,t=ki){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(!Ai())throw Error(`no WebAssembly here`);let t=e.sampleRate;if(!Di.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(ji(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{}}},Ni={makeDecoder:e=>new Mi(e),makeChunk:e=>({type:e.type,timestamp:e.timestamp,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)})};function Pi(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 Fi(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 Ii=[`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 Li(e,t){if(typeof VideoDecoder>`u`)return null;for(let n of Ii)try{if((await VideoDecoder.isConfigSupported({codec:n,codedWidth:e,codedHeight:t})).supported)return n}catch{}return null}function Ri(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 zi=(e,t)=>t?e[0]>>1&63:e[0]&31;function Bi(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 I(...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 Vi=(e,t,n,...r)=>Bi(e,I([t,1],[n,3]),...r),Hi=I([65536,4],[0,4],[0,4],[0,4],[65536,4],[0,4],[0,4],[0,4],[1073741824,4]);function Ui(e){let t=e.handler===`vide`,n=Bi(`ftyp`,new TextEncoder().encode(`isom`),I([1,4]),new TextEncoder().encode(`isomiso6mp41`)),r=Bi(`moov`,Vi(`mvhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[65536,4],[256,2],[0,2],[0,4],[0,4]),Hi,new Uint8Array(24),I([2,4])),Bi(`trak`,Vi(`tkhd`,0,3,I([0,4],[0,4],[1,4],[0,4],[0,4],[0,4],[0,4],[0,2],[0,2],[t?0:256,2],[0,2]),Hi,I([(e.width??0)*65536,4],[(e.height??0)*65536,4])),Bi(`mdia`,Vi(`mdhd`,0,0,I([0,4],[0,4],[e.timescale,4],[0,4],[21956,2],[0,2])),Vi(`hdlr`,0,0,I([0,4]),new TextEncoder().encode(e.handler),new Uint8Array(12),I([0,1])),Bi(`minf`,t?Vi(`vmhd`,0,1,new Uint8Array(8)):Vi(`smhd`,0,0,I([0,4])),Bi(`dinf`,Vi(`dref`,0,0,I([1,4]),Vi(`url `,0,1))),Bi(`stbl`,Vi(`stsd`,0,0,I([1,4]),e.sampleEntry),Vi(`stts`,0,0,I([0,4])),Vi(`stsc`,0,0,I([0,4])),Vi(`stsz`,0,0,I([0,4],[0,4])),Vi(`stco`,0,0,I([0,4])))))),Bi(`mvex`,Vi(`trex`,0,0,I([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 Wi(e,t,n,r,i){let a=i?33554432:16842752,o=e=>Vi(`trun`,0,1793,I([1,4],[e,4],[n,4],[r.length,4],[a,4])),s=e=>Bi(`traf`,Vi(`tfhd`,0,131072,I([1,4])),Vi(`tfdt`,1,0,I([t,8])),o(e)),c=Vi(`mfhd`,0,0,I([e,4])),l=Bi(`moof`,c,s(0)).length,u=Bi(`moof`,c,s(l+8)),d=Bi(`mdat`,r),f=new Uint8Array(u.length+d.length);return f.set(u,0),f.set(d,u.length),f}function Gi(e,t,n=!1){let r=t?[35,...n?[32,33,34]:[]]:[9,...n?[7,8]:[]],i=Ri(e).filter(e=>!r.includes(zi(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 Ki=e=>e.toString(16).padStart(2,`0`),qi=e=>{let t=new Uint8Array(2+e.length);return t[0]=e.length>>8,t[1]=e.length&255,t.set(e,2),t},Ji=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 Yi(e){let t=Ri(e),n=t.filter(e=>zi(e,!1)===7),r=t.filter(e=>zi(e,!1)===8);return!n.length||!r.length||n[0].length<4?null:Ji([I([1,1],[n[0][1],1],[n[0][2],1],[n[0][3],1],[255,1],[224|n.length,1]),...n.map(qi),I([r.length,1]),...r.map(qi)])}function Xi(e,t,n){let r=Ri(e),i=e=>r.filter(n=>zi(n,t)===e),a=(e,t)=>Bi(e,new Uint8Array(6),I([1,2],[0,16],[n.w,2],[n.h,2],[4718592,4],[4718592,4],[0,4],[1,2]),new Uint8Array(32),I([24,2],[65535,2]),t);if(!t){let t=i(7),r=Yi(e);return r?{init:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`avc1`,Bi(`avcC`,r)),width:n.w,height:n.h}),mime:`video/mp4; codecs="avc1.${Ki(t[0][1])}${Ki(t[0][2])}${Ki(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=Yr(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)=>Ji([I([128|e,1],[t.length,2]),...t.map(qi)]),m=Bi(`hvcC`,I([1,1]),u,I([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:Ui({handler:`vide`,timescale:9e4,sampleEntry:a(`hvc1`,m),width:n.w,height:n.h}),mime:`video/mp4; codecs="${y}"`}}function Zi(e,t,n,r,i,a){return Wi(e,t,n,Gi(r,i),a)}function Qi(e,t){let n=Bi(`dOps`,I([0,1],[e,1],[312,2],[t,4],[0,2],[0,1]));return Ui({handler:`soun`,timescale:48e3,sampleEntry:Bi(`Opus`,new Uint8Array(6),I([1,2],[0,8],[e,2],[16,2],[0,4],[3145728e3,4]),n)})}function $i(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 ea(e,t,n){return Wi(e,t,$i(n),n,!0)}var ta={watch:30,player:4},na={watch:{seek:.5,speed:1/0,target:.05},player:{seek:.15,speed:.06,target:.02}},ra={seek:.8,speed:.25,target:.12};function ia(e,t,n){let r=typeof n==`string`?na[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 aa(e,t=`watch`,n){return typeof VideoDecoder<`u`?new ma(e,t,n):new Oa(e,t,n)}var oa=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 L(e){return e.length<3?null:{index:e[0]<<8|e[1],packet:e.subarray(2)}}var R=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 sa(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 ca(e,t){return{snd:e,snd_decoded:t.decoded,snd_concealed:t.concealed,snd_underruns:t.underruns,snd_dropped:t.dropped}}var la=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+ua;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}},ua=.02;async function da(e,t){try{return typeof AudioDecoder>`u`?!1:!!(await AudioDecoder.isConfigSupported({codec:`opus`,sampleRate:e,numberOfChannels:t})).supported}catch{return!1}}var fa=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}},pa=[`pointerup`,`touchend`,`click`,`keydown`],ma=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():ca(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 fa(`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 oa(n),this.clock=new la(t===`player`?.05:.08),typeof AudioDecoder>`u`&&_a()&&(this.mseSound=new va(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=ti(this.header,e)),this.mse?.setHevc(e)}get onMse(){return!!this.mse}decodeFailed(){if(this.mse||this.ownStats.frames>0||++this.failsNoPicture<3||!ba())return!1;let e=new Oa(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,ha(),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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)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=ti(e,this.hevc),!this.opening){this.opening=!0;try{let t=this.hevc?await ka(e):Fi(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:Yi(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=ni(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=Pi(e,this.hevc);if(this.ownStats.arrived(),!this.sawKey&&!n)return this.ownStats.drop(),this.keyAsk.waiting();if(!n&&t.decodeQueueSize>ta[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=Gi(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];da(new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(2),n).then(n=>{if(t!==this.audioGen)return;if(!n)return _a()?this.soundThroughMse(e):this.soundThroughWasm(e);let r=new oi((e,t)=>this.play(e,t,r.sampleRate));try{r.header(sa(e)),this.pipe=r}catch{this.soundThroughMse(e)}})}soundThroughMse(e){this.pipe=null,this.mseSound||(this.mseSound=new va(this.latency,()=>this.mseSoundFailed()),this.soundOn&&this.mseSound.start()),this.mseSound.setHeader(e)}soundThroughWasm(e){this.pipe?.reset(),this.soundWasm=!0;let t=new oi((e,n)=>this.play(e,n,t.sampleRate),Ni,()=>{this.pipe===t&&(this.pipe=null),this.onSoundFail?.()});this.pipe=t,t.header(sa(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 ha(){try{let e=navigator.audioSession;e&&e.type!==`playback`&&(e.type=`playback`)}catch{}}function ga(e,t){try{return e.isTypeSupported(t)}catch{return!1}}function _a(){let e=typeof window>`u`?null:ba();return!!e&&(ga(e,`audio/mp4; codecs="Opus"`)||ga(e,`audio/mp4; codecs="opus"`))}var va=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 R,this.el=n,this.track=new wa(n,()=>this.fail(),e===`player`?ra: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=L(e);if(!t||!this.order.take(t.index))return;let n=ea(this.track.nextSeq(),this.time,t.packet);this.time+=$i(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=Qi(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())}},ya=class{constructor(e,t,n=Ni){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 la(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,ha();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 oi((e,n)=>this.play(e,n,t.sampleRate),this.codecs,()=>{this.pipe===t&&this.fail()});this.pipe=t,t.header(sa(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 pa)window.addEventListener(t,e,!0);this.unarm=()=>{for(let t of pa)window.removeEventListener(t,e,!0);this.unarm=null}}fail(){this.failed||(this.failed=!0,this.stop(),this.onFail())}};function ba(){let e=window;return e.ManagedMediaSource??e.MediaSource??null}var xa=10,Sa=3;function Ca(e,t,n,r=Sa){let i=null;for(let a of e)a>t&&a<=n-r&&(i=a);return i}var wa=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=ba();if(!n||!ga(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=Ta(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=ia(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>xa&&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-Sa;if(this.keys){if(r=Ca(this.keys,t,n),r===null)return(this.keys[this.keys.length-1]??-1/0)<=n-Sa&&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 Ta(e,t){if(`srcObject`in e)try{return e.srcObject=t,`object`}catch{}return e.src=URL.createObjectURL(t),`url`}var Ea=1e4,Da=class{constructor(e=3,t=Ea,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=[]}},Oa=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 fa(`mse`),this.problemShown=!1,this.vTime=0,this.vLast=0,this.soundOn=!1,this.onSoundFail=null,this.onGiveUp=null,this.keyAsk=new oa(n),this.fails=new Da(3,Ea,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 va(t,()=>this.soundThroughWasm()),this.wrap.className=`h-full w-full`,this.wrap.append(i,this.audio.el),this.video=new wa(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(!_a())return this.soundThroughWasm();this.audio.start()}soundThroughWasm(){if(this.wasm)return;this.audio.stop();let e=new ya(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?ca(`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=ti(e,this.hevc)??{w:1920,h:1080},r=Xi(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=Pi(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>ta[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(Zi(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 ka(e){let t=ri(e);if(t&&typeof VideoDecoder<`u`)try{if((await VideoDecoder.isConfigSupported({codec:t,codedWidth:1920,codedHeight:1080})).supported)return t}catch{}return Li(1920,1080)}var z={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},Aa={buttons:0,l2:0,r2:0,lx:0,ly:0,rx:0,ry:0};function ja(e,t){let n=e=>Math.max(0,Math.min(1,e));return[Math.round(n(e)*1919),Math.round(n(t)*941)]}var Ma={ArrowUp:{button:z.UP},ArrowDown:{button:z.DOWN},ArrowLeft:{button:z.LEFT},ArrowRight:{button:z.RIGHT},Enter:{button:z.CROSS},Space:{button:z.CROSS},Backspace:{button:z.CIRCLE},Escape:{button:z.CIRCLE},KeyQ:{button:z.SQUARE},KeyE:{button:z.TRIANGLE},KeyZ:{button:z.L1},KeyC:{button:z.R1},Digit1:{trigger:`l2`},Digit3:{trigger:`r2`},KeyF:{button:z.L3},KeyG:{button:z.R3},Tab:{button:z.OPTIONS},Backquote:{button:z.SHARE},KeyH:{button:z.PS},KeyT:{button:z.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}};z.UP,z.DOWN,z.LEFT,z.RIGHT,z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD;var Na=e=>Math.max(-32768,Math.min(32767,Math.round(e)));function Pa(e,t=Ma){let n={...Aa};for(let r of e){let e=t[r];e&&(`button`in e?n.buttons|=e.button:`stick`in e?n[e.stick]=Na(n[e.stick]+e.dir*32767):n[e.trigger]=255)}return n}var Fa=[z.CROSS,z.CIRCLE,z.SQUARE,z.TRIANGLE,z.L1,z.R1,0,0,z.SHARE,z.OPTIONS,z.L3,z.R3,z.UP,z.DOWN,z.LEFT,z.RIGHT,z.PS,z.TOUCHPAD];function Ia(e){return Math.abs(e)<=1.01?Math.round((e+1)*3.5)%8:null}var La=[0,1,1,1,0,-1,-1,-1],Ra=[-1,-1,0,1,1,1,0,-1];function za(e,t){let n=e.axes[t.a]??0;if(t.hat){let e=Ia(n);return e===null?0:(t.hat===`x`?La:Ra)[e]}return t.inv?-n:n}var Ba={buttons:Fa.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 Va(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=Ia(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 Ha(e){if(e.mapping===`standard`)return Ba;let t=Ua.get(e.id);if(t)return t;let n=e.axes.findIndex(e=>Math.abs(e)>1.05);if(n<0)return Ba;let r={...Ba,buttons:[...Ba.buttons,[z.UP,{h:n,at:0}],[z.RIGHT,{h:n,at:2}],[z.DOWN,{h:n,at:4}],[z.LEFT,{h:n,at:6}]]};return Ua.set(e.id,r),r}var Ua=new Map;function Wa(e,t=Ha){let n={...Aa},r=e=>Math.abs(e)<.08?0:Na(e*32767),i=(e,t)=>Math.abs(t)>Math.abs(e)?t:e,a=(e,t)=>t?r(za(e,t)):0;for(let r of e){if(!r||!r.connected)continue;let e=t(r);for(let[t,i]of e.buttons)Va(r,i)>.5&&(n.buttons|=t);e.l2&&(n.l2=Math.max(n.l2,Math.round(Va(r,e.l2,!0)*255))),e.r2&&(n.r2=Math.max(n.r2,Math.round(Va(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 Ga(e,t){return{buttons:e.buttons|t.buttons,l2:Math.max(e.l2,t.l2),r2:Math.max(e.r2,t.r2),lx:Na(e.lx+t.lx),ly:Na(e.ly+t.ly),rx:Na(e.rx+t.rx),ry:Na(e.ry+t.ry),touch:e.touch??t.touch??null,motion:e.motion??t.motion??null}}function Ka(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 qa=new Map;function Ja(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 Ya(e){let t=e?.getGamepads?.()??[];return qa.size===0||t.some(e=>!!e?.connected)?[...t]:[...qa.values()].sort((e,t)=>e.slot-t.slot).map(e=>Ja(e))}var Xa=`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(`(`),Za={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},Qa=e=>e.toLowerCase().padStart(4,`0`);function $a(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:Qa(t[2]),product:Qa(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:Qa(n[1]),product:Qa(n[2]),name:n[3].trim()}:null}function eo(e){return($a(e)?.name??e.replace(/\s*\((?:XInput\s*)?STANDARD GAMEPAD\)\s*$/i,``)).trim()||e}function to(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 no(e,t){if(!t)return null;let n=t===`l`?[`l`]:[`m`,`w`];for(let t of n){let n=Za[`${t}${e.vendor}${e.product}`];if(n!==void 0)return Xa[n]??null}return null}function ro(e){return e.mapping!==`standard`&&$a(e.id)?.vendor===`2dc8`}var io={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 ao(e){let t=$a(e);return t&&io[t.product]||`manual`}var oo={1:0,2:2,4:4,8:6};function so(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 co(e,t,n){let{n:r,hat:i}=so(t),a=Fa.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 lo(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=oo[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 uo(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 fo(e,t,n){let r=e.split(`,`),i=co(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`&&go(e[1]))&&[t.l2,t.r2,t.lx,t.ly,t.rx,t.ry].every(go)}function vo(){try{let e=It(ho),t=e?JSON.parse(e):null;return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>_o(e[1])))}catch{return{}}}function yo(e,t){let n=vo();return t?n[e]=t:delete n[e],Ft(ho,JSON.stringify(n)),bo=n,n}var bo=null;function xo(e){return bo??=vo(),bo[e.id]??wo(bo,e.id)??mo(e)??Ha(e)}function So(e){return bo??=vo(),bo[e.id]?`saved`:e.mapping===`standard`?`standard`:mo(e)?`known`:`guess`}function Co(e){return mo(e)??Ha(e)}function wo(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?(bo=yo(t,e[i]),e[i]):null}function To(e){return{buttons:e.buttons.map(e=>Math.max(+!!e.pressed,e.value)),axes:[...e.axes]}}function Eo(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?Ia(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 Do(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 Oo=[{kind:`button`,bit:z.CROSS,name:`✕`},{kind:`button`,bit:z.CIRCLE,name:`○`},{kind:`button`,bit:z.SQUARE,name:`□`},{kind:`button`,bit:z.TRIANGLE,name:`△`},{kind:`button`,bit:z.UP,name:`↑`},{kind:`button`,bit:z.DOWN,name:`↓`},{kind:`button`,bit:z.LEFT,name:`←`},{kind:`button`,bit:z.RIGHT,name:`→`},{kind:`button`,bit:z.L1,name:`L1`},{kind:`button`,bit:z.R1,name:`R1`},{kind:`trigger`,which:`l2`,name:`L2`},{kind:`trigger`,which:`r2`,name:`R2`},{kind:`button`,bit:z.L3,name:`L3`},{kind:`button`,bit:z.R3,name:`R3`},{kind:`button`,bit:z.OPTIONS,name:`Options`},{kind:`button`,bit:z.SHARE,name:`Create`},{kind:`button`,bit:z.PS,name:`PS`},{kind:`button`,bit:z.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 ko(){return{buttons:[],l2:null,r2:null,lx:null,ly:null,rx:null,ry:null}}function Ao(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 jo(e,t=Ba){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 Mo=Oo.filter(e=>e.kind!==`button`||![z.L3,z.R3,z.OPTIONS,z.SHARE,z.PS,z.TOUCHPAD].includes(e.bit));function No(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 Po=class{constructor(e=Oo){this.steps=e,this.step=0,this.prof=ko(),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 No(this.rest,e)&&(this.waiting=!1),!1;let t=this.steps[this.step],n=t.kind===`axis`?Do(this.rest,e):Eo(this.rest,e);return n?(this.prof=Ao(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=Ba){return jo(this.prof,e)}};function Fo(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 Io(){try{return typeof sessionStorage<`u`?sessionStorage:null}catch{return null}}var Lo=e=>`ps5upload.join.token.${e??`app`}`,Ro=class{constructor(e){this.o=e,this.ws=null,this.stage={kind:`connecting`},this.token=null,this.player=0,this.last={...Aa},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?Io():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 Lo(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=He(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=qe(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()+$e),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()+$e,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()+Qe),this.scheduleRetry()):this.finish({kind:`ended`,why:`lost`})}scheduleRetry(){if(this.stopped)return;if(this.now()>=this.deadline){this.giveUp();return}let e=Ze(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?{...Aa,touch:null,motion:null}:this.o.readPad(),r=this.now();!e&&Fo(n,this.last)&&r-this.lastSent<100||(this.last=n,this.lastSent=r,this.seq=this.seq+1>>>0,t.send(Xe(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(Xe(this.seq,Aa))),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(Xe(this.seq,Aa))),this.stopped=!0,this.clearTimers(),this.ws=null;try{e?.close()}catch{}}},zo=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})),B=s(((e,t)=>{t.exports=zo()}))(),Bo=`ps5upload.openIn`,Vo=`ps5upload.openIn.tab`;function Ho(){try{return sessionStorage.getItem(Vo)===`browser`}catch{return!1}}function V(){try{sessionStorage.setItem(Vo,`browser`)}catch{}}function H(e){return e===`browser`?`browser`:e===`app`?`opening`:`ask`}function Uo({appLink:e,children:t}){let n=Fe(),[r,i]=(0,E.useState)(()=>Ho()?`browser`:H(It(Bo))),[a,o]=(0,E.useState)(!1);if((0,E.useEffect)(()=>{r===`opening`&&It(`ps5upload.openIn`)===`app`&&(location.href=e)},[]),r===`browser`)return(0,B.jsx)(B.Fragment,{children:t});let s=()=>{a&&Ft(Bo,`app`),i(`opening`),location.href=e},c=()=>{r===`ask`&&a?Ft(Bo,`browser`):r===`opening`&&It(`ps5upload.openIn`)===`app`&&Lt(Bo),V(),i(`browser`)};return(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`open-in-gate`,children:(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_title`,void 0,`Open in the PS5Upload app?`)}),(0,B.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,B.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,B.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,B.jsxs)(`label`,{className:`flex items-center justify-center gap-2 text-xs text-white/60`,children:[(0,B.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,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:n(`open_in_opening`,void 0,`Opening the PS5Upload app…`)}),(0,B.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,B.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,B.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 Wo({id:e,className:t}){let n=Fe(),r=ao(e);if(r===`none`)return(0,B.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,B.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 Go=new Set,Ko={held:new Set,touch:null,touchPad:Aa,mapping:!1,get paused(){return Go.size>0},motion:null},qo={s:.85,m:1,l:1.15},Jo=.25;function Yo(e){return typeof e!=`number`||!Number.isFinite(e)?1:Math.min(1,Math.max(Jo,e))}var Xo={overlay:{width:844,height:390},deck:{width:390,height:480}},Zo=.7,Qo=1.4;function $o(e,t,n,r){let i=qo[e]??1;if(!(t>0)||!(n>0))return i;let a=r?Xo.deck:Xo.overlay,o=Math.min(Qo,Math.max(Zo,Math.min(t/a.width,n/a.height)));return Math.round(o*i*1e3)/1e3}var es=34;function ts(e,t){return t>0&&8+Math.max(112*e,90)+156*e+124*e+Math.max(56*e,44)+es>t}function ns(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 rs=`calc(50% + (env(safe-area-inset-left) - env(safe-area-inset-right)) / 2)`,is=32767,as=12;function os({stream:e,layout:t=`overlay`,opacity:n=1,size:r=`m`,deckTop:i=`0px`,onMenu:a}){let o=Fe(),s=(0,E.useRef)(new Map),c=(0,E.useRef)({...Aa}),[l,u]=(0,E.useState)({...Aa}),[d,f]=(0,E.useState)({l:!1,r:!1,touchpad:!1}),p=(0,E.useRef)(null),[m,h]=(0,E.useState)({width:0,height:0});(0,E.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,E.useEffect)(()=>()=>{Ko.touchPad={...Aa}},[]);let g=()=>{let t={...Aa,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|=z.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,Ko.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*is),c.current[e.which===`l`?`ly`:`ry`]=Math.round(i*is)},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=ja((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=ja((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)>as&&(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)]`,te={filter:`drop-shadow(0 0 1.5px rgba(0,0,0,0.5))`},T=e=>({stroke:e?`#fff`:`rgba(255,255,255,0.75)`,fill:e?`rgba(255,255,255,0.5)`:`rgba(255,255,255,0.1)`}),ne=`pointer-events-auto flex touch-none select-none items-center justify-center bg-transparent p-0`,re={minHeight:`calc(44px / var(--k))`,minWidth:`calc(44px / var(--k))`},ie=(e,t,n,r)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`button`,bit:t})),...S,className:`${ne} ${n}`,style:re,children:r}),ae=(e,t,n,r)=>(0,B.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}),oe=(e,t,n,r)=>ie(e,t,`h-[44px] w-[84px]`,ae(e,ee(t),n,r)),se=(e,t,n)=>(0,B.jsx)(`button`,{type:`button`,"aria-label":e,onPointerDown:e=>v(e,()=>({kind:`trigger`,which:t})),...S,className:`${ne} h-[44px] w-[84px]`,style:re,children:ae(e,l[t]>0,n,!0)}),D=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsx)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:(0,B.jsxs)(`g`,{transform:`rotate(${n} 26 26)`,strokeWidth:`1.5`,strokeLinejoin:`round`,...T(ee(t)),children:[(0,B.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,B.jsx)(`path`,{d:`M20.5 23 L26 17 L31.5 23`,fill:`none`,stroke:`#fff`,strokeLinecap:`round`,strokeWidth:`1.8`})]})})),O=(e,t,n)=>ie(e,t,`h-[52px] w-[52px]`,(0,B.jsxs)(`svg`,{viewBox:`0 0 52 52`,width:`52`,height:`52`,"aria-hidden":!0,style:te,children:[(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`22.5`,strokeWidth:`1.5`,...T(ee(t))}),(0,B.jsx)(`g`,{fill:`none`,stroke:`#fff`,strokeWidth:`1.8`,strokeLinejoin:`round`,strokeLinecap:`round`,children:n})]})),ce=(e,t)=>ie(e,t,`h-[44px] min-w-[64px] px-[4px]`,(0,B.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})),le=(e,t)=>ie(e,t,`h-[44px] w-[44px]`,(0,B.jsx)(`span`,{className:`flex h-[36px] w-[36px] items-center justify-center rounded-full text-[11px] font-bold ${w} ${C(ee(t))}`,children:e})),ue=e=>{let{dx:t,dy:n}=ns(e===`l`?l.lx:l.rx,e===`l`?l.ly:l.ry,34),r=d[e];return(0,B.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,B.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))`}})})},k=t===`deck`,de=$o(r,m.width,m.height,k),fe=e=>`${e}px * var(--k)`,pe=`max(12px, env(safe-area-inset-left))`,me=`max(12px, env(safe-area-inset-right))`,he=`max(12px, env(safe-area-inset-bottom))`,ge=k?`8px`:t===`overlay-bar`?`3.5rem`:`max(10px, env(safe-area-inset-top))`,_e=(e,t,n=0)=>t?n?`calc(${e} + max(${fe(t)}, ${n}px))`:`calc(${e} + ${fe(t)})`:e,ye=(e,t)=>({position:`absolute`,...t,transform:`scale(var(--k))`,transformOrigin:e}),be=k&&ts(de,m.height),A=k?void 0:`58%`,j=e=>k?{top:_e(ge,be?96:112,be?72:90),[e]:e===`left`?pe:me}:{top:A,translate:`0 -50%`,[e]:e===`left`?pe:me},xe=e=>({bottom:be?he:_e(he,k?56:0,44),[e]:be?`calc(${e===`left`?pe:me} + 8px + max(${fe(80)}, 44px))`:_e(e===`left`?pe:me,k?40:168)}),Se=!!a&&!k;return(0,B.jsxs)(`div`,{ref:p,className:`pointer-events-none absolute z-10 select-none [-webkit-touch-callout:none] ${k?`inset-x-0 bottom-0`:`inset-0`}`,style:{top:k?i:void 0,"--k":de},"data-testid":`rp-touch`,"data-layout":t,"data-scale":de,onContextMenu:e=>e.preventDefault(),children:[(0,B.jsxs)(`div`,{className:`absolute inset-0`,style:{opacity:Yo(n)},children:[(0,B.jsx)(`div`,{style:ye(`top left`,{top:ge,left:pe}),children:(0,B.jsxs)(`div`,{className:`ms-[8px] flex flex-col`,style:{rotate:k?void 0:`6deg`,transformOrigin:`top left`},children:[se(`L2`,`l2`,`l`),oe(`L1`,z.L1,`l`,!1)]})}),(0,B.jsx)(`div`,{style:ye(`top right`,{top:ge,right:me}),children:(0,B.jsxs)(`div`,{className:`me-[8px] flex flex-col items-end`,style:{rotate:k?void 0:`-6deg`,transformOrigin:`top right`},children:[se(`R2`,`r2`,`r`),oe(`R1`,z.R1,`r`,!1)]})}),(0,B.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:k?{top:_e(ge,6),left:_e(pe,104),right:_e(me,104),height:`max(44px, calc(${fe(64)}))`}:{top:ge,left:`50%`,translate:`-50% 0`,width:`min(calc(${fe(250)}), 34vw)`,height:`max(44px, calc(${fe(56)}))`}}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top left`:`left center`,j(`left`)),children:[(0,B.jsx)(`span`,{}),D(`↑`,z.UP,0),(0,B.jsx)(`span`,{}),D(`←`,z.LEFT,-90),(0,B.jsx)(`span`,{}),D(`→`,z.RIGHT,90),(0,B.jsx)(`span`,{}),D(`↓`,z.DOWN,180),(0,B.jsx)(`span`,{})]}),(0,B.jsxs)(`div`,{className:`grid grid-cols-3 grid-rows-3`,style:ye(k?`top right`:`right center`,j(`right`)),children:[(0,B.jsx)(`span`,{}),O(`△`,z.TRIANGLE,(0,B.jsx)(`path`,{d:`M26 16.5 L35 32 L17 32 Z`})),(0,B.jsx)(`span`,{}),O(`□`,z.SQUARE,(0,B.jsx)(`rect`,{x:`18`,y:`18`,width:`16`,height:`16`,rx:`1`})),(0,B.jsx)(`span`,{}),O(`○`,z.CIRCLE,(0,B.jsx)(`circle`,{cx:`26`,cy:`26`,r:`8.5`})),(0,B.jsx)(`span`,{}),O(`✕`,z.CROSS,(0,B.jsx)(`path`,{d:`M19 19 L33 33 M33 19 L19 33`})),(0,B.jsx)(`span`,{})]}),(0,B.jsx)(`div`,{style:ye(`bottom left`,xe(`left`)),children:ue(`l`)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,xe(`right`)),children:ue(`r`)}),(0,B.jsx)(`div`,{style:ye(`bottom left`,{bottom:he,left:pe}),children:ce(`Create`,z.SHARE)}),(0,B.jsx)(`div`,{style:ye(`bottom right`,{bottom:he,right:me}),children:ce(`Options`,z.OPTIONS)}),(0,B.jsx)(`div`,{style:ye(`bottom center`,{bottom:be?_e(he,124,88):_e(he,Se?48:0,48),left:rs,translate:`-50% 0`}),children:le(`PS`,z.PS)})]}),Se&&(0,B.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,Yo(n))},children:(0,B.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:`${ne} h-[44px] w-[56px]`,style:re,"data-testid":`rp-menu-handle`,children:(0,B.jsx)(`span`,{className:`flex h-[26px] w-[44px] items-center justify-center rounded-full ${w} ${C(!1)}`,children:(0,B.jsx)(ve,{size:15,strokeWidth:2,"aria-hidden":!0})})})})]})}var ss=`data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAYZbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAfQAAAfQAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAmt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAH0AAAAAAAABAAAAAAHjbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAABAABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABjm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAU5zdGJsAAAAunN0c2QAAAAAAAAAAQAAAKphdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAAAAABFExhdmM2My4xLjEwMiBsaWJ4MjY0AAAAAAAAAAAAAAAAGP//AAAAMGF2Y0MBQsAK/+EAF2dCwAqmEXsBEAAAAwAQAAADACDxImEYAQAGaMhCAZSyAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAABUAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAQAAEAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAJHN0c3oAAAAAAAAAAAAAAAQAAAKCAAAACgAAAAoAAAAKAAAAIHN0Y28AAAAAAAAABAAABlwAAAj+AAAJKAAACVIAAALZdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAH0AAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAB9AAAABAAAAQAAAAACUW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAH0AAAIEAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAfxtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcBzdGJsAAAAfnN0c2QAAAAAAAAAAQAAAG5tcDRhAAAAAAAAAAEAAAAAAAAAAAABABAAAAAAH0AAAAAAADZlc2RzAAAAAAOAgIAlAAIABICAgBdAFQAAAAAAH0AAAAEcBYCAgAUViFblAAaAgIABAgAAABRidHJ0AAAAAAAAH0AAAAEcAAAAIHN0dHMAAAAAAAAAAgAAACAAAAQAAAAAAQAAAQAAAAAoc3RzYwAAAAAAAAACAAAAAQAAAAEAAAABAAAAAgAAAAgAAAABAAAAmHN0c3oAAAAAAAAAAAAAACEAAAATAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAkc3RjbwAAAAAAAAAFAAAGSQAACN4AAAkIAAAJMgAACVwAAAAac2dwZAEAAAByb2xsAAAAAgAAAAH//wAAABxzYmdwAAAAAHJvbGwAAAABAAAAIQAAAAEAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAyAAAACGZyZWUAAAM7bWRhdNwATGF2YzYzLjEuMTAyAAIwQA4AAAJvBgX//2vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9MTYgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEzMSBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTQga2V5aW50X21pbj0xIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAALZYiCAv5MUAAQv8ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmhwF/UABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmioBb1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBwAAAAZBmjsBX1ABGCAHARggBwEYIAcBGCAHARggBwEYIAcBGCAHARggBw==`,cs=null,ls=null;function us(e){e.play().catch(()=>{if(ls||cs!==e)return;let t=()=>{ds(),cs===e&&e.play().catch(()=>{})};window.addEventListener(`pointerdown`,t,{capture:!0}),ls=()=>window.removeEventListener(`pointerdown`,t,{capture:!0})})}function ds(){ls?.(),ls=null}function fs(){if(typeof document<`u`){if(!cs){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=ss,document.body.appendChild(e),cs=e}us(cs)}}function ps(){ds(),cs&&=(cs.pause(),cs.removeAttribute(`src`),cs.remove(),null)}function ms(){return typeof navigator>`u`?null:navigator.wakeLock??null}function hs(){return ut()||!Nn()}var gs=new Set,_s=null,vs=Promise.resolve(),ys=!1;async function bs(){if(gs.size===0||_s&&!_s.released)return;let e=ms();if(!e)ut()&&fs();else try{let t=await e.request(`screen`);t.addEventListener(`release`,()=>{_s===t&&(_s=null)}),_s=t}catch{}}async function xs(){ps();let e=_s;if(_s=null,e&&!e.released)try{await e.release()}catch{}}function Ss(){ys||typeof document>`u`||(ys=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&gs.size>0&&(vs=vs.then(bs))}))}function Cs(e,t){if(!hs())return;Ss();let n=gs.size>0;t?gs.add(e):gs.delete(e);let r=gs.size>0;n!==r&&(vs=vs.then(r?bs:xs))}var ws=new Set;function Ts(){if(typeof window<`u`)return window.PS5UploadPad}function Es(e,t){let n=ws.size>0;t?ws.add(e):ws.delete(e);let r=ws.size>0;if(n!==r)try{Ts()?.setActive(r)}catch{}}var Ds=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}},Os=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 Ds(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}},ks=`ps5upload.join.muted`,As=5e3,js=Object.fromEntries(Object.entries(Ma).filter(([e])=>e!==`Escape`)),Ms=new Set;function Ns(e){if(!(e.code in js)||e.ctrlKey||e.metaKey||e.altKey)return!1;let t=e.target;if(e.code===`Tab`&&(e.shiftKey||Ps(t)))return!1;let n=t?.tagName;return!(n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t?.isContentEditable||Ps(t))}function Ps(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 Fs=!1;function Is(e){Fs=e}function Ls(e,t,n=null){if(!e||e.frames===0&&!t)return null;let r=e.snapshot();return r&&{...r,...t?{problem:t}:{},...n??{}}}function Rs(){if(Fs)return{...Aa};let e=Wa(Ya(typeof navigator>`u`?void 0:navigator),xo),t=Ko.touchPad;return{...Ga(Ga(e,Pa(Ms,js)),t),touch:t.touch??null,motion:Ko.motion??null}}var zs=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:Vs(),path:null},this.client=new Ro({url:e.url,invite:e.invite,code:e.code??null,name:e.name,WebSocketImpl:e.transport,readPad:Rs,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:()=>Ls(this.player?.stats??null,this.snap.problem,this.player?.soundReport()??null),onCodec:(e,t,n)=>{let r=this.picture();r.setHevc(e),r instanceof Os&&(r.setTrack(t,!!n),t&&this.snap.problem&&this.set({problem:null}))},onRumble:(e,t)=>{let n=Ya(typeof navigator>`u`?void 0:navigator);Ka(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=aa(e=>this.set({problem:e}),`player`,()=>this.client.askKeyframe());this.player=this.opts.transport?new Os(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`?Ms.clear():this.player?.resumeSound(),this.client.setNeutral(document.visibilityState===`hidden`)},t=()=>{Ms.clear(),this.client.setNeutral(!0)},n=e=>{this.client.current.kind===`joined`&&Ns(e)&&(!this.opts.keysLive||this.opts.keysLive())&&(e.preventDefault(),Ms.add(e.code))},r=e=>{Ms.delete(e.code)&&Ns(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()},As);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),Ms.clear()}),this.client.start()}setMuted(e){this.player?.setMuted(e);try{localStorage.setItem(ks,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();Ko.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 Bs(e){return(0,E.useSyncExternalStore)(e.subscribe,()=>e.snapshot)}function Vs(){try{return typeof localStorage<`u`&&localStorage.getItem(ks)===`1`}catch{return!1}}function Hs(e){let t=()=>{let t=e.snapshot.stage.kind,n=t!==`refused`&&t!==`ended`;Cs(`play-together`,n),Es(`play-together`,n)};t();let n=e.subscribe(t);return()=>{n(),Cs(`play-together`,!1),Es(`play-together`,!1)}}var Us=3e3,Ws=class{constructor(e,t=Us){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 Gs(e,t,n=!1){let[r,i]=(0,E.useState)(!0),a=(0,E.useRef)(null);(0,E.useEffect)(()=>{let e=new Ws(i);return a.current=e,()=>{e.dispose(),a.current=null}},[]),(0,E.useEffect)(()=>{a.current?.set(e,t,n)},[e,t,n]);let o=(0,E.useCallback)(()=>a.current?.poke(),[]),s=(0,E.useCallback)(()=>a.current?.hide(),[]),c=(0,E.useCallback)(()=>a.current?.toggle(),[]);return{shown:!e||t||r,poke:o,hide:s,toggle:c}}var Ks=3e4,qs=class{constructor(e,t=Ks){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 Js(e){let[,t]=(0,E.useState)(0),[n]=(0,E.useState)(()=>new qs(()=>t(e=>e+1)));return(0,E.useEffect)(()=>{n.set(e),t(e=>e+1)},[n,e]),(0,E.useEffect)(()=>()=>n.reset(),[n]),n.shown}var Ys=()=>Ya(typeof navigator>`u`?void 0:navigator).filter(e=>!!e?.connected);function Xs(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===z.CROSS)return e(`join_check_bottom`,void 0,`Press the bottom face button (✕)`);if(t.bit===z.CIRCLE)return e(`join_check_right`,void 0,`Press the right face button (○)`);if(t.bit===z.SQUARE)return e(`join_check_left`,void 0,`Press the left face button (□)`);if(t.bit===z.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 Zs(e,t){let n=(0,E.useRef)(t);(0,E.useEffect)(()=>{n.current=t}),(0,E.useEffect)(()=>{if(e===null)return;let t=0,r=()=>{n.current(Ys().find(t=>t.index===e)??null),t=window.requestAnimationFrame(r)};return t=window.requestAnimationFrame(r),()=>window.cancelAnimationFrame(t)},[e])}var Qs=[[z.CROSS,`✕`],[z.CIRCLE,`○`],[z.SQUARE,`□`],[z.TRIANGLE,`△`],[z.UP,`↑`],[z.DOWN,`↓`],[z.LEFT,`←`],[z.RIGHT,`→`],[z.L1,`L1`],[z.R1,`R1`],[z.L3,`L3`],[z.R3,`R3`],[z.SHARE,`Create`],[z.OPTIONS,`Options`],[z.PS,`PS`],[z.TOUCHPAD,`Touchpad`]];function $s({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,B.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,B.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,B.jsxs)(`div`,{className:`space-y-2`,"data-testid":`join-pad-test`,"data-buttons":e.buttons,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[Qs.map(([n,r])=>(0,B.jsx)(`span`,{className:t((e.buttons&n)!==0),"data-on":(e.buttons&n)===0?`0`:`1`,children:r},n)),(0,B.jsx)(`span`,{className:t(e.l2>30),children:`L2`}),(0,B.jsx)(`span`,{className:t(e.r2>30),children:`R2`})]}),(0,B.jsxs)(`div`,{className:`flex gap-3`,children:[n(e.lx,e.ly,`L`),n(e.rx,e.ry,`R`)]})]})}function ec({onClose:e}){let t=Fe(),[n,r]=(0,E.useState)(()=>Ys().map(e=>({index:e.index,id:e.id}))),[i,a]=(0,E.useState)(()=>Ys()[0]?.index??null),[o,s]=(0,E.useState)(Aa),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(0),[f,p]=(0,E.useState)(vo),[m,h]=(0,E.useState)(null),[g,_]=(0,E.useState)(null);(0,E.useEffect)(()=>(Is(!0),()=>Is(!1)),[]),(0,E.useEffect)(()=>{let e=()=>{let e=Ys();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)}},[]),Zs(i,e=>{if(_(t=>t?.id===e?.id?t:e),!e)return;if(c){c.feed(To(e))&&v(c,e);return}let t=Wa([e],xo);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 v=(e,n)=>{if(!e.done)return d(e.step);let r=n?.id??g?.id;l(null),r&&(p(yo(r,e.profile(n?Co(n):void 0))),h(t(`join_check_saved`,void 0,`Saved for this controller on this device. Try it below.`)))},y=()=>{h(null),d(0),l(new Po(Mo))},b=g,x=b?So(b):null,S=!!(b&&f[b.id]);return(0,B.jsx)(`div`,{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,B.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,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(me,{size:16,className:`text-white/70`}),(0,B.jsx)(`p`,{className:`flex-1 font-semibold`,children:t(`join_check_title`,void 0,`Check your controller`)}),(0,B.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,B.jsx)(Ee,{size:15})})]}),b?(0,B.jsxs)(B.Fragment,{children:[n.length>1&&(0,B.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:n.map(e=>(0,B.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:eo(e.id)},`${e.index}-${e.id}`))}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`p`,{className:`truncate font-medium`,"data-testid":`join-pad-check-name`,children:eo(b.id)}),(0,B.jsx)(`p`,{className:`text-xs text-white/60`,"data-testid":`join-pad-check-kind`,"data-kind":x??``,children:x===`saved`?t(`rp_pad_mapped`,void 0,`Plays with your mapping`):x===`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`)}),ro(b)&&(0,B.jsx)(Wo,{id:b.id,className:`mt-1 block text-xs text-amber-200/90`})]}),c?(0,B.jsxs)(`div`,{className:`space-y-3`,"data-testid":`join-pad-learn`,children:[(0,B.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,B.jsx)(`p`,{className:`text-lg font-semibold`,"data-testid":`join-pad-learn-step`,children:c.current?Xs(t,c.current):``}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:()=>{c.skip(),v(c,b)},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,B.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,B.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,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)($s,{pad:o}),m&&(0,B.jsx)(`p`,{className:`text-xs text-emerald-300`,role:`status`,children:m}),(0,B.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:y,className:`rounded-full bg-white px-3 py-1.5 text-xs font-medium text-black`,"data-testid":`join-pad-learn-start`,children:S?t(`join_check_redo`,void 0,`Redo`):t(`join_check_map`,void 0,`Set up the buttons`)}),S&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>{p(yo(b.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,B.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,B.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 tc(e,t){let[n,r]=(0,E.useState)(!1);return(0,E.useEffect)(()=>{if(!e||!t)return;let n=!0;return ze(e,Ie).then(e=>{n&&!e&&r(!0)}),()=>{n=!1}},[e,t]),n}function nc({href:e}){let t=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center`,"data-testid":`open-on-wifi`,children:[(0,B.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,B.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 rc(e){let t=Math.max(0,Math.ceil(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`}var ic=`ps5upload.join.guided`,ac=1;function oc(e){return e.player!==ac&&(!e.guided||e.movedOff)&&!e.reconnecting}function sc(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 cc(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 lc(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 cc(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 cc(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 uc(e){let[t,n]=(0,E.useState)(()=>Date.now());return(0,E.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),500);return()=>window.clearInterval(t)},[e]),t}function dc(){let[e,t]=(0,E.useState)({ready:!1,pressed:!1,id:null,kind:null,weak8BitDo:!1});return(0,E.useEffect)(()=>{let e=()=>{let e=Ya(typeof navigator>`u`?void 0:navigator).find(e=>!!e?.connected),n=!!e,r=n?Rs():null,i=!!r&&(r.buttons!==0||r.l2>30||r.r2>30),a=e?.id??null,o=e?So(e):null,s=!!e&&ro(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 pc=14,mc=()=>typeof window<`u`&&!!window.matchMedia?.(`(pointer: coarse)`).matches,hc={good:`var(--color-good,#32d074)`,fair:`var(--color-warn,#ffb340)`,slow:`var(--color-bad,#ff6961)`,none:`rgba(255,255,255,.5)`};function gc({text:e,body:t,onCancel:n}){let r=Fe();return(0,B.jsxs)(`div`,{className:`flex flex-col items-center gap-5 px-6 py-10 text-center`,"data-testid":`join-waiting`,children:[(0,B.jsxs)(`div`,{className:`relative flex h-24 w-24 items-center justify-center`,"aria-hidden":!0,children:[(0,B.jsx)(`span`,{className:`absolute inset-0 animate-ping rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`absolute inset-3 animate-pulse rounded-full bg-white/10 [animation-duration:2.4s]`}),(0,B.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center rounded-full bg-white/15`,children:(0,B.jsx)(Se,{size:26})})]}),(0,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-stage`,children:e}),t&&(0,B.jsx)(`p`,{className:`max-w-sm text-sm text-white/60`,children:t}),(0,B.jsx)(`button`,{type:`button`,onClick:n,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 _c({session:e,inApp:t=!1,onLeave:n,onAgain:r,onFullscreen:i,lanUrl:a=null,hubDown:o=!1}){let s=Fe(),c=Bs(e),{stage:l,status:u}=c,d=c.host??s(`join_host_fallback`,void 0,`your friend`),f=(0,E.useRef)(null),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(()=>It(ic)===`1`),[_,v]=(0,E.useState)(()=>typeof window<`u`&&window.innerHeight>window.innerWidth),y=dc(),[b,x]=(0,E.useState)(!1),S=l.kind===`reconnecting`,ee=uc(S),C=l.kind===`joined`||S,w=u?.state===`picking_user`,te=l.kind===`joined`||l.kind===`reconnecting`?l.player:0,[T,ne]=(0,E.useState)(!1),re=(0,E.useRef)(te);(0,E.useEffect)(()=>{re.current===ac&&te>ac&&ne(!0),te&&(re.current=te)},[te]);let[ie,ae]=(0,E.useState)(!1),[oe,se]=(0,E.useState)(!1),D=C&&(p||!t),O=mc(),ce=Js(w),ue=Gs(D,S||ce&&!O||ie||oe,O),{poke:de}=ue,pe=(0,E.useRef)(null),he=()=>{pe.current&&clearTimeout(pe.current.timer),pe.current=null};(0,E.useEffect)(()=>he,[]);let[_e,ve]=(0,E.useState)(!1),ye=(0,E.useRef)(!1);(0,E.useEffect)(()=>{if(!D||!O||ue.shown||!h||ye.current)return;ye.current=!0,ve(!0);let e=setTimeout(()=>ve(!1),6e3);return()=>clearTimeout(e)},[D,O,ue.shown,h]),(0,E.useEffect)(()=>{if(!C)return;let t=e.element;return f.current?.appendChild(t),()=>t.remove()},[C,e]),(0,E.useEffect)(()=>{if(!C||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)}},[C,c.sound,e]),(0,E.useEffect)(()=>{let e=()=>v(window.innerHeight>window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,E.useEffect)(()=>{if(p)return()=>void i?.(!1)},[p,i]);let A=(0,E.useRef)(p);(0,E.useEffect)(()=>{A.current=p},[p]),(0,E.useEffect)(()=>{if(!t||!C||!mc()||typeof window>`u`||!window.matchMedia)return;let e=window.matchMedia(`(orientation: landscape)`),n=()=>{e.matches&&!A.current&&(m(!0),i?.(!0))};return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[t,C,i]),(0,E.useEffect)(()=>{if(!C)return;let e=e=>{e.key===`Escape`&&(de(),p&&m(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[C,p,de]),(0,E.useEffect)(()=>{if(!p||!mc())return;window.history.pushState(window.history.state,``);let e=window.location.href,t=!1,n=()=>{t=!0,m(!1)};return window.addEventListener(`popstate`,n),()=>{window.removeEventListener(`popstate`,n),!t&&window.location.href===e&&window.history.back()}},[p]),(0,E.useEffect)(()=>{if(!p||typeof document>`u`)return;let e=()=>{document.fullscreenElement||mc()||m(!1)};return document.addEventListener(`fullscreenchange`,e),()=>document.removeEventListener(`fullscreenchange`,e)},[p]);let xe=()=>{e.leave(),n()};if(l.kind===`connecting`||l.kind===`asking`)return(0,B.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`,children:[l.kind===`connecting`&&o&&a&&(0,B.jsx)(nc,{href:a}),(0,B.jsx)(gc,{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:xe})]});if(l.kind===`refused`||l.kind===`ended`){let i=l.kind===`refused`||l.why!==`left`&&l.why!==`mismatch`;return(0,B.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,children:[(0,B.jsx)(Se,{size:28,className:`text-white/60`}),(0,B.jsx)(`p`,{className:`max-w-sm text-base`,"data-testid":`join-ended-text`,children:lc(s,l,d,e.opts.internet??!!e.opts.transport)}),a&&l.why===`no_hub`&&(0,B.jsx)(nc,{href:a}),(0,B.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[i&&(0,B.jsx)(`button`,{type:`button`,onClick:r,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,B.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-full bg-white/15 px-4 py-2 text-sm`,"data-testid":`join-done`,children:s(`join_done`,void 0,`Done`)})]})]})}let Ce=l.player,M=c.light??it(Ce),Te=c.rttMs??u?.rttMs??null,Ee=rt(Te),De=mc(),Oe=C&&!S&&!y.ready&&De&&(!t||p),ke=oc({player:Ce,guided:h,movedOff:T,reconnecting:S}),Ae=Ce===ac,je=u?.playsAs??null,Me=S?(l.deadline-ee)/1e3:0,Ne=async()=>{let e=!p;m(e),await i?.(e)},Pe=t&&!p&&De&&C,Ie=(0,B.jsxs)(B.Fragment,{children:[(0,B.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,B.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{background:`rgb(${M[0]},${M[1]},${M[2]})`}}),t&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[s(`join_playing_at`,{host:d},`Playing at ${d}'s`),` · `]}),s(`join_you_are`,{n:Ce},`You are Player ${Ce}`)]}),Te!=null&&(0,B.jsxs)(`span`,{className:`rounded-full bg-black/60 px-2 py-1 tabular-nums`,style:{color:hc[Ee]},"data-testid":`join-delay`,"data-tone":Ee,"data-path":c.path??void 0,children:[c.path&&(0,B.jsxs)(`span`,{className:`text-white/80`,children:[sc(s,c.path),` · `]}),Math.round(Te),` ms`]}),Ae&&(0,B.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.`)}),je&&!Ae&&(0,B.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:je},`You're playing as ${je}. No need to pick one.`)}),w&&!Ae&&u?.seatNote&&(0,B.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.`)}),w&&!Ae&&(0,B.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`)})]}),Le=(0,B.jsxs)(B.Fragment,{children:[D&&O&&ue.shown&&!S&&(0,B.jsxs)(`button`,{type:`button`,onClick:ue.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,B.jsx)(fe,{size:13}),s(`join_hide_controls`,void 0,`Hide`)]}),!c.sound&&(0,B.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,B.jsx)(we,{size:13}),s(`join_sound`,void 0,`Tap for sound`)]}),c.sound&&!c.noSound&&(0,B.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,B.jsx)(N,{size:13}):(0,B.jsx)(we,{size:13}),c.muted?s(`rp_unmute`,void 0,`Sound on`):s(`rp_mute`,void 0,`Mute`)]}),c.noSound&&(0,B.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,B.jsx)(N,{size:13}),s(`join_no_sound`,void 0,`No sound in this browser`)]}),(t||typeof document<`u`&&!!document.documentElement.requestFullscreen)&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>void Ne(),"aria-label":p?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:p?(0,B.jsx)(be,{size:13}):(0,B.jsx)(k,{size:13})}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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,B.jsx)(me,{size:13})}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:13}),s(`join_leave`,void 0,`Leave`)]})]}),Re=ue.shown?`opacity-100`:`pointer-events-none opacity-0`,ze={"data-testid":`join-bar`,"data-shown":ue.shown?`1`:`0`,onFocus:e=>{e.target.matches?.(`:focus-visible`)&&se(!0)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||se(!1)},onPointerEnter:e=>{e.pointerType===`mouse`&&ae(!0)},onPointerLeave:()=>ae(!1)};return(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`${p||!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)]`} select-none text-white [-webkit-touch-callout:none]`,style:{touchAction:`none`},onPointerMove:e=>{if(e.pointerType===`mouse`)return de();let t=pe.current;t&&t.id===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>pc&&he()},onPointerDown:e=>{if(fc(e.target))return;if(e.pointerType===`mouse`||!O)return de();if(e.target.closest?.(`[data-testid="join-bar"], button, a, input, [role="button"]`))return;he();let{pointerId:t,clientX:n,clientY:r}=e;pe.current={id:t,x:n,y:r,timer:setTimeout(()=>{pe.current=null,navigator.vibrate?.(15),ue.toggle()},450)}},onPointerUp:he,onPointerCancel:he,onPointerLeave:he,"data-testid":`join-stage-view`,children:[(0,B.jsx)(`div`,{ref:f,className:`pointer-events-none absolute inset-0 z-0 flex items-center justify-center`,"aria-hidden":!0}),D&&!ue.shown&&!S&&Te!=null&&(0,B.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:hc[Ee],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(Te),` ms`]}),Oe?(0,B.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 ${Re}`,...ze,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Ie}),(0,B.jsx)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:Le})]}):Pe?null:(0,B.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 ${Re}`,...ze,children:[Ie,(0,B.jsx)(`span`,{className:`flex-1`}),Le]}),!ue.shown&&!Oe&&(0,B.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),de()},"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,B.jsx)(le,{size:16,"aria-hidden":!0})}),_e&&!ue.shown&&(0,B.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,B.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.`)}),b&&(0,B.jsx)(ec,{onClose:()=>x(!1)}),Oe&&(0,B.jsx)(os,{stream:e,layout:`overlay`,onMenu:()=>ue.shown?ue.hide():de()}),!Oe&&!S&&(0,B.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 ${Re}`,"data-testid":`join-pad`,children:[(0,B.jsx)(me,{size:14,style:{color:y.pressed?`rgb(${M[0]},${M[1]},${M[2]})`:void 0}}),y.ready?(0,B.jsxs)(`span`,{className:`flex flex-col items-start gap-1`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_ready`,void 0,`Your controller is ready`)}),y.weak8BitDo&&y.id&&(0,B.jsx)(Wo,{id:y.id,className:`text-amber-200/90`}),y.kind===`guess`&&to()&&(0,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>x(!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`)})]})]}):De&&t&&!p?s(`join_full_to_play`,void 0,`Tap full screen to play with the on-screen controller.`):(0,B.jsxs)(`span`,{className:`flex flex-col`,children:[(0,B.jsx)(`span`,{children:s(`join_pad_none`,void 0,`Connect a controller (USB or Bluetooth) and press any button.`)}),(0,B.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.`)})]})]}),u?.blockSystem&&u.state===`playing`&&!Oe&&(0,B.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 ${Re}`,"data-testid":`join-blocked`,children:s(`join_block_note`,{host:d},`${d} turned off PS and Create for friends.`)}),ce&&!Ae&&O&&!ue.shown&&!S&&(0,B.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`)}),ke&&!je&&(0,B.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,B.jsx)(`p`,{className:`font-semibold`,children:s(`join_guide_title`,void 0,`One more step on the TV`)}),(0,B.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,B.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,B.jsx)(`button`,{type:`button`,onClick:()=>{Ft(ic,`1`),g(!0),ne(!1)},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`)})]}),S&&(0,B.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,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:14}),s(`join_leave`,void 0,`Leave`)]}),(0,B.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,B.jsx)(`p`,{className:`max-w-sm text-base font-medium`,"data-testid":`join-host-away`,children:s(`join_host_away`,{time:rc(Me)},`The host stopped playing — waiting for them to start again (${rc(Me)})`)}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`text-base font-medium`,children:s(`join_reconnecting`,void 0,`Reconnecting…`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/70`,"data-testid":`join-reconnecting-left`,children:s(`join_reconnecting_left`,{time:rc(Me)},`Your place is kept for ${rc(Me)}.`)})]})]}),!t&&C&&_&&De&&(0,B.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-16 z-20 flex justify-center`,children:(0,B.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,B.jsx)(j,{size:14}),s(`pad_turn`,void 0,`Turn the phone sideways`)]})})]}),Pe&&(0,B.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,B.jsx)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-2`,children:Ie}),(0,B.jsxs)(`button`,{type:`button`,onClick:()=>void Ne(),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,B.jsx)(k,{size:15}),s(`pad_fill`,void 0,`Full screen`)]}),c.sound&&!c.noSound?(0,B.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,B.jsx)(N,{size:16}):(0,B.jsx)(we,{size:16})}):c.sound?null:(0,B.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,B.jsx)(we,{size:15}),s(`join_sound`,void 0,`Tap for sound`)]}),(0,B.jsxs)(`button`,{type:`button`,onClick:xe,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,B.jsx)(ge,{size:15}),s(`join_leave`,void 0,`Leave`)]})]})]})}var vc=`ps5upload.join.name`;function yc(e){return/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:``}function bc(e){return e.trim().slice(0,32)}function xc(e=``){return bc(It(`ps5upload.join.name`)??``)||e}function Sc(e){let t=bc(e);return t&&Ft(vc,t),t}function Cc(e){try{return!!sessionStorage.getItem(Lo(e))}catch{return!1}}async function wc(e){try{e?(await document.documentElement.requestFullscreen?.({navigationUI:`hide`}),await screen.orientation.lock?.(`landscape`)):document.fullscreenElement&&await document.exitFullscreen()}catch{}}function Tc({url:e,invite:t,host:n,transport:r,lanUrl:i=null,path:a=null,internet:o}){let s=Fe(),c=tc(r&&o!==!1?e:null,i),[l,u]=(0,E.useState)(()=>xc(yc(typeof navigator>`u`?``:navigator.userAgent))),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(0),h=i=>{let s=Sc(i);if(!s)return;let c=new zs({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,E.useEffect)(()=>{!d&&Cc(t)&&l.trim()&&h(l)},[]),(0,E.useEffect)(()=>d?Hs(d):void 0,[d]),(0,E.useEffect)(()=>{if(!d)return;let e=()=>d.stop();return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[d]),d)return(0,B.jsx)(_c,{session:d,lanUrl:i,hubDown:c,onLeave:()=>f(null),onAgain:()=>{d.stop(),h(l)},onFullscreen:wc},p);let g=n??s(`join_host_fallback`,void 0,`your friend`),_=(0,B.jsx)(`div`,{className:`flex min-h-[100dvh] items-center justify-center bg-black px-6 text-white`,"data-testid":`join-name-step`,children:(0,B.jsxs)(`form`,{className:`w-full max-w-sm space-y-4 rounded-2xl border border-white/10 bg-neutral-900 p-6`,onSubmit:e=>{e.preventDefault(),h(l)},children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,B.jsx)(`span`,{className:`flex h-10 w-10 items-center justify-center rounded-full bg-white/10`,children:(0,B.jsx)(Se,{size:20})}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`h1`,{className:`text-lg font-semibold`,children:s(`join_title`,void 0,`Join a friend's game`)}),(0,B.jsx)(`p`,{className:`text-sm text-white/60`,children:s(`join_title_body`,{host:g},`Play on ${g}'s PS5 as Player 2, 3 or 4.`)})]})]}),(0,B.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,B.jsx)(`span`,{className:`text-sm font-medium`,children:s(`join_name_label`,void 0,`Your name`)}),(0,B.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,B.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,B.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,B.jsx)(nc,{href:i})]})});return t?(0,B.jsx)(Uo,{appLink:nt(location.href),children:_}):_}function Ec(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 Dc(e,t){let n=Ec(e),r=Ec(t);return n===1||r===1?`tailscale`:r===0?`lan`:r===2?`internet`:null}function Oc(e){let t=(e??``).toLowerCase();if(t.endsWith(`.local`))return`lan`;if(t.endsWith(`.ts.net`))return`tailscale`;let n=Ec(t);return n===0?`lan`:n===1?`tailscale`:null}function kc(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 Dc(a(i.localCandidateId),a(i.remoteCandidateId))}function Ac(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``);return`${t===`localhost`||t===`127.0.0.1`||t===`::1`?`ws`:`wss`}://${e}/ws`}function jc(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 Mc(e,t){let n=jc(e);return n!==null&&n===t.toUpperCase()}var Nc=16777216;function Pc(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 Ic(e){let t=new Uint8Array(9);return t[0]=3,t.set(e.subarray(0,8),1),t}var Lc=[`stun:stun.cloudflare.com:3478`,`stun:stun.l.google.com:19302`],Rc=1500,zc=2e4;function Bc(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 Vc=null;function Hc(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 Uc(e,t={}){let n=t.WebSocketImpl??(typeof WebSocket>`u`?void 0:WebSocket);if(!n||Vc)return;let r=Ac(e.hub),i;try{i=new n(r)}catch{return}let a={url:r,room:e.room,ws:i,msgs:[],timer:null};Vc=a;let o=()=>{Vc===a&&(Vc=null,a.timer&&clearTimeout(a.timer),Hc(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 Wc(e,t){let n=Vc;return n?(Vc=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`)?(Hc(n.ws),null):{ws:n.ws,msgs:n.msgs}):null}function Gc(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 Fc,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??Ac(e.hub),a=t.signalUrl||t.lan?null:Wc(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:Lc}]})}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=Bc(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?!Mc(t.sdp,e.fp):jc(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(Ic(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 kc(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 Pc(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+zc,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()},Rc),!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(Ve,`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 Kc=3e3;function qc(e,t){return/^https?:\/\/[^/?#]+(\/[^?#]*)?\/join\/?$/.test(e)?e.replace(/^http/,`ws`).replace(/\/join\/?$/,`/${t}`):null}var Jc=e=>qc(e,`api/join/signal`);function Yc(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?Jc(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?qc(e.lan,`api/join/ws`):null;if(n){let r=e.reach(n);t.push({via:`socket`,make:()=>e.socket(r)})}return t}var Xc=new Map;function Zc(e,t,n=300,r=Kc){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 Qc(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(He(e.e)??``));return t&&(He(t.e)!==`no_hub`||!n)?t.e:n?n.e:t?.e??e[e.length-1]?.e??null}function $c(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=Zc(n.map(e=>e.via),Xc.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)&&He(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(Qc(this.closes))}}won(e,n){if(this.readyState!==0)return;this.winner=e,Xc.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}var el=new URLSearchParams(location.hash.slice(1)),tl=el.get(`n`)?.trim()||null,nl=tt(location.hash);nl&&Uc(nl);var rl=(0,x.createRoot)(document.getElementById(`root`));if(nl){let e=Gc(nl,{video:!0,log:e=>console.info(`[join] ${e}`)}),t=Le(location.hash,`join`);rl.render((0,B.jsx)(Tc,{url:Ac(nl.hub),invite:nl.key,host:tl,transport:e,lanUrl:t?Re(t,{key:nl.key}):null}))}else{let e=el.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:$c(()=>Yc({net:null,lan:i,ts:null,fp:et(el.get(`fp`)),rtc:!0,reach:e=>e,rtcMake:(e,t)=>Gc(e,{video:!0,log:r,...t}),socket:e=>new WebSocket(e)}),{room:i,log:r});rl.render((0,B.jsx)(Tc,{url:n,invite:e,host:tl,path:Oc(location.hostname),transport:a,internet:!1}))} diff --git a/site/pad/index.html b/site/pad/index.html index d9893367e..c35b03638 100644 --- a/site/pad/index.html +++ b/site/pad/index.html @@ -268,7 +268,7 @@ ã/¸Ä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.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)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)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.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(){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`,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})}))} From 94f17b9eadbbfce445dcfbb433b324714501c761 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:42:15 -0800 Subject: [PATCH 18/25] Bug report: a console not probed yet no longer gets the selected console's status buildPs5Snapshot for another console fell back to the selected console's connection state when runtimeByHost had no record for it. The report then showed the selected console's helper version and kernel for the other one, and its 'up' started a full read of a console that was never reached. An unprobed console now reads as unknown (EMPTY_HOST_RUNTIME). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/lib/ps5Snapshot.test.ts | 17 +++++++++++++++++ client/src/lib/ps5Snapshot.ts | 9 +++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/client/src/lib/ps5Snapshot.test.ts b/client/src/lib/ps5Snapshot.test.ts index e47c912d0..c6a5ccf4c 100644 --- a/client/src/lib/ps5Snapshot.test.ts +++ b/client/src/lib/ps5Snapshot.test.ts @@ -25,6 +25,23 @@ describe("buildPs5Snapshot (disconnected)", () => { expect(Object.keys(snapshot.errors)).toHaveLength(0); }); + it("a console not probed yet gets no status of the selected one", async () => { + useConnectionStore.setState({ + host: "10.0.0.2", + payloadStatus: "down", + payloadVersion: "12.6.28", + ps5Kernel: "r229358/releases/13.60", + ucredElevated: true, + runtimeByHost: {}, + }); + const { snapshot } = await buildPs5Snapshot({ redact: false, host: "10.0.0.9" }); + expect(snapshot.host).toBe("10.0.0.9"); + expect(snapshot.payload_version).toBeNull(); + expect(snapshot.ps5_kernel).toBeNull(); + expect(snapshot.ucred_elevated).toBeNull(); + expect(snapshot.connected).toBe(false); + }); + it("treats payload 'up' with an empty host as disconnected", async () => { useConnectionStore.setState({ host: "", payloadStatus: "up" }); const { snapshot } = await buildPs5Snapshot({ redact: false }); diff --git a/client/src/lib/ps5Snapshot.ts b/client/src/lib/ps5Snapshot.ts index 70642c143..c64cee890 100644 --- a/client/src/lib/ps5Snapshot.ts +++ b/client/src/lib/ps5Snapshot.ts @@ -1,6 +1,6 @@ import { invoke } from "./invokeLogged"; -import { useConnectionStore } from "../state/connection"; +import { EMPTY_HOST_RUNTIME, useConnectionStore } from "../state/connection"; import { hostOf, mgmtAddr, transferAddr } from "./addr"; import { redactHost } from "./diagnosticBundle"; import { blackBoxFor, recordBlackBox } from "./payloadBlackBox"; @@ -337,7 +337,12 @@ export async function buildPs5Snapshot(opts: { }): Promise { const live = useConnectionStore.getState(); const host = (opts.host ?? live.host)?.trim() ?? ""; - const rt = opts.host && hostOf(opts.host) !== hostOf(live.host) ? live.runtimeByHost[hostOf(opts.host)] : undefined; + // Another console with no record yet (never probed) is unknown, not the selected one: its + // version and kernel went into the report, and its "up" let a full read of the other one run. + const rt = + opts.host && hostOf(opts.host) !== hostOf(live.host) + ? (live.runtimeByHost[hostOf(opts.host)] ?? EMPTY_HOST_RUNTIME) + : undefined; const conn = rt ? { ...live, From 0b53937b1e07ffd23aafbd8b1d04a81192febf66 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:43:22 -0800 Subject: [PATCH 19/25] Helper send: the new helper's status goes into the console's own record When a sent helper answered, onUp wrote only the flat fields of the selected console, not runtimeByHost. A switch to another tab and back restored the old record (an older version, or down), and everything that reads runtimeByHost (tab dots, the Convert firmware note, launch hints) kept the old helper until the next status poll. It now uses setHostStatus, which mirrors to the screen while that console is selected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- client/src/state/helperSendRuntime.test.ts | 21 +++++++++++++++++++++ client/src/state/helperSendRuntime.ts | 9 +++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/client/src/state/helperSendRuntime.test.ts b/client/src/state/helperSendRuntime.test.ts index 761e999bb..375f2ba32 100644 --- a/client/src/state/helperSendRuntime.test.ts +++ b/client/src/state/helperSendRuntime.test.ts @@ -77,6 +77,27 @@ describe("sendHelperTo and the copies the PS5 starts at boot", () => { }); }); +describe("the new helper answering", () => { + const H = "192.168.0.9"; + type OnUp = (h: string, s: { payloadVersion: string; ps5Kernel: string; ucredElevated: boolean; priorInstance: null }) => void; + const up = { payloadVersion: "5.37.1", ps5Kernel: "r229358/releases/13.60", ucredElevated: true, priorInstance: null }; + + it("is this console's own record too, so going to another tab and back still shows it", async () => { + runHelperSend.mockResolvedValue("ok"); + updateHelperCopiesAfterSend.mockResolvedValue([]); + useConnectionStore.getState().setHost(H); + useConnectionStore.getState().setHostStatus(H, { payloadStatus: "down", payloadVersion: "5.30.0" }); + await sendHelperTo(H, tr); + (runHelperSend.mock.calls[0][1] as { onUp: OnUp }).onUp(H, up); + expect(useConnectionStore.getState().payloadVersion).toBe("5.37.1"); + useConnectionStore.getState().setHost("192.168.0.10"); + useConnectionStore.getState().setHost(H); + expect(useConnectionStore.getState().payloadStatus).toBe("up"); + expect(useConnectionStore.getState().payloadVersion).toBe("5.37.1"); + expect(useConnectionStore.getState().runtimeByHost[H]?.ps5Kernel).toBe(up.ps5Kernel); + }); +}); + describe("sendHelperAndWait", () => { const H = "192.168.0.9"; beforeEach(() => { diff --git a/client/src/state/helperSendRuntime.ts b/client/src/state/helperSendRuntime.ts index e7924a20d..dd91bb5ed 100644 --- a/client/src/state/helperSendRuntime.ts +++ b/client/src/state/helperSendRuntime.ts @@ -222,17 +222,18 @@ export async function sendHelperTo( if (conn().host === h) conn().setStatus({ payloadProbing: on }); }, onUp: (h, status) => { - if (conn().host !== h) return; - conn().setStatus({ + // The console's own record, mirrored to the screens while it is the selected one: the + // flat fields alone were put back to the record's old "down" by a switch to another + // tab and back, hiding the new helper until the next status poll. + conn().setHostStatus(h, { payloadStatus: "up", - payloadStatusHost: h, payloadVersion: status.payloadVersion, ps5Kernel: status.ps5Kernel, ucredElevated: status.ucredElevated, priorInstance: status.priorInstance, power: "awake", - payloadProbing: false, }); + if (conn().host === h) conn().setStatus({ payloadProbing: false }); }, onOk: (h, msg) => { if (conn().host === h) conn().setStep2("ok", msg); From d05df3599d99fe374c12611b846c5530f4c8bed6 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:35:58 -0800 Subject: [PATCH 20/25] Using a received save no longer deletes the received file Share's 'use this save' handed the received .zip to the shared-save import, which moved it into its scratch folder and then deleted that folder. The person's only copy was gone after one use, and also when the import was refused (wrong parts, too big, game running). The import now reads a file where it is; the upload endpoint still cleans up its own spool. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../crates/ps5upload-engine/src/save_copy.rs | 70 ++++++++++++++----- 1 file changed, 54 insertions(+), 16 deletions(-) diff --git a/engine/crates/ps5upload-engine/src/save_copy.rs b/engine/crates/ps5upload-engine/src/save_copy.rs index 3d81663ed..8d5f85f18 100644 --- a/engine/crates/ps5upload-engine/src/save_copy.rs +++ b/engine/crates/ps5upload-engine/src/save_copy.rs @@ -787,21 +787,21 @@ pub fn import( ) } -/// A shared save's zip: in memory (one made here a moment ago) or a file taken over from the -/// caller (one that came over the network, which can be large). +/// A shared save's zip: in memory (one made here a moment ago) or a file on disk (one that came +/// over the network, which can be large). The file is only read, where it is: it can be the +/// user's own copy (Share's received save), which a move into the scratch folder deleted along +/// with the scratch folder, used or refused. enum ZipIn<'a> { Bytes(&'a [u8]), File(&'a Path), } impl ZipIn<'_> { - fn write_to(&self, dest: &Path) -> std::io::Result<()> { + /// The zip on disk: `scratch`, written, for bytes; the file itself for a file. + fn on_disk(&self, scratch: &Path) -> std::io::Result { match self { - ZipIn::Bytes(b) => std::fs::write(dest, b), - ZipIn::File(p) => std::fs::rename(p, dest).or_else(|_| { - std::fs::copy(p, dest)?; - std::fs::remove_file(p) - }), + ZipIn::Bytes(b) => std::fs::write(scratch, b).map(|()| scratch.to_path_buf()), + ZipIn::File(p) => Ok(p.to_path_buf()), } } } @@ -825,9 +825,8 @@ fn import_as( let tmp = make_temp_dir(&title_id)?; let tmp_s = tmp.to_string_lossy().into_owned(); let result = (|| { - let zip = tmp.join("shared.zip"); - zip_in - .write_to(&zip) + let zip = zip_in + .on_disk(&tmp.join("shared.zip")) .map_err(|e| format!("save the file: {e}"))?; let unpacked = tmp.join("x"); std::fs::create_dir_all(&unpacked).map_err(|e| format!("unpack: {e}"))?; @@ -2068,13 +2067,15 @@ mod tests { } #[test] - fn a_zip_taken_from_a_file_leaves_nothing_behind() { + fn a_zip_from_a_file_is_read_where_it_is() { let tmp = make_temp_dir("zipin-test").unwrap(); - let (from, to) = (tmp.join("a"), tmp.join("b")); + let (from, scratch) = (tmp.join("a"), tmp.join("b")); std::fs::write(&from, b"zip").unwrap(); - ZipIn::File(&from).write_to(&to).unwrap(); - assert!(!from.exists()); - assert_eq!(std::fs::read(&to).unwrap(), b"zip"); + assert_eq!(ZipIn::File(&from).on_disk(&scratch).unwrap(), from); + assert_eq!(std::fs::read(&from).unwrap(), b"zip"); + assert!(!scratch.exists()); + assert_eq!(ZipIn::Bytes(b"z").on_disk(&scratch).unwrap(), scratch); + assert_eq!(std::fs::read(&scratch).unwrap(), b"z"); let _ = cleanup_temp_dir(&tmp.to_string_lossy()); } @@ -2665,6 +2666,43 @@ mod tests { share(&Fake::both(images), &folder(A)).unwrap().1 } + /// A save file on disk (Share's received save) is still there after it was used, and after + /// a refusal: it is the user's only copy. It used to be moved into the scratch folder and + /// deleted with it. + #[test] + fn a_save_file_on_disk_is_kept_used_or_refused() { + let dir = make_temp_dir("keepfile").unwrap(); + let file = dir.join("received.zip"); + std::fs::write(&file, shared_zip(&[MAIN, STAR])).unwrap(); + let c = Fake::both(&[MAIN, STAR]); + let used = import_as( + &c, + &folder(B), + B, + "this user", + ZipIn::File(&file), + None, + None, + ); + assert!(used.is_ok(), "{:?}", used.err().map(|f| f.msg)); + assert!(file.is_file(), "the received save was deleted by using it"); + let other = dir.join("other.zip"); + std::fs::write(&other, zip_of(&[("Pictures/a.png", b"x")])).unwrap(); + let c = Fake::both(&[MAIN, STAR]); + assert!(import_as( + &c, + &folder(B), + B, + "this user", + ZipIn::File(&other), + None, + None + ) + .is_err()); + assert!(other.is_file(), "a refused save file was deleted"); + let _ = cleanup_temp_dir(&dir.to_string_lossy()); + } + /// A save backup picked as a save file (#633) is called that, noted (10.6.0 on) or not, and /// nothing on the console changes. #[test] From 692ef31b18ed2edf4803f32c2270b3a4cfd48392 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:37:42 -0800 Subject: [PATCH 21/25] Remote Play keys with a non-hex character are refused, not a panic The regist key and RP key parsers sliced the text two bytes at a time after checking only its length in bytes. A non-ASCII character (a key typed into the consoles API, or one in a pairing reply) put a slice inside it and the handler panicked; a saved one panicked again on every wake or stream. Both parsers now accept hex digits only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- engine/crates/ps5upload-core/src/rp_regist.rs | 7 ++++++- engine/crates/ps5upload-core/src/rp_session.rs | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/engine/crates/ps5upload-core/src/rp_regist.rs b/engine/crates/ps5upload-core/src/rp_regist.rs index 8fc7c52b2..114092511 100644 --- a/engine/crates/ps5upload-core/src/rp_regist.rs +++ b/engine/crates/ps5upload-core/src/rp_regist.rs @@ -118,7 +118,9 @@ pub fn credential_from_regist_key(regist_key_hex: &str) -> Result { fn parse_hex(s: &str) -> Option> { let s = s.trim(); - if !s.len().is_multiple_of(2) { + // Hex digits only, before slicing in twos: a non-ASCII character put a slice inside it, + // which panicked (`u8::from_str_radix` also takes a leading `+`). + if !s.len().is_multiple_of(2) || !s.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } (0..s.len()) @@ -697,6 +699,9 @@ mod tests { assert!(credential_from_regist_key("zz").is_err()); // Valid hex, but the bytes are not hex *text*. assert!(credential_from_regist_key("ffffffff").is_err()); + // An even number of bytes that are not all hex digits: refused, never a panic. + assert!(credential_from_regist_key("a€bc").is_err()); + assert!(credential_from_regist_key("+31+32").is_err()); } #[test] diff --git a/engine/crates/ps5upload-core/src/rp_session.rs b/engine/crates/ps5upload-core/src/rp_session.rs index 189480abc..06061996a 100644 --- a/engine/crates/ps5upload-core/src/rp_session.rs +++ b/engine/crates/ps5upload-core/src/rp_session.rs @@ -117,6 +117,11 @@ fn hex16(s: &str) -> Result<[u8; KEY_SIZE]> { if s.len() != KEY_SIZE * 2 { bail!("expected {} hex chars, got {}", KEY_SIZE * 2, s.len()); } + // Before slicing: a non-ASCII character (a key typed into the API, or one a console sent) + // put a two-byte slice inside it, and the parse panicked instead of refusing it. + if !s.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!("not hex"); + } let mut out = [0u8; KEY_SIZE]; for (i, b) in out.iter_mut().enumerate() { *b = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).map_err(|_| anyhow!("not hex"))?; @@ -1456,4 +1461,14 @@ mod tests { assert!(SessionCreds::from_hex("00", "00").is_err()); assert!(SessionCreds::from_hex(&"a".repeat(32), &"b".repeat(32)).is_ok()); } + + /// 32 bytes that are not 32 hex digits are refused, not a panic (a slice inside `€`). + #[test] + fn creds_refuse_non_ascii_keys() { + let odd = format!("a€{}", "0".repeat(28)); + assert_eq!(odd.len(), 32); + assert!(SessionCreds::from_hex(&odd, &"b".repeat(32)).is_err()); + assert!(SessionCreds::from_hex(&"a".repeat(32), &odd).is_err()); + assert!(SessionCreds::from_hex(&format!("+{}", "a".repeat(31)), &"b".repeat(32)).is_err()); + } } From 3c0e25e624aecfbc0c3f08238ef38e25a661cc04 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:40:08 -0800 Subject: [PATCH 22/25] A console read reply longer than asked is cut to the ask The fs.read loop appended whatever the helper sent and then computed the bytes left as want minus what it had. A reply over the ask underflowed that: a panic in a debug build, and in a release build the loop asked on to the end of the file. Only the bytes asked for are kept now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- engine/crates/ps5upload-ava1/src/mgmt.rs | 5 +++- engine/crates/ps5upload-ava1/tests/mgmt.rs | 27 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/engine/crates/ps5upload-ava1/src/mgmt.rs b/engine/crates/ps5upload-ava1/src/mgmt.rs index 371133e21..504ea1966 100644 --- a/engine/crates/ps5upload-ava1/src/mgmt.rs +++ b/engine/crates/ps5upload-ava1/src/mgmt.rs @@ -778,7 +778,10 @@ impl AvaTransport { .await?; let r = gen::FsReadResult::decode(&r)?; let got = r.data.len(); - out.extend_from_slice(&r.data); + // Never more than was asked: a reply over it made `want - out.len()` underflow + // (a panic in a debug build, a read on to the end of the file in a release one). + let take = got.min(usize::try_from(left).unwrap_or(usize::MAX)); + out.extend_from_slice(&r.data[..take]); if r.eof != 0 || got == 0 || want == 0 { break; } diff --git a/engine/crates/ps5upload-ava1/tests/mgmt.rs b/engine/crates/ps5upload-ava1/tests/mgmt.rs index 8cb2aba85..2a03dfd37 100644 --- a/engine/crates/ps5upload-ava1/tests/mgmt.rs +++ b/engine/crates/ps5upload-ava1/tests/mgmt.rs @@ -448,6 +448,33 @@ async fn a_read_stops_at_eof_and_continues_after_a_short_read() { assert_eq!(calls.lock().unwrap().len(), 3); } +/// A node that answers with more bytes than asked: the read is still the bytes asked for. The +/// count of what was left underflowed (a panic in a debug build; in a release one the loop read +/// on to the end of the file). +#[tokio::test(flavor = "multi_thread")] +async fn a_reply_over_the_ask_is_cut_to_it() { + let file = file_bytes(4096); + let f = file.clone(); + let server: RpcHandler = Box::new(move |_, body| { + let q = gen::FsRead::decode(body).unwrap(); + let lo = (q.offset as usize).min(f.len()); + let hi = (lo + q.len as usize + 100).min(f.len()); + ok(gen::FsReadResult { + data: f[lo..hi].to_vec(), + eof: (hi == f.len()) as u8, + } + .to_bytes() + .unwrap()) + }); + let (t, _p, c) = console("over", server).await; + let body = br#"{"path":"/f","offset":0,"limit":1000}"#; + let r = call(&t, &c, m::FS_READ, "FS_READ(/f)", body, T) + .await + .unwrap() + .unwrap(); + assert_eq!(r, &file[..1000]); +} + #[tokio::test(flavor = "multi_thread")] async fn a_read_never_asks_past_the_per_call_ceiling() { let file = file_bytes(3 * 1024 * 1024); From 698b9ef5c9737ae474c128a22efd231c1ad487b2 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:44:18 -0800 Subject: [PATCH 23/25] A game's content id names the package only when it is a plain name With no name typed, a package is named after the content id in the game's param.json (PS5) or param.sfo (PS4). The only check was the PS5 id's length, so an id like ../../../../tmp/AAAA (36 characters) put the package outside the chosen folder. A PS5 build now refuses an id with anything but letters, digits, - and _ (a real one never has more), and the engine names neither kind of package after such an id. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../crates/ps5upload-engine/src/fpkg_api.rs | 16 +++++++-- engine/crates/ps5upload-fpkg/src/build.rs | 17 +++++++++ engine/crates/ps5upload-fpkg/tests/writer.rs | 35 +++++++++++++++++++ 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/engine/crates/ps5upload-engine/src/fpkg_api.rs b/engine/crates/ps5upload-engine/src/fpkg_api.rs index 8126ddb4e..13ea76aa6 100644 --- a/engine/crates/ps5upload-engine/src/fpkg_api.rs +++ b/engine/crates/ps5upload-engine/src/fpkg_api.rs @@ -534,7 +534,13 @@ pub(crate) async fn fpkg_build_handler( .clone() .filter(|n| !n.trim().is_empty()) .or_else(|| req.content_id.clone().filter(|c| !c.trim().is_empty())) - .or_else(|| inspection.content_id.clone()); + // The game's own id names the file only when it is a plain name (never `../x`). + .or_else(|| { + inspection + .content_id + .clone() + .filter(|c| build::content_id_is_plain(c)) + }); let stem = match stem { Some(s) if req.keep_both => Some( crate::folder_build::keep_both_stem(&s, |c| { @@ -829,7 +835,13 @@ async fn ps4_package_build( .name .clone() .filter(|n| !n.trim().is_empty()) - .or_else(|| inspection.content_id.clone()) + // The param.sfo's id names the file only when it is a plain name (never `../x`). + .or_else(|| { + inspection + .content_id + .clone() + .filter(|c| build::content_id_is_plain(c)) + }) .or_else(|| { source_path .file_stem() diff --git a/engine/crates/ps5upload-fpkg/src/build.rs b/engine/crates/ps5upload-fpkg/src/build.rs index 69a8c186a..60369e7d6 100644 --- a/engine/crates/ps5upload-fpkg/src/build.rs +++ b/engine/crates/ps5upload-fpkg/src/build.rs @@ -244,6 +244,17 @@ pub struct BuildControl<'a> { pub sample: Option, } +/// Whether `id` is a content id's characters only (`UP0000-PPSA00000_00-0123456789ABCDEF`: +/// letters, digits, `-`, `_`), so it can name the package file. The id comes from the game's own +/// param.json or param.sfo: one like `../../../../tmp/AAAA…` put the package outside the +/// folder chosen for it. +pub fn content_id_is_plain(id: &str) -> bool { + !id.is_empty() + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + /// Build the package. `progress` receives short phase lines. pub fn build(request: &BuildRequest, progress: &mut dyn FnMut(&str)) -> Result { build_controlled(request, progress, &mut BuildControl::default()) @@ -343,6 +354,12 @@ fn build_mode( content_id.len() )); } + if !content_id_is_plain(&content_id) { + return format_err(format!( + "content id {content_id:?} has characters a content id never has \ + (only letters, digits, - and _)" + )); + } // The packaged copy has to name the id the package is built under, both in `contentId` // (the console checks it against the transfer's own) and in `titleId` (which it reads at // GetRawContentInfo). A source that says something else is the ordinary case for a rename. diff --git a/engine/crates/ps5upload-fpkg/tests/writer.rs b/engine/crates/ps5upload-fpkg/tests/writer.rs index 4fbc0f200..89a567b3b 100644 --- a/engine/crates/ps5upload-fpkg/tests/writer.rs +++ b/engine/crates/ps5upload-fpkg/tests/writer.rs @@ -274,6 +274,41 @@ fn a_package_keeps_the_games_own_languages() { ); } +/// A game whose param.json names a content id with a path in it (36 characters, like a real +/// one) is refused: the id names the package file, which landed outside the chosen folder. +#[test] +fn a_content_id_with_a_path_in_it_is_refused() { + let source_dir = TempDir::new("cid-source"); + let output_dir = TempDir::new("cid-out"); + write_tree(source_dir.path()); + let escaped = format!("../fpkg-writer-{}-cid-escaped", std::process::id()); + let id = format!("{escaped}{}", "A".repeat(36 - escaped.len())); + assert_eq!(id.len(), 36); + std::fs::write( + source_dir.path().join("sce_sys/param.json"), + format!( + "{{\"contentId\":\"{id}\",\"contentVersion\":\"01.001.000\",\"titleId\":\"PPSA01234\",\"applicationCategoryType\":0,\"attributePub\":0}}" + ), + ) + .unwrap(); + let request = BuildRequest { + time: Some((1_700_000_000, 0)), + seed: Some([7; 16]), + ..BuildRequest::new(source_dir.path(), output_dir.path()) + }; + let Err(e) = build::build(&request, &mut |_| {}) else { + panic!("a content id with a path in it was built"); + }; + let e = e.to_string(); + assert!(e.contains("characters a content id never has"), "{e}"); + let outside = output_dir.path().join(format!("{id}.pkg")); + let outside_partial = output_dir.path().join(format!("{id}.pkg.partial")); + assert!(!outside.exists() && !outside_partial.exists()); + assert!(build::content_id_is_plain(CONTENT_ID)); + assert!(!build::content_id_is_plain("")); + assert!(!build::content_id_is_plain("UP0000-PPSA01234_00\\X")); +} + #[test] fn a_second_build_reports_warnings_but_still_verifies() { let source_dir = TempDir::new("warn-source"); From fde0e7feb802e3152df9ef38fb08c44e6ebdd58c Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:53:11 -0800 Subject: [PATCH 24/25] WebDAV reads refuse a partial answer for another range A WebDAV ranged read took any 206 as the bytes asked for. A server or a proxy that answered another range (clamped or restarted) put the wrong bytes into a copied file or a package install, which then finished as done. The answer's Content-Range must now start where the read asked, as the link fetcher already checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- .../ps5upload-engine/src/remote/webdav_fs.rs | 42 ++++++++++++++++++- .../crates/ps5upload-engine/src/remote_pkg.rs | 2 +- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/engine/crates/ps5upload-engine/src/remote/webdav_fs.rs b/engine/crates/ps5upload-engine/src/remote/webdav_fs.rs index 3f8c90631..4337543bb 100644 --- a/engine/crates/ps5upload-engine/src/remote/webdav_fs.rs +++ b/engine/crates/ps5upload-engine/src/remote/webdav_fs.rs @@ -729,6 +729,28 @@ struct WebdavInner { auth: Arc, } +/// Whether a 206's `Content-Range` (when it has one) starts where the read asked. A server or a +/// proxy that answers another range sent bytes that were copied as if they came from `offset`: +/// a package or a copied file with the wrong bytes in it, reported done. +fn partial_answers( + content_range: Option<&str>, + offset: u64, + host: &str, +) -> Result<(), RemoteError> { + let Some(value) = content_range else { + return Ok(()); + }; + match crate::remote_pkg::parse_content_range(value) { + Some((start, _)) if start == offset => Ok(()), + Some((start, _)) => Err(RemoteError::Io(format!( + "{host}: asked for bytes from {offset}, the server answered from {start}" + ))), + None => Err(RemoteError::Io(format!( + "{host}: a partial answer with an unreadable Content-Range ({value:?})" + ))), + } +} + #[async_trait::async_trait] impl RemoteFile for WebdavFile { fn size(&self) -> u64 { @@ -760,7 +782,13 @@ impl RemoteFile for WebdavFile { resp = send()?; } match resp.status().as_u16() { - 206 => {} + 206 => { + let range = resp + .headers() + .get("content-range") + .and_then(|v| v.to_str().ok()); + partial_answers(range, offset, &inner.host)?; + } // The server ignored the range: usable only from the start, and only up to len. 200 if offset == 0 => {} 200 => { @@ -1040,6 +1068,18 @@ mod typed_host_tests { mod tests { use super::*; + /// A 206 for another range than the one asked is refused, not copied as if it were it. + #[test] + fn a_partial_answer_from_another_offset_is_refused() { + assert!(partial_answers(Some("bytes 100-199/1000"), 100, "nas").is_ok()); + assert!(partial_answers(Some("bytes 100-199/*"), 100, "nas").is_ok()); + // No Content-Range: taken as asked, as the package fetcher does. + assert!(partial_answers(None, 100, "nas").is_ok()); + let e = partial_answers(Some("bytes 0-99/1000"), 100, "nas").unwrap_err(); + assert!(e.to_string().contains("answered from 0"), "{e}"); + assert!(partial_answers(Some("pages 1-2"), 100, "nas").is_err()); + } + #[test] fn an_untrusted_certificate_is_told_from_other_failures() { assert!(is_certificate_error( diff --git a/engine/crates/ps5upload-engine/src/remote_pkg.rs b/engine/crates/ps5upload-engine/src/remote_pkg.rs index b5c94aaad..6ccc30283 100644 --- a/engine/crates/ps5upload-engine/src/remote_pkg.rs +++ b/engine/crates/ps5upload-engine/src/remote_pkg.rs @@ -218,7 +218,7 @@ fn origin_changed_on_200( } /// `bytes 5-9/100` as (5, Some(100)); a `*` total is `None`. -fn parse_content_range(value: &str) -> Option<(u64, Option)> { +pub(crate) fn parse_content_range(value: &str) -> Option<(u64, Option)> { let spec = value.trim().strip_prefix("bytes")?.trim_start(); let (range, total) = spec.split_once('/')?; let start = range.split_once('-')?.0.trim().parse().ok()?; From 4ea0fb763a407a28a9a0c2734da17f2c29a5ab31 Mon Sep 17 00:00:00 2001 From: phantomptr Date: Wed, 25 Nov 2026 00:58:32 -0800 Subject: [PATCH 25/25] 12.6.29 release notes; catch up to 12.6.28 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GtiJiJdHq1hekoZ6vizvVT --- CHANGELOG.md | 29 +++++++++++++++++++++++ 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, 72 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c804f6f9..95b3e419e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ What's new in ps5upload, written for humans. ## Unreleased +**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. + +**Files** +- **Long names stay readable on a phone held sideways (#931).** In landscape, rows showed every action button and cut the name to nothing. A sideways phone now gets the same rows as upright: the name wraps, its type and size sit below, and the actions are behind ⋮. Computers keep one line per row. + +**Saves** +- **Using a received save keeps the file.** "Use this save" on a save someone sent you deleted the received file, even when the save was refused. It now reads the file where it is. +- **A failed backup zip no longer deletes the file you chose to replace.** The new zip is written in full first, then put over the old one. +- **Backup clean-up only touches its own temporary folders.** +- **A console removed while the backup list was being sent is no longer backed up.** +- **Restoring a backup on the PS5 only reads files inside that backup.** + +**Cheats and the PS5 helper** +- **Cheats never write into a system module mistaken for the game.** In some PS4 games another module sits where the game's own was expected; game patches no longer write there. +- **A game patch that can't be recorded is not left in the game**, so turning it off always takes it out. An over-long cheat value is refused instead of written cut short. +- **SDK Changer** no longer patches past the end of a short file, and stops 32 folders deep instead of running out of memory on a very deep game folder. + +**Fixes found in an audit** +- Remote Play keys with a stray character are refused instead of crashing the engine. +- WebDAV servers that answer with the wrong part of a file are caught, so a copy or install never gets wrong bytes. +- A game whose content ID looks like a path can no longer place the built package outside the folder you chose. +- A Play Together friend's player opens no new video decoder after it stopped (phones have only a few). +- A bug report for a console that hasn't been checked yet no longer shows another console's details. +- After sending the helper, every console's own status updates right away, not after the next check. +- Release tooling never marks an older version as the latest. + +## 12.6.28 + **Fake packages (FPKG)** - **Fake PS5 games play up to firmware 13.60.** A kstuff build with fake-package support up to 13.60 came out in November 2026. The app no longer warns that an installed fake PS5 game won't start on 11.61, 12.xx or 13.xx: the warning now appears only above 13.60. The fake-package note, Convert, the Payloads list, the FAQ and the README say that firmware above 11.60 needs that November 2026 kstuff (or newer). Convert again suggests a package, not an image, for a PS5 game on 13.60. - **A fake PS5 game that won't start says why.** On 11.61 to 13.60, a launch that fails now adds that a game from a fake package needs the November 2026 kstuff, so load it and press Play again. diff --git a/VERSION b/VERSION index 1868d5fbb..1e518e280 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -12.6.27 +12.6.28 diff --git a/client/package-lock.json b/client/package-lock.json index 537e0a1db..478b5654c 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1,12 +1,12 @@ { "name": "ps5upload-client", - "version": "12.6.27", + "version": "12.6.28", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ps5upload-client", - "version": "12.6.27", + "version": "12.6.28", "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 7cbdf9bad..679095089 100644 --- a/client/package.json +++ b/client/package.json @@ -2,7 +2,7 @@ "name": "ps5upload-client", "private": true, "type": "module", - "version": "12.6.27", + "version": "12.6.28", "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 c497ec8a6..9293fb8ce 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.27" +version = "12.6.28" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4752,14 +4752,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.27" +version = "12.6.28" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.27" +version = "12.6.28" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -4768,7 +4768,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.27" +version = "12.6.28" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4777,7 +4777,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.27" +version = "12.6.28" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -4788,7 +4788,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "crc32fast", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -4817,7 +4817,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.27" +version = "12.6.28" dependencies = [ "blake3", "libc", @@ -4834,7 +4834,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4868,7 +4868,7 @@ dependencies = [ [[package]] name = "ps5upload-desktop" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -4909,7 +4909,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4973,7 +4973,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.2", "crc32fast", @@ -4996,7 +4996,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.27" +version = "12.6.28" dependencies = [ "axum", "base64 0.23.1", @@ -5010,7 +5010,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.2", "blake3", @@ -5022,7 +5022,7 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.27" +version = "12.6.28" dependencies = [ "cc", ] diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 378c495a2..30cfe005b 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ps5upload-desktop" -version = "12.6.27" +version = "12.6.28" 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 901c77deb..c3201a193 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.27", + "version": "12.6.28", "identifier": "com.phantomptr.ps5upload", "build": { "beforeDevCommand": "npm run dev:vite", diff --git a/engine/Cargo.lock b/engine/Cargo.lock index 963dc1323..4ebdf0bbe 100644 --- a/engine/Cargo.lock +++ b/engine/Cargo.lock @@ -2561,7 +2561,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.27" +version = "12.6.28" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2570,14 +2570,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.27" +version = "12.6.28" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.27" +version = "12.6.28" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -2587,7 +2587,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.27" +version = "12.6.28" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2597,7 +2597,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.27" +version = "12.6.28" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -2608,7 +2608,7 @@ dependencies = [ [[package]] name = "ps5upload-apidoc" -version = "12.6.27" +version = "12.6.28" dependencies = [ "proc-macro2", "quote", @@ -2618,7 +2618,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "crc32fast", @@ -2628,7 +2628,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -2651,7 +2651,7 @@ dependencies = [ [[package]] name = "ps5upload-convert" -version = "12.6.27" +version = "12.6.28" dependencies = [ "libc", "ps5upload-archive", @@ -2666,7 +2666,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.27" +version = "12.6.28" dependencies = [ "blake3", "flate2", @@ -2686,7 +2686,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2720,7 +2720,7 @@ dependencies = [ [[package]] name = "ps5upload-ctest" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -2736,7 +2736,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2804,7 +2804,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.4", "blake3", @@ -2828,7 +2828,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.27" +version = "12.6.28" dependencies = [ "axum", "base64 0.23.1", @@ -2843,7 +2843,7 @@ dependencies = [ [[package]] name = "ps5upload-lab" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -2861,7 +2861,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.27" +version = "12.6.28" dependencies = [ "aes 0.9.4", "blake3", @@ -2873,14 +2873,14 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.27" +version = "12.6.28" dependencies = [ "cc", ] [[package]] name = "ps5upload-tests" -version = "12.6.27" +version = "12.6.28" dependencies = [ "anyhow", "ava1", @@ -2898,7 +2898,7 @@ dependencies = [ [[package]] name = "ps5upload-unrar" -version = "12.6.27" +version = "12.6.28" dependencies = [ "serde", "serde_json", diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 3da299fd5..6328b6541 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.27" +version = "12.6.28" [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 41d6e4cc2..5b1f768f4 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.27" +#define PS5UPLOAD2_VERSION "12.6.28" /* 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